Flat UI theme for ASP.NET MVC Web App

Nowadays Flat UI has become very popular with any developers and desginers, all major websites, web app and even mobile apps have shifted to Flat UI.

I recently saw this Flat UI – Free User Interface Kit and I created this template for ASP.NET MVC built website. The code has been downloaded for view from here GitHub – Flat-UI-Template-ASP.NET-MVC and can also demo it here.

Below are few screenshots from the template :

Flat-UI-3

Flat-UI-2

Flat-UI

Custom Authorization in ASP.NET MVC 3 using IAuthorizationFilter & FilterAttribute

Authorization filters : These implement IAuthorizationFilter and make security decisions about whether to execute an action method, such as performing authentication or validating properties of the request.

This post demonstrates how to create a custom authorization filter.

Step 1 : Create the Authorization Attribute and Filter:

///marker attribute
public class CustomAuthorizeAttribute : FilterAttribute { }

//filter
public class CustomAuthorizeFilter : IAuthorizationFilter
{
      private readonly ICustomerService _customerService;
      public CustomAuthorizeFilter(ICustomerService userService)
      {
          _customerService = userService;
      }

      public override void OnAuthorization(AuthorizationContext filterContext)
      {
          var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
          var actionName = filterContext.ActionDescriptor.ActionName;

          var authorized = false;
          var routeValues = GetRouteDataValues();
          int id = routeValues["id"] == null ? 0 : int.Parse(routeValues["id"].ToString());

          // build your custom logic using 
          // controllerName, actionName and id to set the 'authorized' flag.

          if(!authorized)
          {
              HandleUnauthorizedRequest(filterContext);
          }
      }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        Elmah.ErrorSignal.FromCurrentContext().
          Raise(new Exception("403 forbidden - " + filterContext.RequestContext.HttpContext.Request.RawUrl, null));
        filterContext.HttpContext.Response.StatusCode = 404;
        filterContext.Result = new ViewResult
        {
            ViewName = "~/Views/Error/PageNotFound.cshtml"
        };
    }

      public Dictionary<string, object> GetRouteDataValues()
      {
          return new Dictionary<string, object>(_contextBase.Request.RequestContext.RouteData.Values);
      }
}

Step 2: Binding:

this.BindFilter<CustomAuthorizeFilter>(System.Web.Mvc.FilterScope.Controller, 0).WhenActionHas<CustomAuthorizeAttribute>();

Step 3 : Decorate your Actions with the filter:

public class AccountController : Controller
{
    [CustomAuthorizeAttribute]
    public ActionResult MyPreciousAction()
    {
        // beep beep bepp ;)
    }
}

You may want to refer the below links I had used while creating this blog post. Cheers !

References:

How to use distinct() method on property of a class in C#

Distinct() is used to remove all duplicate items from a list or a collection. To use this method on a property of a class, below is an extension method which you could use :

public static class MoreLinq 
{
    public static IEnumerable<T> DistinctByProperty<T, TKey>(this IEnumerable<T> items, Func<T, TKey> property)
    {
        return items.GroupBy(property).Select(x => x.First());
    }

    // more such extensions can go in here...
}

Above I have created an extension method called “DistinctByProperty”, now you can use this property like as shown below…

var distinctEmails = customers.DistinctByProperty(x => x.EmailAddress);

References

Using Custom Validation Attributes in ASP.NET MVC

Background:

Model validations are required for ensuring that the received data we receive is valid and correct so that we can do the further processing with this data. We can validate a model in an action method. The built-in validation attributes are Compare, Range, RegularExpression, Required, StringLength. However we may have scenarios wherein we required validation attributes other than the built-in ones.

Custom Validation Attributes

Below is the code for the same, its pretty self-explanatory. In case of doubts or queries feel free to use the comments section.

public class EmployeeModel 
{
    [Required]
    [UniqueEmailAddress]
    public string EmailAddress {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int OrganizationId {get;set;}
}

To create a custom validation attribute, you will have to derive this class from ValidationAttribute.

public class UniqueEmailAddress : ValidationAttribute
{
    private IEmployeeRepository _employeeRepository;
    [Inject]
    public IEmployeeRepository EmployeeRepository
    {
        get { return _employeeRepository; }
        set
        {
            _employeeRepository = value;
        }
    }
    protected override ValidationResult IsValid(object value,
                        ValidationContext validationContext)
    {
        var message = "Email address already in use in this organization.";
        var model = (EmployeeModel)validationContext.ObjectInstance;
        var spec = new Specification<EmployeeModel>
        (m => m.EmailAddress == value && m.OrganizationId == model.OrganizationId);
        var emp = _employeeRepository.Get(spec);
        if(emp != null)
        {
            return new ValidationResult(message);
        }
        return ValidationResult.Success;
    }
}

Hope this helps. Cheers !

References

SqlBulkCopy – Bulk insert using SqlBulkCopy with C# & ASP.NET

So there was this requirement I was working on recently, where I had to make inserts of around 5,000 to 10,000 into a table all at one go. As I am quite used to using ORMs – Entity framework 5 : I initially implemented this bulk insert using Entity Framework 5. When testing my code with around 5,000 records, it took around 5-6 minutes for my code to insert all the 5,000 records.

6 minutes !!! NOT ACCEPTABLE. Enter SqlBulkCopy…

SqlBulkCopy lets you efficiently bulk load a SQL Server table with data from another source. The code is pretty self-explanatory, questions if any can be asked below in the comment section. Cheers !

FYI : With SqlBulkCopy now it took only 1 to 2 seconds for the same 5,000 inserts :D

Table-BulkCopy

public class Employee 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

public int BulkInsertIntoEmployees(List<Employee> employees)
{
    using (var scope = new TransactionScope())
    {
        string connectionString = "your-connection-string-here";
        var sqlConnection = new SqlConnection(connectionString);
        var sqlBulkCopy = new SqlBulkCopy(sqlConnection)
        {
            DestinationTableName = "Tbl_Employees",
            BulkCopyTimeout = 6000
        };
        var dataTable = GetDataTableForEmployees(employees);
        sqlConnection.Open();

        sqlBulkCopy.WriteToServer(dataTable);

        scope.Complete();
        sqlBulkCopy.Close();
        sqlConnection.Close();
        sqlConnection.Dispose();
    }
    return employees.Count;
}

private DataTable GetDataTableForEmployees(List<Employee> employees)
{
    var table = new DataTable();
    table.Columns.Add("Id", typeof(int));    
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Email", typeof(string));

    // note : the order of the field is very important
    // and should be same as the defined in table structure.
    employees.ForEach(data => table.Rows.Add(
                                        data.Id
                                        , data.Name
                                        , data.Email
                                        ));
    return table;
}

Introduction to RabbitMQ with C# .NET, ASP.NET and ASP.NET MVC with examples

This post assumes that you already have installed and configured RabbitMq on your system or on some server. Download .NET/C# RabbitMq’s client library from http://www.rabbitmq.com/dotnet.html or from rabbitmq-dotnet-client-3.1.4-dotnet-3.0.zip

If RabbitMq has been installed on your server, you can view the management screen using this url : http://server-name:15672/, more on this you will find on this link.

Incase you havent read about what RabbitMq is and how it works I strongly recommend you to read the following links first and then come back again to this post.

Lets get started, first you’ll need to import the libraries(dll) u just downloaded.

RabbitMq-AddReferences

You can use the following class I have created, modify them to suit your requirement. Instead of hard-coding the Username, Password and other fields its better you define them in your config file and read from there.

public static class BrokerHelper
{
    public static string Username = "guest";
    public static string Password = "guest";
    public static string VirtualHost = "/";
    // "localhost" if rabbitMq is installed on the same server,
    // else enter the ip address of the server where it is installed.
    public static string HostName = "localhost";
    public static string ExchangeName = "test-exchange";
    public static string ExchangeTypeVal = ExchangeType.Direct;
    public static string QueueName = "SomeQueue";
    public static bool QueueExclusive = false;
    public static bool QueueDurable = false;
    public static bool QueueDelete = false;
    public static string RoutingKey = "yasser";

    public static IConnection Connection;
    public static IModel Channel;
    public static void Connect()
    {
        var factory = new ConnectionFactory();
        factory.UserName = Username;
        factory.Password = Password;
        factory.VirtualHost = VirtualHost;
        factory.Protocol = Protocols.FromEnvironment();
        factory.HostName = HostName;
        factory.Port = AmqpTcpEndpoint.UseDefaultPort;
        Connection = factory.CreateConnection();
        Channel = Connection.CreateModel();
    }

    public static void Disconnect()
    {
        Connection.Close(200, "Goodbye");
    }

    public static bool IsBrokerDisconnected()
    {
        if(Connection == null) return true;
        if(Connection.IsOpen) return false;
        return true;
    }

    public static void Publish(string message)
    {
        if (IsBrokerDisconnected()) Connect();

        Channel.ExchangeDeclare(ExchangeName, ExchangeTypeVal.ToString());
        Channel.QueueDeclare(QueueName, QueueDurable, QueueExclusive, QueueDelete, null);
        Channel.QueueBind(QueueName, ExchangeName, RoutingKey);
        var encodedMessage = Encoding.ASCII.GetBytes(message);
        Channel.BasicPublish(ExchangeName, RoutingKey, null, encodedMessage);
        Disconnect();
    }
}

Almost Done ! Now that we have the above classes in place, publishing our message to rabbitMq will just be the following line of code :

BrokerHelper.Publish("Hello World");

Hope this helped.

References:

Using Twitter typeahead.js with ASP.NET MVC Web API

There are many auto-complete jQuery libraries I have used before, like jQuery UI’s Autocomplete, loopJ’s jQuery Tokeninput and Select2. But one of my colleague at work, recently introduced me to this jQuery plugin called twitter’s typeahead.js, it seemed to be good, so we decided to use it in one of our ongoing project.

So, What is typeahead.js ? typeahead.js is a fast and fully-featured autocomplete library. You can check out some of the basic examples from here or you can hit straight to the docs from here.

Lets get started with a few basic examples.

1. Things you’ll need to download: You can download the latest version of typeahead.js from here. Below are the js and css you’ll need to include :

<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.js" />
<link href="http://twitter.github.io/typeahead.js/css/examples.css" rel="stylesheet" />

2. Local data example: (fiddle)

<input type="textbox" placeholder="Search Song" id="search-box" />

<script type="text/javascript">
$('input#search-box').typeahead({
  name: 'name',
  local: ['yasser', 'shyam', 'sujesh', 'siddhesh', 'vaibhav']
});
</script>

typeAhead-local

3. MVC Web Api example :

public class SongController : ApiController
{

    public JsonResult GetSongs(string searchTerm)
    {
        List<Songs> songList = new List<Songs>();
        songList.Add(new Songs{ Name = "Addat", Artist = "Aatif Aslam", Year = "2007"});
        songList.Add(new Songs{ Name = "Woh Lamhey", Artist = "Jal - The band", Year = "2008"});
        songList.Add(new Songs{ Name = "Kryptonite", Artist = "3 Doors Down", Year = "2009"});
        songList.Add(new Songs{ Name = "Manja", Artist = "Amit Trivedi", Year = "2013"});
        songList.Add(new Songs{ Name = "Tum hi ho", Artist = "Arjit Singh", Year = "2013"});

        songList = songList.Where(m => m.Name.Contains(searchTerm)).ToList();

        return songList;
    }
}

public class Songs
{
    public string Name { get; set; }
    public string Year { get; set; }
    public string Artist { get; set; }
}

$("#search-box2").typeahead({
    name: 'songs',
    valueKey: 'Name',
    remote: {
        url: '/Song/GetSongs?searchTterm=%QUERY'
    }
}); 

Hope this helps :)

How to setup Elmah.MVC with ASP.NET MVC 4 ?

What is Elmah ? ELMAH is an open source project whose purpose is to log and report unhandled exceptions in ASP.NET web applications.

Why to use Elmah ? ELMAH serves as an unobtrusive interceptor of unhandled ASP.NET exceptions, those usually manifesting with the ASP.NET yellow screen of death.

So now we know what and why to use Elmah, Lets quickly get started on how to use Elmah with your ASP.NET MVC project.

Step 1: Right click on your solution and select the “Manage Nuget Packages” option Elmah - Step 1 - Manage Nuget Packages

Step 2: In the Nuget Package manager search for “Elmah” and install the Elmah.MVC nuget extension.Step 2 - Elmah - Elmah mvc nuget search The Nuget Package manager will download and add the required dlls and modify the web.config’s <appSetting> for Elmah to work. Step 2 - Elmah - Elmah mvc nuget web config

Step 3: That’s it !! Your Elmah is now ready to test. I have generated a 404 to test if my Elmah works, ELMAH can be accessed by this url : http://yourapp.com/elmah. Elmah - Output Screen 0Elmah - Output Screen 1

Hope this helps :)

Further Reading :

How to set SmtpClient properties using web.config

SmtpClient Class allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP). Instead of assigning properties of this class in C# , we can use the <system.net> element in the web.config as shown below :

<system.net>
    <mailSettings>
        <smtp from = "email@abc.com">
            <network 
                host = "mail.abc.com"
                port = "25"
                password = "password"
                userName = "email@abc.com"
                defaultCredentials = "false"
                enableSsl = "true"
             />
         </smtp>
     </mailSettings>
 </system.net>

The advantage of this approach is that we can change the mail settings without having to rebuild the entire application.

Hope this helps :)

Further Reading :
Sending Email with System.Net.Mail