Udemy

Story of Equality in .Net - Part 5

Monday, August 29, 2016 0 Comments A+ a-

Background:

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


In the previous post (i.e. Part 4) we compared the result of equality comparison of value type using == operator and Object.Equals method and the result was same but the mechanism for evaluating the equality is different as the IL generated for Object.Equals and == operator was different, which means that == operator does not call Object.Equals behind the scenes but it uses CPU’s registers to determine if the two value type variable are equal or not.

Introduction:

I hope that after reading the previous posts, you have now better understanding how the c# equality operator works for primitive types like int, float, double etc. In this post we will be focusing on how the c# equality operator and Equals method behave for reference types either they are framework class library types or user defined custom types. If you haven’t read previous parts and interested in reading from start about this topic, you can navigate all parts published before here:


== Operator and Reference Types 

If you recall from the previous post we saw an example using reference types for equality that it checks for reference equality, now we will modify the same example to see that equality operator compiles to what in case of reference types.

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


Now we will test using these both method of checking equality i.e. equality operator of c# and Equals method of Object type. If we runt his example we will see false  printed on the console two times which was expected result as Person is a reference type and those are two different instances of person with difference memory reference.

From the output we can easily deduce that both the equality operator and Equals method check for reference equality for reference types and that’s actually what’s happening.  So, Equality operator also checks reference equality not value equality for reference types just same like Equals method.

What Happens Behind the Scenes?

Now let’s examine the IL code generated for this example. 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.

The IL code for the above C# code looks like:


If we see the IL code for p1.Equals(p2), there are no surprises, it is comparing the equality by calling the virtual Equals method of Object, and the method signatures are pretty clear, as they say it requires an object, so this is actually a virtual call to Object.Equals method, this is the best type’s method match that C# compiler picked.

Now if we look at IL code generated for equality operator comparison of the objects. It is exactly the same instruction used which we saw for the integer example in the previous part. It is not calling any method to do the comparison, it is just loading both arguments to the evaluation stack and doing a ceq, which is a dedicated IL instruction to check for equality probably using the CPU’s hardware.

You might be thinking how does that achieve the reference equality?  We know that Person is a class which is a reference type which means whatever the variable of type Person contains is the address in memory of where the Person object is on managed heap.

Both arguments p1 and p2 are holding the memory addresses and you know addresses in memory are just numbers which means that they can be compared using the ceq statement for equality just like the integers you declare in the code. In fact this ceq is comparing the addresses to see if they are equal, in other words whether the reference is pointing to the same memory address is reference equality.

Summary

  • We saw that == operator and Object.Equals method call both work differently behind the scenes which we can verify by inspecting the IL code generated.
  • We saw that for Reference types as well 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 ceq instruction which do the  comparison of memory addresses using hardware instructions .

Udemy

Grid View with Server Side Filtering, Sorting and Paging in asp.net mvc 5

Tuesday, August 09, 2016 0 Comments A+ a-

 

Download Source Code


Background

In the previous post, we talked about how we can achieve a gridview type functionality in asp.net mvc same like we have in asp.net webforms. We saw that how easy it is to implement a gird using jQuery datatables plugin which provides vital features such as searching, sorting and pagination.


One thing to notice in the previous post is that all the features provided by the plugin are client side which means that all the data is loaded in the page first and then the plugin handles the data on client side for searching, pagination and sorting which is fine if the result sets coming are not very big, but it can cause problems if the table is too big or the data is not that much but grows gradually as applications is used, so if that is the case this way of creating the grid would fail in long run.

Introduction

In this post, we will be seeing how we can implement the server side pagination, searching and sorting which is of course a better approach in the long run or for the applications where datasets are too big.
We will be modifying the source code from the previous post for this, so let’s get started.

First of all, we need to install datatables.mvc5  from nuget package manager, it is a datatables model binder to controller implemented by Stefan Nuxoll. You may be thinking why we need this package, it is because the binder will provide strongly typed model posted at controller, which will help us to avoid reading the request parameter and will also save us from type-casting the parameters from Request as all the parameters posted in Request object are not type safe so we have to convert them manually to their destination type, which will help the developers to focus on business logic instead of playing around with Http parameters, checking them and casting to the right type.
 The good thing about this binder is that you can add custom parameters sent in the request if your business requirements need that.
 You can add your own custom parameters if needed by providing your own implementation of IDataTablesRequest, and you will also need to override the BindModel and MapAdditionalColumns method of it.

So now we will install datatables.mvc5 , 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 Browse button and then search for datatable.mvc5 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.



Select the correct package which is in the above screenshot the top one returned in the search results and install it.



If the installation of package goes successful, you will be able to see in the References of the project:



Go to the Index.cshtml file and update the html of the view by removing the thead and tbody elements of the table. Your updated html would be:

<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%;">
                </table>
            </div>
        </div>
    </div>
</div>

We removed the head and body of table because it would get generated by the datatables plugin itself. Now we will have to update the jQuery datatables initialization so that it loads data from server side via ajaxing.

For that add the following code in the Index.cshtml view:

@section Scripts
{
    
<script type="text/javascript">
        var assetListVM;
        $(function () {
            assetListVM = {
                dt: null,

                init: function () {
                    dt = $('#assets-data-table').DataTable({
                        "serverSide": true,
                        "processing": true,
                        "ajax": {
                            "url": "@Url.Action("Get","Asset")"
                        },
                        "columns": [
                            { "title": "Bar Code", "data": "BarCode", "searchable": true },
                            { "title": "Manufacturer", "data": "Manufacturer", "searchable": true },
                            { "title": "Model", "data": "ModelNumber", "searchable": true },
                            { "title": "Building", "data": "Building", "searchable": true },
                            { "title": "Room No", "data": "RoomNo" },
                            { "title": "Quantity", "data": "Quantity" }
                        ],
                        "lengthMenu": [[10, 25, 50, 100], [10, 25, 50, 100]],
                    });
                }
            }

            // initialize the datatables
            assetListVM.init();

        });

</script>
    
 }

After this, we will write the Get action code in the AssetController, for that first we need to reference the System.Linq.Dynamic namespace as we will be using the methods provided for dynamic linq in our action, for that go to Nuget Package Manager once again and search for System.Linq.Dynamic package and install it in your project.



After installing the package, go to AssetController and write the Get action implementation which will be :

public ActionResult Get([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel)
{
    IQueryable<asset> query = DbContext.Assets;
    var totalCount = query.Count();

    #region Filtering
    // Apply filters for searching
    if (requestModel.Search.Value != string.Empty)
    {
        var value = requestModel.Search.Value.Trim();
        query = query.Where(p => p.Barcode.Contains(value) ||
                                 p.Manufacturer.Contains(value) ||
                                 p.ModelNumber.Contains(value) ||
                                 p.Building.Contains(value)
                           );
     }

     var filteredCount = query.Count();

     #endregion Filtering

     #region Sorting
     // Sorting
     var sortedColumns = requestModel.Columns.GetSortedColumns();
     var orderByString = String.Empty;

     foreach (var column in sortedColumns)
     {
        orderByString += orderByString != String.Empty ? "," : "";
        orderByString += (column.Data) + (column.SortDirection == Column.OrderDirection.Ascendant ? " asc" : " desc");
     }

     query = query.OrderBy(orderByString == string.Empty ? "BarCode asc" : orderByString);

     #endregion Sorting

     // Paging
     query = query.Skip(requestModel.Start).Take(requestModel.Length);


     var data = query.Select(asset => new
     {
        AssetID = asset.AssetID,
        BarCode = asset.Barcode,
        Manufacturer = asset.Manufacturer,
        ModelNumber = asset.ModelNumber,
        Building = asset.Building,
        RoomNo = asset.RoomNo,
        Quantity = asset.Quantity
     }).ToList();

     return Json(new DataTablesResponse(requestModel.Draw, data, filteredCount, totalCount), JsonRequestBehavior.AllowGet);
}


Now build the project, and run it in browse to see the working grid view with server side filtering, paging and sorting in action.

Source Code

The source code is available for download from MSDN code samples gallery here