How to attach a file from MemoryStream to a Mail in C#

Here’s a simplified snippet for sending an in-memory string as an email attachment (a CSV file in this particular case).
If you are trying this with PDF, put special mention on stream.position = 0. As it will make the writer write the file from starting position always.
Whatever the source-type you care coming with convert that to memory-stream and the use the memory stream to create the attachment.
That’s it!!

using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))    // using UTF-8 encoding by default
using (var mailClient = new SmtpClient("localhost", 25))
using (var message = new MailMessage("me@example.com", "you@example.com", "Just testing", "See attachment..."))
{
    writer.WriteLine("Comma,Seperated,Values,...");
    writer.Flush();
    stream.Position = 0;     // read from the start of what was written

    message.Attachments.Add(new Attachment(stream, "filename.csv", "text/csv"));

    mailClient.Send(message);
}

Dependency Injection in ASP.NET Web API 2

What is Dependency Injection?

A dependency is any object that another object requires. For example, it’s common to define a repository that handles data access. Let’s illustrate with an example. First, we’ll define a domain model:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Here is a simple repository class that stores items in a database, using Entity Framework.

public class ProductsContext : DbContext
{
    public ProductsContext()
        : base("name=ProductsContext")
    {
    }
    public DbSet<Product> Products { get; set; }
}

public class ProductRepository : IDisposable
{
    private ProductsContext db = new ProductsContext();

    public IEnumerable<Product> GetAll()
    {
        return db.Products;
    }
    public Product GetByID(int id)
    {
        return db.Products.FirstOrDefault(p => p.Id == id);
    }
    public void Add(Product product)
    {
        db.Products.Add(product);
        db.SaveChanges();
    }

    protected void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (db != null)
            {
                db.Dispose();
                db = null;
            }
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

 

Now let’s define a Web API controller that supports GET requests for Product entities. (I’m leaving out POST and other methods for simplicity.) Here is a first attempt:

public class ProductsController : ApiController
{
    // This line of code is a problem!
    ProductRepository _repository = new ProductRepository();

    public IEnumerable<Product> Get()
    {
        return _repository.GetAll();
    }

    public IHttpActionResult Get(int id)
    {
        var product = _repository.GetByID(id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }
}

 

Notice that the controller class depends on ProductRepository, and we are letting the controller create the ProductRepository instance. However, it’s a bad idea to hard code the dependency in this way, for several reasons.

  • If you want to replace ProductRepository with a different implementation, you also need to modify the controller class.
  • If the ProductRepository has dependencies, you must configure these inside the controller. For a large project with multiple controllers, your configuration code becomes scattered across your project.
  • It is hard to unit test, because the controller is hard-coded to query the database. For a unit test, you should use a mock or stub repository, which is not possible with the currect design.

We can address these problems by injecting the repository into the controller. First, refactor the ProductRepository class into an interface:

public interface IProductRepository
{
    IEnumerable<Product> GetAll();
    Product GetById(int id);
    void Add(Product product);
}

public class ProductRepository : IProductRepository
{
    // Implementation not shown.
}

Then provide the IProductRepository as a constructor parameter:

public class ProductsController : ApiController
{
    private IProductRepository _repository;

    public ProductsController(IProductRepository <span class="hiddenGrammarError" pre="">repository)  
    {
        _repository</span> = repository;
    }

    // Other controller methods not shown.
} 

This example uses constructor injection. You can also use setter injection, where you set the dependency through a setter method or property.

But now there is a problem, because your application doesn’t create the controller directly. Web API creates the controller when it routes the request, and Web API doesn’t know anything about IProductRepository. This is where the Web API dependency resolver comes in.

The Web API Dependency Resolver

Web API defines the IDependencyResolver interface for resolving dependencies. Here is the definition of the interface:

public interface IDependencyResolver : IDependencyScope, IDisposable
{
    IDependencyScope BeginScope();
}

public interface IDependencyScope : IDisposable
{
    object GetService(Type serviceType);
    IEnumerable<object> GetServices(Type serviceType);
}

The IDependencyScope interface has two methods:

  • GetService creates one instance of a type.
  • GetServices creates a collection of objects of a specified type.

The IDependencyResolver method inherits IDependencyScope and adds the BeginScope method. I’ll talk about scopes later in this tutorial.

When Web API creates a controller instance, it first calls IDependencyResolver.GetService, passing in the controller type. You can use this extensibility hook to create the controller, resolving any dependencies. If GetService returns null, Web API looks for a parameterless constructor on the controller class.

Dependency Resolution with the Unity Container

Although you could write a complete IDependencyResolver implementation from scratch, the interface is really designed to act as bridge between Web API and existing IoC containers.

An IoC container is a software component that is responsible for managing dependencies. You register types with the container, and then use the container to create objects. The container automatically figures out the dependency relations. Many IoC containers also allow you to control things like object lifetime and scope.

“IoC” stands for “inversion of control”, which is a general pattern where a framework calls into application code. An IoC container constructs your objects for you, which “inverts” the usual flow of control.

For this tutorial, we’ll use Unity from Microsoft Patterns & Practices. (Other popular libraries include Castle Windsor, Spring.Net, Autofac, Ninject, and StructureMap.) You can use NuGet Package Manager to install Unity. From the Tools menu in Visual Studio, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

Install-Package Unity

Here is an implementation of IDependencyResolver that wraps a Unity container.

using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;

public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer container;

    public UnityResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        this.container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List<object>();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose()
    {
        container.Dispose();
    }
}

If the GetService method cannot resolve a type, it should return null. If the GetServices method cannot resolve a type, it should return an empty collection object. Don’t throw exceptions for unknown types.

Configuring the Dependency Resolver

Set the dependency resolver on the DependencyResolver property of the global HttpConfiguration object.

The following code registers the IProductRepository interface with Unity and then creates a UnityResolver.

public static void Register(HttpConfiguration config)
{
    var container = new UnityContainer();
    container.RegisterType<IProductRepository, ProductRepository>(new HierarchicalLifetimeManager());
    config.DependencyResolver = new UnityResolver(container);

    // Other Web API configuration not shown.
}

Dependenecy Scope and Controller Lifetime

Controllers are created per request. To manage object lifetimes, IDependencyResolver uses the concept of a scope.

The dependency resolver attached to the HttpConfiguration object has global scope. When Web API creates a controller, it calls BeginScope. This method returns an IDependencyScope that represents a child scope.

Web API then calls GetService on the child scope to create the controller. When request is complete, Web API calls Dispose on the child scope. Use the Dispose method to dispose of the controller’s dependencies.

How you implement BeginScope depends on the IoC container. For Unity, scope corresponds to a child container:

public IDependencyScope BeginScope()
{
    var child = container.CreateChildContainer();
    return new UnityResolver(child);
}

Credit:

Thanks Mike Wasson(Mike Wasson is a programmer-writer at Microsoft) this injection. And yes you originally published this post(which is 100% yours till dinosaur appear again on earth.) on Asp.Net 🙂

MVC Recommended Resources And Tutorials

The articles and links below are a confronting effort of Rick Anderson, he works as a programmer writer for Microsoft, and mainly deals with Asp.net MVC, Azure and Entity Framework. You may find him tweeting something useful: @RickAndMSFT

Getting Started with ASP.NET MVC

New Featured Content

Microsoft Azure

Security

Membership, Authentication

OWIN and Katana

Data Access in ASP.NET MVC

Web Forms to MVC

Performance

AngularJS, Knockout, KnockoutJS

jQuery, Ajax, JSON, JavaScript

HTML5

Routing

Globalization, Internationalization and Localization

Azure and ASP.NET MVC

Mobile

Single Page Application (SPA)

Twitter, Facebook

Unit Testing , TDD, Repository Pattern and Unit of Work

Best Practices

Deployment

Rich text Editors for MVC

General

Forum Posts

Convert Decimal To String With Trailing Zeroes [ C# ]

convert decimal to string
It is very tedious to always convert string to decimal and decimal to string when we deal with objects in C#. And it is quite clumsy if your manager ask you to show a value with trailing zeroes(I really hate it, but not him).
So there may be situations when we want to show the decimal values as string with trailing zeroes to customer/ or UI as :

Let say we want to show 3 decimal places after precision for every number and number should look like below:

  • 1.30 >> 1.300
  • 1.1 >> 1.100
  • 1.00 >> 1
  • 1.01 >> 1.010

String.Format is the one method that really going to help us achieve this using the code below. So if you really wanna know about string format function check it out msdn reference for this.

And lets talk some code now:

        // pass a decimal number
		decimal Number = 1.12m;
		
		// define a scale to show after decimal point
		int scale = 10;
		
		//create a precision scale using scale defined
		string precisionScale = new String('0', scale);
            
		//define string format using precision scale
		string format = "{0:0." + precisionScale + "}";

        
		//format the number as string
		var numberAsString = string.Format(format, Number);

        //if number has zeroes after decimal point, return number itself    
		if (numberAsString.EndsWith(precisionScale))
        {
            //returning the number without zeroes, if it has all zeroes trailing after precision 
			Console.WriteLine(((int)Number).ToString());
        }
        else
		{
             Console.WriteLine(numberAsString);
		}

And if you got a different situation for doing this, why don’t you play with this fiddle

Cheers!!

Why EF5 Not Saving Decimal Precision Correctly

Entity Framework Not Saving Decimal Precision Correctly : DecimalPropertyConfiguration.HasPrecision  and there is now a DecimalPropertyConfiguration.HasPrecision Method to play with precision of specific property of a entity class. Let see some code:  public DecimalPropertyConfiguration HasPrecision( byte precision, byte scale ) where precision is the total number of digits the db will store, regardless of where the decimal point falls and scale is the number of decimal places it will store.  Therefore there is no need to iterate through properties and this can be called for any property as below:  public class EFDbContext : DbContext {    protected override void  OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)    {        modelBuilder.Entity<Class>().Property(object => object.property).HasPrecision(12, 10);          base.OnModelCreating(modelBuilder);    } } So basically you just have to add specific precision and scale using HasPrecision for the appropriate property of your class that tell your model to configure it this way.
Entity Framework Not Saving Decimal Precision Correctly

Let say you have a table in database with datatype decimal(18,3) which is most common datatype to store decimal values in SQL Server. You can easily change the precision(total char length of attribute ) and scale(number of char after decimal point) by going into design.

If yo are using Entity Framework ( >4.1 ) and then you try to save values like 1.111 to the field but it saves 1.110; Bummer!!!

Here the thing starts looking like weird. There are 2 important changes, from EF 4.1 onwards:

DbModelBuilder

the ModelBuilder class is now DbModelBuilder 

DecimalPropertyConfiguration.HasPrecision

and there is now a DecimalPropertyConfiguration.HasPrecision Method to play with precision of specific property of a entity class. Let see some code:


public DecimalPropertyConfiguration HasPrecision( byte precision, byte scale )

where precision is the total number of digits the db will store, regardless of where the decimal point falls and scale is the number of decimal places it will store.

Therefore there is no need to iterate through properties and this can be called for any property as below:


public class EFDbContext : DbContext
{
   protected override void  OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
   {
       modelBuilder.Entity<Class>().Property(object => object.property).HasPrecision(12, 10);

       base.OnModelCreating(modelBuilder);
   }
}

So basically you just have to add specific precision and scale using HasPrecision for the appropriate property of your class that tell your model to configure it this way.

Cheers!!