Creating user friendly strings for C# enums

Standard

Recently one of my colleague asked me question, he want to create a enum with string values. But C# doesn’t support string based enums, so here is the code snippet which will help you to associate string values to enums. This code is not using any custom attribute, instead it is using DescriptionAttribute class. Here is the enum, with the associated string values.

enum OrderStatus
{
    [Description("New Order")]
    NewOrder = 1,
    [Description("Order is processing")]
    Processing = 2,
    [Description("Order is shipped")]
    Shipped = 3
}

And here is the extension method, which returns the string value associated to the enum

public static class Extensions
{
    public static string Description(this Enum @enum)
    {
        var description = string.Empty;
        var fields = @enum.GetType().GetFields();
        foreach (var field in fields)
        {
            var descriptionAttribute = Attribute.GetCustomAttribute(field,
                typeof(DescriptionAttribute)) as DescriptionAttribute;
            if (descriptionAttribute != null && 
field.Name.Equals(@enum.ToString(), StringComparison.InvariantCultureIgnoreCase))
            {
                description = descriptionAttribute.Description;
                break;
            }
        }

        return description;
    }
}

You can get the description from enum like this.

var orderStatus = OrderStatus.NewOrder;
Console.WriteLine(orderStatus.Description());

Happy Programming :)

Update : Based on the comment from NDVictory, source code modified to return the exact value, earlier it was always returning the first value. Thank you NDVictory

HTML5 Application Cache and Azure websites

Standard

Today I faced any issue with HTML5 Application Cache (I will post about HTML5 Application Cache later), I deployed an HTML5 application to azure website, but I was getting error like this

Application Cache Error event: Manifest fetch failed (404)

Application Cache Error event: Manifest fetch failed (404)

Application Cache Error event: Manifest fetch failed (404)

This issue was due to the MIME type mapping was missing. Since it is website, developers don’t have direct control over the IIS. Here is the fix, using Web.Config file.

<system.webServer>
  <staticContent>
    <remove fileExtension=".appcache" />
    <mimeMap fileExtension=".appcache" 
              mimeType="text/cache-manifest" />
  </staticContent>
</system.webServer>

Sometimes we will get this issue while running in IIS Express as well.

Happy Programming :)

How to identify static class using reflection

Standard

Today someone asked me, how to find static class from list of types. I was against the implementation he was doing, but still I couldn’t find how to find static class. Later I did some research and I found like you need to look for IsAbstract and IsSealed properties of the type.

Here is source code, which identify the static class from the list of available types in the assembly.

class Program
{
    static void Main(string[] args)
    {
        var types = Assembly.GetExecutingAssembly().GetTypes();
        types.Where(x => x.IsAbstract && x.IsSealed).ToList()
            .ForEach(Console.WriteLine);
    }
}

static class StaticClass { }

sealed class SealedClass { }

interface Interface { }

class NormalClass { }

abstract class AbstractClass { }

If you run the above code, it will print the StaticClass name.

Happy Programming :)

Introduction to Dapper.NET ORM in ASP.NET 5

Standard

Dapper.NET is an open source, high performance Micro-ORM supporting Sql Server, MySQL, Sqlite, SqlCE, Firebird etc, from Stack Overflow team. Drapper provides extension methods for IDbConnection, so you require an instance of IDbConnection to use Dapper. To use Dapper, you need to include Dapper in the project.json file. In this post I am using Repository pattern and injecting the repository to the controller via constructor injection.

Here is the project.json file, the EntityFramework.SqlServer reference is required to use IDbConnection interface.

{
  "dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta2",
    "Microsoft.AspNet.Hosting": "1.0.0-beta2",
    "Microsoft.AspNet.Mvc": "6.0.0-beta2",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta2",
    "EntityFramework.SqlServer": "7.0.0-beta2",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta2",
     "Dapper":"1.38.0-*"
  },
  "commands": {
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5010",
  },
  "frameworks": {
    "aspnet50": {}
  }
}

Here is the constructor of the respository class. In this I am creating the instance of SqlConnection.

private IDbConnection _connection;
public EmployeeRepository()
{
	_connection = new SqlConnection("Server=.\\SQLEXPRESS; Database=DemoDb; Integrated Security=SSPI");
	_connection.Open();
}

Dapper extends the IDbConnection with Query method, which you can use to execute a query and map the result to a strongly typed object or list of objects.

public Employee Get(int? id)
{
	return _connection.Query<Employee>("SELECT * FROM Employees WHERE Id = @Id", new{ Id = id }).FirstOrDefault();
}

public IEnumerable<Employee> FindAll()
{
	return _connection.Query<Employee>("SELECT * FROM Employees");
}

You can use Execute method to execute DML queries as well to the Database.

public void Save(Employee employee)
{
	_connection.Execute("INSERT INTO Employees(Name,Designation,JoiningDate,Remarks) VALUES(@Name,@Designation,@JoiningDate,@Remarks)", employee);
}

public void Delete(Employee employee)
{
	_connection.Execute("DELETE FROM Employees WHERE Id=@Id", employee);
}

Dapper also supports Stored Procedures as well. You need to provide the command type parameter.

public void Update(Employee employee)
{
	_connection.Query("usp_UpdateEmployee", employee, commandType: CommandType.StoredProcedure);
}

You can use Dapper in ASP.NET or any .net applications, for that you need to include the Dapper nuget reference. You can find more details about Dapper from Dapper wiki

Happy Programming :)