Udemy

Beginners Guide for Creating GridView in asp.net mvc 5

Saturday, July 23, 2016 0 Comments A+ a-


Download Source Code


Introduction

In this post, we will be seeing how we can create a grid view in asp.net mvc, same like we have in asp.net web form. There are many their party both server side and also client side plugins written in jQuery are available which provide all the essential functionalities that we have in web forms which include searching, sorting and paging etc. It totally depends on the requirements of specific application if the search is needed client side or server side, same for the other functions.

You can download the source code from this link.

Libraries Available

Some of the libraries and plugins available are:
·         Grid.Mvc
·         MVCGrid.NET
·         PagedList.MVC
·         JQuery.Grid
·         JQuery Grid for ASP.NET MVC
·         JQuery DataTables

Using Jquery DataTables

All have their pros and cons, but personally I have found jQuery datatables to be a good choice. It is highly flexible. It supports pagination, instant-search, multi-column ordering. It also supports almost all the data sources to which it can be binded, some of which are:
·         DOM
·         JavaScript
·         Ajax
·         Server-side processing

One of the best option which I like in it is that it supports both client side searching, pagination, sorting etc, but it also provides option to have server side processing of it, as there can be case where we have too much data in database and in that case client side paging wouldn’t be a good option, just think millions of rows in a table and if they are binded to it using client side pagination, it will make or page unresponsive due to high amount of rows processing and html rendering.

We will first see an example of how we can implement it using client side processing. So, let’s get started. We will have a working grid with searching, sorting and paging at the end of the post which will look like:


First of all create database and table that we will be using in this post, Open SQL Management Studio and run the following script:

CREATE DATABASE [GridExampleMVC]  
 GO  
   
 CREATE TABLE [dbo].[Assets] (  
     [AssetID]                   UNIQUEIDENTIFIER NOT NULL,  
     [Barcode]                   NVARCHAR (MAX)   NULL,  
     [SerialNumber]              NVARCHAR (MAX)   NULL,  
     [FacilitySite]              NVARCHAR (MAX)   NULL,  
     [PMGuide]                   NVARCHAR (MAX)   NULL,  
     [AstID]                     NVARCHAR (MAX)   NOT NULL,  
     [ChildAsset]                NVARCHAR (MAX)   NULL,  
     [GeneralAssetDescription]   NVARCHAR (MAX)   NULL,  
     [SecondaryAssetDescription] NVARCHAR (MAX)   NULL,  
     [Quantity]                  INT              NOT NULL,  
     [Manufacturer]              NVARCHAR (MAX)   NULL,  
     [ModelNumber]               NVARCHAR (MAX)   NULL,  
     [Building]                  NVARCHAR (MAX)   NULL,  
     [Floor]                     NVARCHAR (MAX)   NULL,  
     [Corridor]                  NVARCHAR (MAX)   NULL,  
     [RoomNo]                    NVARCHAR (MAX)   NULL,  
     [MERNo]                     NVARCHAR (MAX)   NULL,  
     [EquipSystem]               NVARCHAR (MAX)   NULL,  
     [Comments]                  NVARCHAR (MAX)   NULL,  
     [Issued]                    BIT              NOT NULL,  
     CONSTRAINT [PK_dbo.Assets] PRIMARY KEY CLUSTERED ([AssetID] ASC)  
 )  
 GO

There is complete sql script file attached in the source code, so you can use it to create the database and table with sample data.

Now, create a new asp.net mvc 5 web application. Open Visual Studio 2015. Go to File >> New >> Project



From the dialog navigate to Web and select ASP.Net Web Application project and click OK.


From Templates, Select MVC, check the unit tests if you will write unit tests as well for your implementations and click OK.
Our project is created with basic things in place for us. Now we will start by creating the database context class as we will be using Entity Framework for the Data Access.

First of all we need to create model for the Asset table which we will be using for retrieving data using ORM.
In Model folder, create a new class named Asset:

using System.ComponentModel.DataAnnotations;

namespace GridExampleMVC.Models
{
    public class Asset
    {
        public System.Guid AssetID { get; set; }

        [Display(Name = "Barcode")]
        public string Barcode { get; set; }

        [Display(Name = "Serial-Number")]
        public string SerialNumber { get; set; }

        [Display(Name = "Facility-Site")]
        public string FacilitySite { get; set; }

        [Display(Name = "PM-Guide-ID")]
        public string PMGuide { get; set; }

        [Required]
        [Display(Name = "Asset-ID")]
        public string AstID { get; set; }

        [Display(Name = "Child-Asset")]
        public string ChildAsset { get; set; }

        [Display(Name = "General-Asset-Description")]
        public string GeneralAssetDescription { get; set; }

        [Display(Name = "Secondary-Asset-Description")]
        public string SecondaryAssetDescription { get; set; }
        public int Quantity { get; set; }

        [Display(Name = "Manufacturer")]
        public string Manufacturer { get; set; }

        [Display(Name = "Model-Number")]
        public string ModelNumber { get; set; }

        [Display(Name = "Main-Location (Building)")]
        public string Building { get; set; }

        [Display(Name = "Sub-Location 1 (Floor)")]
        public string Floor { get; set; }

        [Display(Name = "Sub-Location 2 (Corridor)")]
        public string Corridor { get; set; }

        [Display(Name = "Sub-Location 3 (Room No)")]
        public string RoomNo { get; set; }

        [Display(Name = "Sub-Location 4 (MER#)")]
        public string MERNo { get; set; }

        [Display(Name = "Sub-Location 5 (Equip/System)")]
        public string EquipSystem { get; set; }

        public string Comments { get; set; }

        public bool Issued { get; set; }

    }
}


Now Navigate to Models folder from Solution Explorer and open IdenityModels.cs file , we will add a property for the Asset table in the database context, which will be the Entity Framework representation of Asset table which we created using the script. Add new property in the ApplicationDbContext class:

public class ApplicationDbContext : IdentityDbContext
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public DbSet Assets { get; set; }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}


The above is the default entity framework settings for asp.net identity 2.0, we are extending it with our own tables for which we have added new DbSet for Asset table.

Now add an empty controller in Controllers folder named AssetController, which we will be using for all the Asset related work. Here is how it should look like:


public class AssetController : Controller
    {
        // GET: Asset
        public ActionResult Index()
        {
            return View();
        }
    }


Now we will install jQuery datatables that we will be using to build the gird, Go to Tools >> NuGet Package Manager >> Manage Nuget Packages for Solution and click it.


The package manager will get opened and by default it will be displaying the installed nugget packages in your solution, click the browser button and then search for jQuery datatables package, then select it and check the projects of the solution in which you want to install this package, in our case we are installing in it GridExampleMVC web project only as per requirement and then press the Install button.






Visual Studio will prompt to tell that it is going to modify the solution, you will have to press ok to continue the installation of the package.

After the nugget package is installed successfully, we need to include the necessary js and css of jquery datatables in the view where we will use it, for that we have to register the jquery datatables, for that open the BundleConfig.cs file locate in App_Start folder and add the following code for css and js files at the end:

bundles.Add(new ScriptBundle("~/bundles/datatables").Include(
                        "~/Scripts/DataTables/jquery.dataTables.min.js",
                        "~/Scripts/DataTables/dataTables.bootstrap.js"));

bundles.Add(new StyleBundle("~/Content/datatables").Include(
          "~/Content/DataTables/css/dataTables.bootstrap.css"));


After registering the scripts and css for datatables, we need to add them in our master layout which is by default _Layout.cshtml located in Views >> Shared which is defined in the _ViewStart.cshtml located in the same location.






Before writing the controller code, we need to configure the connection string for entity framework that will be used to connect database when it will be doing database operations i.e. running queries. So our connection string should be pointing to a valid data source so that our application won’t break when we run it.


For that open web.config and provide the connection string for the database. In config file you will find the under configuaration node connectionStrings, you will need to modify the connection string in that node according to your system. In my case it looks like:

<connectionstrings>
    <add connectionstring="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=GridExampleMVC;Integrated Security=True;MultipleActiveResultSets=true" name="DefaultConnection" providername="System.Data.SqlClient"/>
</connectionstrings>

Now in controller add a property for database context that we will be using for querying the database.

private ApplicationDbContext _dbContext;

public ApplicationDbContext DbContext
{
    get
    {
        return _dbContext ?? HttpContext.GetOwinContext().Get();
    }
    private set
    {
        _dbContext = value;
    }

}

This property we will be using to query the database with entity framework in all actions of the controller wherever needed.

Now in the index action, we will simply fetch all the rows of the table and pass it to view:

public ActionResult Index()
{
    return View(DbContext.Assets.ToList());
}


Our complete controller class code now looks like:

using GridExampleMVC.Models;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity.Owin;


namespace GridExampleMVC.Controllers
{
    public class AssetController : Controller
    {

        private ApplicationDbContext _dbContext;

        public ApplicationDbContext DbContext
        {
            get
            {
                return _dbContext ?? HttpContext.GetOwinContext().Get();
            }
            private set
            {
                _dbContext = value;
            }

        }

        public AssetController()
        {

        }

        public AssetController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        // GET: Asset
        public ActionResult Index()
        {
            return View(DbContext.Assets.ToList());
        }
    }
}

Here comes the view part now, where we will write code about how it should render as html. So create a view with Template Empty (Without Model) for the Index action and add the following code in it:

@model IEnumerable< GridExampleMVC.Models.Asset>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-primary list-panel" id="list-panel">
            <div class="panel-heading list-panel-heading">
                <h1 class="panel-title list-panel-title">Assets</h1>
            </div>
            <div class="panel-body">
                <table id="assets-data-table" class="table table-striped table-bordered" style="width:100%">
                    <thead>
                        <tr>
                            <th>Bar Code</th>
                            <th>Manufacturer</th>
                            <th>Model Number</th>
                            <th>Building</th>
                            <th>Room No</th>
                            <th>Quantity</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var asset in Model)
                        {
                            <tr>
                                <td>@asset.Barcode</td>
                                <td>@asset.Manufacturer</td>
                                <td>@asset.ModelNumber</td>
                                <td>@asset.Building</td>
                                <td>@asset.RoomNo</td>
                                <td>@asset.Quantity</td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@section Scripts
{
    
 <script type="text/javascript">
     $(document).ready(function () {

         $('#assets-data-table').DataTable();
     });
    </script>   
    
 }

Now run the application and you will see a grid with sorting, searching and filtering available in it, but there is one problem in it, which is it is processed on client side, all the data is rendered by view when action is called which may make page performance slow or increases page load time if there are a large number of rows coming.

We will be seeing in another post how we can make it more better by using server side paging, sorting and filtering which is surely a better approach where we have huge data set.

Source Code

The code is available at MSDN samples gallery for download. Please click here to download.
Udemy

Story of Equality in .Net - Part 4

Friday, July 08, 2016 0 Comments A+ a-


Background:

This article is in the continuation of the previous three articles regarding how Equality works in .Net, the purpose is to have the developers more clear understanding on how .Net handles equality for types. You may want to read the previous post as well:


Introduction

I hope that after reading the previous three posts, you have now understanding how the .Net framework deals with the Equality using the virtual Object.Equals method and for most of the value types and for few of Reference types using IEquatable<T>. In this post we will be discussing the c# equality operator provided by Microsoft. We will explore what the C# Equality operator does and how it works. After reading this post I hope you will have a better understanding what it means when you check for equality of two variable using == operator.

We will cover the following things:
  • We will be writing some code for comparing the == operator and Object.Equals behavior for same parameters to see what happens, and we will see that the result is same, but the mechanism used for both is different
  • We will see how C# equality operator works for primitive types.
C# also provides inequality operator as well, the syntax for which is !=. We will not be discussing this operator in detail because it is the negation of what equality operator does, so they are not that much different. For example, if a==b evaluates to true then a!=b should evaluate to false and vice versa. Apart from this difference both the operators work exactly the same way. So, keep in mind that everything that we will discuss in this post about equality operator also applies to the inequality operator as well, it will just inverse the return value.

The equality operator is used when we want to evaluate that if two of the variables are equal or not. A lot of developers have misconception that this operator is basically the same as Object.Equals method, and it is just a syntactical convenience provide by C# language.

This is not true actually. It is being designed in a way that it often gives the same result which by calling Object.Equals will give but that’s not always the case as the underlying mechanism is completely different.

== Operator and Primitive Types

We will see with example code that how the equality operator uses different mechanism in reference to Object.Equals method.

    class Program
    {
 
        static void Main(String[] args)
        {
            int num1 = 5;
            int num2 = 5;
 
            Console.WriteLine(num1.Equals(num2));
            Console.WriteLine(num1 == num2);
 
 
            Console.ReadKey();
        }     
 
 
    }



We are comparing two integers for equality using both way , first using Object.Equals overload for integer and second one using c# equality operator and we will examine the generated IL code which will help us understand how they are different in mechanism.
Of course when we will run this program it will evaluate to true for both the statements, and you can test it on your machine as well. As the result of both the statements is same this makes us believe that both are using Object.Equals and checking two integers for equality.



What Happens Behind the Scene

As we talked earlier that the == operator and Object.Equals work differently and we are going to see that how it is which will be a proof to what we talked earlier. We will examine the IL generated for both the statements after compilation.

One thing to note here is that before doing this you will need to build your project using Release build not debug, as debug code will generate a lot of unnecessary instructions that are helpful when we need to debug and also in debug build it will use Object.Equals implementation for both, so that will not help you to see what we will discuss next.

For doing that, Open the Visual studio command prompt, for opening it, go to Start Menu >> All Programs >> Microsoft Visual Studio >> Visual Studio Tools>> Developer Command Prompt




Type ildasm on the command prompt, this will launch the ildasm which is used  to look at the IL code contained in an assembly, it is installed automatically when you install Visual Studio, so you don’t need to do anything for installing it.



Browse the folder where your executable is and open it using File Menu. This will bring up the IL code of your executable.



Expand the Program class and double click the Main method, it will open up the intermediate language for Main method:




You don’t need to understand all the code written in it, if you have not seen IL seen before that may look complex to you, but you don’t need to understand all the instructions.
We will just look at the lines where the comparison is done for both ways to show you the difference, you can see the following line:

IL_0007:  call       instance bool [mscorlib]System.Int32::Equals(int32)

Here it is calling the Object.Equals implementation provided via IEquatable<int> for integer type, in IL we need to specify the method call using Fully Qualified name, so the above statements say to call Equals method which takes as int32 as parameter and method exists in System.Int32 type and this type exists in mscorlib assembly.

Now look at IL generated for second comparison which was done via equality operator, which is:

IL_0013:  ceq

You can see that call to Equals method in Int class is not called in this case, instead we have an IL instruction written ceq which says that compare the two values that are being loaded on the stack right now and perform equality comparison using CPU registers. So, C# equality operator uses ceq statement to do equality check for primitive types and it does not calls the Object.Equals implementation provided by that primitive type.




Summary

  • We compared the == operator with Object.Equals method in this post.
  • We saw that using == operator gives us the same result as calling Object.Equals but underlying mechanism of == operator is different in IL as compare to Object.Equals, which is that it does not uses the Object.Equals instead it uses probably cpu registers to do the comparison.
 
Udemy

Story of Equality in .Net - Part 3

Monday, July 04, 2016 1 Comments A+ a-


Introduction

After reading,

 Story of Equality in .Net - Part 1  
 Story of Equality in .Net - Part 2

you can see that Object.Equals method has two problems. One thing is that it lacks strong typing and for value types boxing needs to be done. In this post we will look at the IEquatable<T> interface which provides solution to these problems.

IEquatable<T> Interface

The generic IEquatable <T> exists for solving a slightly different problem with Equals method. The Equals method on Object type takes parameter of type Object. We know that this is the only type of parameter which is possible if we want Object.Equals to work for all types.
But Object is a reference type which means that if you want to pace a value type as an argument, the value type would be boxed which will be a performance hit which is bad. Typically when we define value type instead of reference type is because we are concerned of performance, so we always want to avoid this performance overhead of boxing and unboxing.
There is also another problem, having an object as parameter means that there is no type safety. For Example, the following code will compile without any problem:

    class Program
    {
 
        static void Main(String[] args)
        {
            Person p1 = new Person("Ehsan Sajjad");
 
            Program p = new Program();
 
            Console.WriteLine(p1.Equals(p));
 
 
            Console.ReadKey();
        }        
 
    }



There is nothing to stop me for calling Equals method on two difference type of instances. We are comparing instance of Person class with instance of Program and compiler didn’t stopped me doing that, which is clearly an issue as both are totally different types and there is no way they can meaningfully equal each other.


This was just an example, you should not be doing this kind of comparisons in your code, and obviously it would be nice if compiler could pick up this kind of situation, right now it cannot because Object.Equals method does not have strong type safety.
We can solve this boxing and type safety issue by having an Equals method that takes the type being compare as parameter, so for example we can have an Equals method on String which takes a string as parameter and   we can have an Equals method on Person class which takes a Person variable as parameter. This will solve both boxing and type safety problem nicely.

As we talked in the previous post about the problem of inheritance with the above approach. But there is no way to usefully define these strongly typed methods on System.Object, because System.Object does not know what types will be deriving from it.
So how can we make a strongly typed Equals method generally available to consume. Microsoft solved this problem by providing the interface IEquatable<T> which can be exposed by any type that wants to provide strongly typed Equals method. If we look at the documentation we can see that IEquatable<T> exposes just one method called Equals which returns a bool.


This serves  exactly the same purpose  as Object.Equals, but it takes the generic type T instance as a parameter and therefore it is strongly typed which means for value types there will be no boxing to be  done.

IEquatable<T> and Value Types

We can illustrate the IEquatable<T> interface with one of the simplest type integer.

        static void Main(String[] args)
        {
            int num1 = 5;
            int num2 = 6;
            int num3 = 5;
 
            Console.WriteLine(num1.Equals(num2));
            Console.WriteLine(num1.Equals(num3));

        }


We have three integer variables which we are comparing using Equals and printing the result on the console. If we look at the intellisense, we can see that there are two Equals method for int, one of them takes object as parameter and that’s the overridden Object.Equals method, other one takes an integer as parameter, this Equals method is implementation of IEquatable<int> by integer type, and this is the overload which will be used for comparison of the above example code, because in both Equals call we are passing integer as parameter not object, so the compiler will pick the overload defined for IEquatable<int> as it is the best signature match.


 This is obviously very unnatural way to compare integers, normally we just write like:

    Console.WriteLine(num1 == num2);

We have written the code via Equals method so that you can see that there are two Equals method out there. All primitive supports provide the implementation for IEquatable<T> interface. Just take the above example, int implements the IEquatable<int>.


Likewise other primitive types also implement IEquatable<T>. Generally IEquatable<T> is very useful for value types. Unfortunately Microsoft had not been very consistent about implementing it for non-primitive value types in the Framework Class Library, so you can’t always rely on this interface to be available

IEquatable<T> and Reference Types

.IEquatable<T> is not that much useful for reference types as it is for value types. Because for reference types there is not really any performance issues like we had for value types (boxing) which needs fixing and also for the reason that IEquatable<T> does not play nicely with inheritance.

But it is worth noting here that String which is a reference type does implements IEquatable<T>.  If you recall from the Part – 2, when we were demonstrating the Equals method for string we were explicitly casting the string variable to object.

        static void Main(String[] args)
        {
            string s1 = "Ehsan Sajjad";
            string s2 = string.Copy(s1);
            
            Console.WriteLine(s1.Equals((object)s2));

        }


That was to make sure that it call the Object.Equals override which takes object as parameter, if we don’t do that then compiler will pick the strongly typed Equals method and that method is actually the implementation of IEquatable<string> implemented by String . String is a sealed class so you cannot inherit from it, so the issue of conflict between Equality and Inheritance does not arise.

Obviously you would expect that when both Equals method are available on a type, the virtual Object.Equals method and the IEquatable<T> Equals method, they should always give the same result. That’s’ true for all the Microsoft implementations and it’s one of the things that is expected of you when you implement this interface yourself.
If you want to implement IEquatable<T> interface, then you should make sure that you override the Object.Equals method to do exactly the same thing as your interface method does and that makes sense, because it should be clear that if a type implements two versions of Equals that behave differently, then developers who will consume your type will get very confused.

Summary

·         We saw that we can implement IEquatable<T> on our types to provide a strongly typed Equals method which also avoids boxing for value types.
IEquatable<T> is implemented for  primitive numeric types but unfortunately Microsoft has not been very proactive  implementing for other value types in the Framework Class Library