Friday, June 29, 2018

C# Entity Framework : Asynchronous Programming (async/await)


Asynchronous programming is a means of parallel programming in which a unit of work runs separately from the main application thread and notifies the calling thread of its completion, failure or progress. The main benefits one can gain from using asynchronous programming are improved application performance and responsiveness.

Entity Framework 6.0 supports asynchronous Programming, it means asynchronously you can query data and save data. By using async/await you can easily write the asynchronous programming for entity framework.

Example:

public async Task<Project> GetProjectAsync(string name)
{
 DBContext _localdb = new DBContext();
 return await _localdb.Projects.FirstOrDefaultAsync(x => x.Name == name);
}

In above example, asynchronously return the first element of records which satisfied condition or default value.

public async Task<Project> SaveProjectAsync(Project project)
{
 DBContext _localdb = new DBContext();
_localdb.Projects.Add(project);
 await _localdb.SaveChangesAsync();
 return project;
}

In above example, asynchronously saves all changes made in this context to the underlying database.

if you are doing asynchronous programming in entity framework, then the each async method should have own DBContext object otherwise if you are sharing dbcontext among multiple threads it could thrown exception


other links related to entity framework : 

Thanks for visiting!!

Monday, June 18, 2018

ASP.NET MVC : OutPutCache Action Filter

The outputCache, inbuilt action filter in MVC, enables you to cache the action result content by a MVC controller action. By default MVC Output cache is enabled. So for this you don’t need to do anything, if client will send same request, browser will not forward request to MVC controller and it returns previous cached result.

There are few major properties of OutPutCache attribute
·         Location
·         NoStore
·         Duration
·         VaryByParm
·         VaryByHeader

OutPutCache Location:

The output cache can be located on the browser client (where the request originated), on a proxy server (or any other server) participating in the request, or on the server where the request was processed. There are following possible values for output cache location and default value is ‘ANY’.
  • Any - the output cache can be located on client browser, proxy server.
  • Client - Cache will be stored on client browser as private.
  • Downstream - The output cache will be stored in any HTTP 1.1 cache-capable devices other than the origin server
  • None - The output cache will be disabled
  • Server - The output cache will be stored on the server where request was handled and processed.
  • ServerAndClient – the output cache will be stored on both server and client browser. 
Here is an example, output cache location is Client.

public class HomeController : Controller

    {
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*", Location = System.Web.UI.OutputCacheLocation.Client)]

public ActionResult LoadInfo(int pageNumber)

{

            List<Info> infos = new List<Info>();

            for (int i = 0; i < 10; i++)

            {

                int ivalue = rand.Next();

                Info info = new Info()

                {

                    Header = "Header" + ivalue,

                    InfoBody = "Body",

                };

                infos.Add(info);

            }

            return PartialView("_Info", infos);

}

    }


OutputCache NoStore:

NoStore is Boolean property, which tells that cache value will be stored or not. Default value is true.If NoStore value is true, it prevent the caching your data.

OutputCache Duration:

It tell the time duration (in second) that the cache data is stored.

OutputCache VaryByParm:

This property enables you to create different cached versions of the very same content when a form parameter or query string parameter varies.
  • VaryByParam = “City,CustomerID” :
     It creates different cached versions whenever any of the form or query string parameters in the list “City, CustomerID” varies.

[OutputCache(NoStore = true, Duration = 1000, VaryByParam = " City,CustomerID", Location = System.Web.UI.OutputCacheLocation.Client)]

public ActionResult GetCustomerInfo(int customerID, string city)

{

}

  • VaryByParam = "none" :
If you don’t want to store the Cache data, set VaryByParam = "none" it never cache data and always calls to repository to get data from database.

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "none", Location = System.Web.UI.OutputCacheLocation.Client)]

public ActionResult GetCustomerInfo(int customerID, string city)

{

}
  • VaryByParam = "*" :
It create a different cached version, whenever a form or query string parameters varies

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*", Location = System.Web.UI.OutputCacheLocation.Client)]

public ActionResult GetCustomerInfo(int customerID, string city)

{

}

Other related topics 
Thanks for visiting!! 

Wednesday, June 13, 2018

ASP.NET Web API : Steps To Improve ASP.NET Web API Performance

ASP.NET Web API is a .net framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

In this blog, we will discuss about 4 techniques to quickly improve the ASP.NET Web API performance.

1.     JSON serializer over XML:

JSON serializer use JSON Formatter and by default Web API provides media-type formatters for both JSON and XML.A media type formatter is used to read CLR objects from an HTTP message and write the CLR object in HTTP message body.
JSON serializer is highly recommend and it very faster compare to other Serlializer like XML.

2.     Asynchronous Task Based WebAPI :

     Async Web API action help to increase the number of concurrent HTTP requests Web API can handle. We can implement asynchronous programming for web api controller by using keywords async, Task, await

public class UserController : ApiController
{        public async Task<IHttpActionResult> Read()
{
var data = await _db.UserMaster.ToListAsync();
return Ok(data);
}
}

3.     Cache Data:
Web API  does not provide the output Caching attribute to cache web api response but you can Cache data in memory to process same future request without hitting database and it improve the performance of ASP.NET Web API and Microsoft provides the System.Runtime.Caching library for memory caching.  More information about web api caching

4.     Multi ResultSets:
Web API should return as many objects as you can in one Web API request and combining objects into one aggregate object and It reduce the number of HTTP request to web API

Example : Aggregate Object ‘UserScreenData’

class
 UserScreenData
{
public List<State> States { getset; }
public List<Country> Countries { getset; }
}

           Web API Method to return Aggregate object

public async Task<IHttpActionResult> GetScreenData()
{
UserScreenData screen = new Controllers.UserScreenData();
screen.State = await _db.State.ToListAsync();
screen.Countries = await _db.Country.ToListAsync();
return Ok(data);
}

Other ASP.NET WEB API related topics:
Thanks for visiting!!

Friday, June 1, 2018

Generate WCF Proxy by using Svcutil.exe

Svcutil.exe generates the service client proxy based on the Web Service Description Language (WSDL) from the service.



Open the visual studio command prompt and run the following command

Generate WCF Proxy by using Svcutil.exe


svcutil http://localhost/MyService/Service.svc  /Language=c#   /t:Code  /out:C:\Service\ServiceProxy.cs /config:C:\Service\ServiceProxy.config

/Out                      – specifies the file name for generated service proxy class, by default it derived from WSDL, service name
/Config                 –specifies the filename for the generated service configuration file and by default its output.config
/Language          -specifies the programming language to use for service proxy code generation and by default it is C#

When you run the above command, it generates the service proxy class “ServiceProxy.cs” at C:\Service and also generate service proxy config file “ServiceProxy.config” at C:\Service


Thanks for visiting!!

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...