Thursday 19 November 2015

Json Deserilize Model Binding Async,Await

Json Deserilize Model Binding Async,Await

Sample Code is here :

  public async Task<List<Models.Emp>> DemoAsyn()
        {
var obj = await new WebClient().DownloadStringTaskAsync("http://api.androidhive.info/contacts/");
string str = obj.Split('[').GetValue(1).ToString().Split(']').GetValue(0).ToString();
List<Models.Emp> list = JsonConvert.DeserializeObject<List<Models.Emp>>("[" + str + "]");
return View(list);
        }


Monday 16 November 2015

SqlDependency


SqlDependency

In this fast moving world of technologies , there is need  to share data between instances, as in a chat program, or receive constant updates like scores, as in a stock broker application.

Sqldependency will fulfill this, as this provides the instant trigger if the event when ever there is a change in the database entries .

Among the many new features for SQL Server 2012 are Service Broker and Query Notifications. The Service Broker is a queued, reliable messaging mechanism that is built into SQL Server 2012 and provides a robust asynchronous programming model.

Query Notifications allow applications to receive a notice when the results of a query have been changed. This improves performance by not having to periodically query the database for changes. 

To use SqlDependecy, the database must support a Service Broker. If the database was not created with this option enabled, you will need to enable it.

  ALTER DATABASE database SET ENABLE_BROKER

SqlNotificationRequest can also be used to provide the same services, however, it requires a good deal of manual setup. SqlDependency sets up the plumbing for you. While it is simpler to implement, it obviously doesn't allow the degree of customization that may be necessary for some applications, andSqlNotificationRequest would be the best choice.

A dependency is created between the application and the database via a SqlCommand. Before that can be established, the SqlDependency must be started for this session.


Sample code to use sqldependency

  using (SqlCommand command = new SqlCommand(query, connection))
            {
                command.Notification = null;
                SqlDependency dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    reader.Read();
                    message = reader[0].ToString();
                    stat = reader[1].ToString();
                }
            }


 private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            
            if (e.Info == SqlNotificationInfo.Insert)
            {
               //function code
            }

            if (e.Info == SqlNotificationInfo.Update)
            {
               //function code
            }

        }


Wednesday 30 September 2015

Async/Await in MVC 5 and Performance test


Asynchronous feature in MVC 5 


No one wants to develop a lazy loading  website and unresponsive application , but it takes some time to go with maximum performance .To use the latest , efficient techniques and features available will make us help in  building the robust application .  

Asynchronous  feature is one of the important feature used to develop a maximum utilization of the threads running in thread pool in server side .


Comparison of Traditional way of Approach and Modern way:


Traditional Approach  : 

In this approach , the threads in the thread pool will be blocked until there is a request processed completely .It means the server takes more time to process a request for database operations request will block the thread until the response comes .



Here each request is associated with one different thread and blocks the thread .
In real scenario if there are more request comes , then if all threads are blocked for some reasons then for new request to process it will take time until there is a free thread to associate .

Modern Approach  :


When request comes , the request is first associated with the thread in the thread pool ,
but if the request take more time for its database operation then the thread is released.
Once the entire operation is done, the request will again assiciate the thread and fulfills the request .

The advantage of using the asynchronous feature is when there is delay in the database operations to perform when request comes . Threads will de-associate then the released threads may be used by other request which comes in but where as in traditional approach there is a blockage for the thread which deceases the performance .

Here is the benchmark test for testing the performance  : 

Note  : The test is dependent on the machine you run.




Traditional Approach :

To server 1000 request at particular time , the time taken to finish all the requests is766 ms.












Modern Approach :

To server 1000 request at particular time , the time taken to finish all the requests is 366 ms.














Asynchronous Programming in MVC 5 

Controller method to perform asynchronously :

//Traditional Way of approach , using this the thread will be blocked until the request is fulfilled.
 public  ActionResult Traditional()
        {
            var listofrecords =  entities.ToList();
            return View(listofrecords);
        }


//Modern Way of approach , in this case the thread is not blocked instead the thread is released if there is a long processing for Database operations to perform .

 public async Task<ActionResult> ModernApproach()
        {          
            var listofrecords = await entities.ToListAsync();
                return View(listofrecords);
        } 

To have a website to be load faster and with minimum usage of the resources and traffic .
I recommend to use this feature for your upcoming projects.







Monday 28 September 2015

Calling Controller Method from Javascript using $.ajax in MVC 5

Javascript function to call Controller Method 

@section  Scripts
{


<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

   <script type="text/javascript">

       $(document).ready(
           function () {
               $("#btn").click(
                   function () {

                       $("#showcontent").text("Loading...Ajax content").css({ "color": "red" });

                       $.ajax(
                           {
                               url: "/home/AjaxCall",
                               type: "GET",
                               success : function(data)
                               {
                                   $("#showcontent").text(data).css({ "color": "green" });
                               }
                            }
                           );

                   }

                   );

           }

           );

    </script>

}

<h2 id="showcontent"></h2>
<button id="btn" >Show details</button>

Add these lines  in any of your sample views and mention the controller method in the url section of ajax block which is highlighted ..

Here is the controller method  




 [System.Web.Mvc.HttpGet]
        public string AjaxCall()
        {
            Thread.Sleep(5000); // Thread is for showing the ajax loading call on view
            return "AjaxCall";

        }

Use this code in your controller ..

Output : 

1. Initially the view will look like this  :


 2. After Pressing the Show details , the ajax call will go to the controller.
      then the below screen will appear.



   3. Once the call is reached to controller and after 5 seconds  , the controller method will return with        'AjaxCall'. '


 



Monday 21 September 2015

ASP.NET MVC 6

Features of  ASP.NET MVC 6

MVC 6  is simply a next version of MVC 5 , which means initially there was different framework are included and used to develop the integrated web application which consists of  WEB API, MVC and web forms .

But in MVC 6 , all the individual frameworks are combined into one framework , which reduced the duplicates of the classes in each separate framework .

MVC 6 is one ASP.NET , which includes MVC architecture , web forms and web api in one framework and makes it simple by using the one framework instead of multiple frameworks to understand .




Sunday 12 January 2014

Signal r 2.0


SignalR is an open-source .NET library for building web applications that require live user interaction or real-time data updates. Examples include social applications, multiuser games, business collaboration, and news, weather, or financial update applications. These are often called real-time applications.

Friday 20 December 2013

Mvc History

Asp.Net MVC is a Framework built on the top of Microsoft .Net Framework to develop web application.This Framework is used with a clean separation of the code.
This will help developer for easy manageable code.
Asp.Net MVC is a more efficent open source framework for building web applications.
The list of Asp.net Mvc framework versions Released so far.

First Release : Asp.net MVC1
Released on Mar 13, 2009
compatible version .Net 3.5 framework
Html Helpers
Ajax helpers
Routing

Second Release : Asp.net MVC2

Released on Mar 10, 2010
Compatible versions .Net 3.5, 4.0
Data Annotations Attribute support
Client-side validation
Automatic scaffolding & customizable templates
Asynchronous controllers

Third Release :Asp.net MVC3

Released on Jan 13, 2011
Compatible versions 4.0
Razor view engine
Data Annotations in Advance
Compare Attribute
Dependency Resolver Entity Framework Nuget Support

Fourth Release : Asp.Net MVC4

Released on Aug 15, 2012
Compatible versions 4.0, 4.5
ASP.NET Web API
SignalR-Real time Communication
Enhancements to default project templates
Display Modes
Asynchronous Controllers
Bundling and minification

Fifth Release : Asp.Net MVC5 Preview

Released on Jun 26, 2013
Compatible versions .Net 4.5, 4.5.1
ASP.NET Scaffolding
Bootstrap in the MVC template
ASP.NET Web API2
SignalR- 2.0 Real time Communication