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

How to create a Google Chrome App?

Step 1: Create the manifest

Every extension, installable web app, and theme has a JSON-formatted manifest file, named manifest.json, that provides important information. First create your manifest.json file using the format shown here.

{
  "name": "Code Formatter",
  "description": "A chrome plugin to format your HTML, CSS, JS, SQL or JSON code.",
  "version": "0.1",
  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  },
  "icons": { "16": "icons/logo.png", "128": "icons/logo-128.png"}
}

Step 2: Create the background script

Next create a new file called background.js with the following content:

chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('window.html', {
    'bounds': {
      'width': 400,
      'height': 500
    }
  });
});

In the above sample code, the onLaunched event will be fired when the user starts the app. It then immediately opens a window for the app of the specified width and height. Your background script may contain additional listeners, windows, post messages, and launch data, all of which are used by the event page to manage the app.

Step 3: Create a window page

Create your window.html file:

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div>Hello, world!</div>
  </body>
</html>

Step 4: Create the icons

Copy these icons to your app folder: – logo-128.png and logo-16.png

Step 5: Launch your app

To load your app, bring up the apps and extensions management page by clicking the settings icon and choosing Tools > Extensions. Make sure the Developer mode checkbox has been selected. Click the Load unpacked extension button, navigate to your app’s folder and click OK.

CodeFormatter-Upload CodeFormatter-ChromeApp CodeFormatter-AppLaunch

ReferencesGoogle Chrome – Create Your First App

Installing BugTracker.NET on Windows 7 with IIS 6

About BugTracker.NET

BugTracker.NET is a free, open-source, web-based bug tracking and general purpose issue tracking application. It is in daily use by thousands of development, customer support, and help desk teams around the world.

Prerequisites:

  • ASP.NET 2.0 or above
  • IIS 6 or 7
  • SQL Server 2005 express or above

Steps

  1. Download the the .zip file from here and unzip it to say “C:\btnet_3_6_2”.
  2. Open IIS, add a new website, give the site a name (say “btnet”) and point the website to the folder “C:\btnet_3_6_2\www” we just extracted our zip file to. Btdn-add-websiteMake sure your application pool for this website is set to .NET Framework V4.0
  3. Start your SQL Server Management Studio
    • Create database “btnet”
    • Run “C:\btnet_3_6_2\www\setup.sql” on this database
  4. Modify your web.config
    • Open “C:\btnet_3_6_2\www\web.config” in a text editor
    • Goto line 148 and change the connection string server, database username and password : <add key="ConnectionString" value="server=(local);database=btnet;user id=btnet;password=btn3t;Trusted_Connection=no;"/>.
  5. Now browse to the website you created and you should get the window like the one shown below Btdn-setup1
  6. Login using username as “admin” and password also as “admin”. Once logged in, go to the Admin Tab > Users > Add New User. Btdn-add-user1
    • Type in your username, password, email address and other optional settings.
  7. That’s it and your btnet is ready to be used ! In case of doubts/queries feel free to use the comment section.

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;
}

SimpleDropDownEffects – A jQuery plugin for transforming select drop-down lists with some amazing expanding effects.

I recently bumped into this page on GITHUB and found this simple and easy to use jquery plugin which transform a simple select drop down list to a drop down list with some amazing jquery effects.

Untitled

Above shown screenshots are taken from this demo page. I personally found the plugin very easy to use, let me quickly show you how to set this plugin up, heres a link to the fiddle i created : http://jsfiddle.net/yrshaikh/B3y8e/.

Step 1: Download the zip package from its github page and inlcude the js and css file in your project, there is one js file named jquery.dropdown.js which you need to include you may also want to include the modernizr.js incase you haven’t already.

Step 2: Your HTML

<select id="cd-dropdown" class="cd-select">
    <option value="-1" selected>Actions</option>
    <option value="1">View</option>
    <option value="2">Edit</option>
    <option value="3">Delete</option>
</select>

Step 3: Jquery

$('#cd-dropdown').dropdown();

And voila its done ! dropdown demo

I have also created a fiddle for this here : http://jsfiddle.net/yrshaikh/B3y8e/ hope this helps :)

Cheers !