Saturday, April 16, 2016

Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup

This error prompts you when you forget to initialize the apllication startup to fix this problem kindly use the given below line and add it under global.asax file of solution.

   GlobalConfiguration.Configuration.EnsureInitialized();

image

This is the complete stack trace which comes when you run an application.

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>

<StackTrace>
at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes() at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request) at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
</StackTrace>

</Error>

Hope it will sort out your issue.

Learn more about MVC and WebApi :

http://www.dotnetpiper.com/search/label/MVC

http://www.dotnetpiper.com/search/label/WCF%20and%20WebAPI

Tuesday, April 12, 2016

Explore Persistence Caching In Web API Using CacheCow.Server.EntityTagStore.SqlServer

Concert crowd

In the previous post Apply Caching in Web API Using CacheCow, I have shared about apply caching in-memory using CacheCow and its benefits. In the continuation of that post I’ll sharethoughts about persistence caching and its implementation. Caching always plays vital role when we have very frequent request model to server to fetch the data. Caching helps to reduce frequent hits to server and brings potential information in a minimal duration. Caching also helps to enhance Web API performance and reduce the load on server where Web API is hosted? EntityTag is an HttpHeader used for cache conditional request for resource.EntityTag is also pronounced as ETag.

Let’s take a simple example which uses ETag like “Client sends a request to Http server with Etag value that holds an updated value for cached resource, server identifies this with ETag value whether client has an already updated value for resource or it should revert with a latest copy back to client.

ETag working behavior and implementation

This section elaborates about ETag and its working behavior. Actually ETag is a string representation which is created by server against each request for a resource and also varies as value is updated for resource. For example,

Initially client sends a request http://localhost:57888/api2/employees/getdetails/5 to server and ask for employeeId 5, as per initial request it won’t be cached and server will return the fresh copy of the requested resource with some ETag value. We’ll see this in illustration down the level of this article. Later client send the same request to server with header If-None-Matchalong with ETag value which client has received in body response of earlier (e.g. TR6truy7) request If server finds equal ETag value for the requested resource than server responds Http not modified otherwise server will respond with new ETag value. Header “If-None-Match” works only with HttpGet and HttpDelete.

Installation of SqlServerEntityTagStore

HttpGet and HttpDelete works in similar manner. ThoughHttpPut works slightly in different nature. For this purpose we’ve to install “CacheCow.Server.EntityTagStore.SqlServer” from NuGet manager. Right click on solution and choose manage NuGet Manager.

Manager

Type CacheCow.Server.EntityTagStore.SqlServer in search, the following window will appears shown below. Click on install button.

install

Install of CacheCow library: Click on install button as show on above screen. As soon as you install the CacheCowlibrary you will findCacheCow.Server.EntityTagStore.SqlServer.dllin solution explorer under reference folder as depicted in screen below:

reference

Once the installation has done, we need to register CacheCowSQlServerEntitytagStore handler in WebApiConfig.cs file like shown below in depicted image.

installation

  1. //Configure HTTP Caching SqlServerEntityTagStore using Entity Tags
  2. varconnString = System.Configuration.ConfigurationManager.ConnectionStrings["CacheCowConnectionString"].ConnectionString; 
  3. vareTagStore = new CacheCow.Server.EntityTagStore.SqlServer.SqlServerEntityTagStore(connString); 
  4. varcacheCowCacheHandler = newCacheCow.Server.CachingHandler(config,eTagStore,""); 
  5. cacheCowCacheHandler.AddLastModifiedHeader = false; 
  6. config.MessageHandlers.Add(cacheCowCacheHandler); 

You can read more about how does handler works in ASP.NET Web API from here: Global and Per-Route Handler in Asp.Net WebApi

Once we are have done with installation and code segment placing, next step is to execute the following database script placed under {ProjectPath}\packages\CacheCow.Server.EntityTagStore.SqlServer.1.0.0\scripts.Onceexecute the database script there will be a table dbo.CacheState and 6 procedures as shown in depicted image below:

procedures

Each procedure works in different manner. Now I’ll perform PUT HTTP PUT request to understand how persistence caching works does.

We will see this complete step by step process to understand this here. I’m using fiddler for this purpose.

Step 1: Send the Initial request using Postman as shown below and press send button:

send

Response from server as given below in screen shot:

server

As soon as you receive a response for the latest request sent by client, there will be an entry relevant to resource in CacheState table exist in database as shown below in screen shot, and which is self-explanatory.

explantory

Step 2:
We will utilize this recently received ETag value for further communication in order to update the record using HTTP PUT verb.

Note
:
Kindly send If-Match parameterin header of request to update the resource. Kindly refer the image shown below: If- Match has the value "07aa73fe997d4c199f9b4774007778ac" which is sent by the server in last request.

CacheState
The status 200 means resource has updated .

Step 3:
In these steps the main objective is to identify that, does client has the latest copy of resource or not, which client is willing to update. So send the new request using the ETag value (not latest one) received in some old response. In short If the ETag value doesn’t match with the ETag value persist in database than will revert precompiled condition issue in response .Which means that client doesn’t have the latest copy to update the resource. So please get the latest copy of resource(Using HTTP GET) before sending the update request. Kindly refer the image shown below:

request

If I use the latest Etag value than it works fine and update the value.
done

Caching plays a vital role where client sends very frequent request for a resource. CacheCow one of the good providers to maintain caching in solution though there are lots of other variants exist. It is simple in use easy to install and works very effectively. The one fall point which I realized is that you have to keep the updated value of specific ETag sent by server response for each request

You can download the source code from link given below: 

Explore Persistence Caching In Web API Using CacheCow.Server.EntityTagStore.SqlServer

Learn more about MVC and WebApi :

http://www.dotnetpiper.com/search/label/MVC

 http://www.dotnetpiper.com/search/label/WCF%20and%20WebAPI

Saturday, April 9, 2016

The request contains an entity body but no Content-Type header
The Simple solution for such issue is please put “ Content-Type: application/json; charset=utf-8” in request.
Kinldy find a screen shot given below for reference:
image
Please refer www.dotnetpiper.com

Friday, April 8, 2016

Attribute Routing in ASP.NET Web API 2

Attribute Routing in ASP.NET Web API 2

Concert crowd

In the last article we’ve seen how can we inject multiple parameters to Web API method the same can be achieve using route attribute in Web API. Though there were little challenges which I will also describe in this article which may reduce your development time for sure. Excerpt from asp.net about routing,
"Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API. For example, you can easily create URIs that describe hierarchies of resources.The earlier style of routing, called convention-based routing, is still fully supported. In fact, you can combine both techniques in the same project".

The website also stated why Attribute Routing is required,
"The first release of Web API used convention-based routing. In that type of routing, you define one or more route templates, which are basically parameterized strings. When the framework receives a request, it matches the URI against the route template. One advantage of convention-based routing is that templates are defined in a single place, and the routing rules are applied consistently across all controllers".

Enabling Attribute Routing
To enable attribute routing, call MapHttpAttributeRoutes during configuration. This extension method is defined in the System.Web.Http.HttpConfigurationExtensions class. Kindy have a look at the code shown below as well as an image depicted below:

  1. namespace WebApiDemo 
  2.     public static class WebApiConfig 
  3.     { 
  4.         public static void Register(System.Web.Http.HttpConfiguration config) 
  5.         { 
  6.             config.MapHttpAttributeRoutes(); 
  7.             config.Routes.MapHttpRoute( 
  8.                 name: "DefaultApi", 
  9.                 routeTemplate: "api/{controller}/{action}/{id}", 
  10.                 defaults: new
  11.                 { 
  12.                     id = RouteParameter.Optional 
  13.                 } 
  14.             ); 
  15.         } 
  16.     } 

Here, I’ve a simple controller Employees which has the following Action Methods defined below and performs a set of statement like fetch a record from collection.GetDetails() action method takes one parameter and has its own specific routes while GetEmployeeByID() action method takes two parameters as arguments and has its own defined route.
GetDetails

  1. [Route("api/{employees}/{id}")] 
  2. public Employee GetDetails(int id) 
  3. return listEmp.First(e => e.ID == id); 

GetEmployeeByID

  1. [HttpGet] 
  2. [Route("api/{employees}/{id}/{userName}")] 
  3. [ActionName("GetEmployeeByID")] 
  4. public Employee Get(int id, string userName) 
  5. return listEmp.First(e => e.ID == id); 
  6.     SqlDataReader reader = null; 
  7.     SqlConnection myConnection = newSqlConnection(); 
  8.     myConnection.ConnectionString = @ "Server=.;Database=DBCompany;User ID=sa;Password=db@1234;"; 
  9.     SqlCommand sqlCmd = newSqlCommand(); 
  10.     sqlCmd.CommandType = CommandType.Text; 
  11.     sqlCmd.CommandText = "Select * from tblEmployee where EmployeeId=" + id + ""; 
  12.     sqlCmd.Connection = myConnection; 
  13.     myConnection.Open(); 
  14.     reader = sqlCmd.ExecuteReader(); 
  15.     Employee emp = null; 
  16. while (reader.Read()) 
  17.     { 
  18.         emp = new Employee(); 
  19.         emp.EmployeeId = Convert.ToInt32(reader.GetValue(0)); 
  20.         emp.Name = reader.GetValue(1).ToString(); 
  21.         emp.ManagerId = Convert.ToInt32(reader.GetValue(2)); 
  22.     } 
  23. return emp; 
  24.     myConnection.Close(); 
  25. } 

I run my application and verify that whether API is up or not. Kindly find given below image to identify this.
api
It shows API is running and ready to perform some action. Along with this I’ve Postman running aside where I paste the specific url. which meets the requirement as shown below:
normal
As soon as I click on the Send button it will go to the respective controller’s action to execute set of statements. This is the best benefits of Attribute routing is you can set any route as per you convenient. Like in the above URl there is no action method defined still it finds the right action method.This type of URI is difficult to create using convention-based routing(traditional routing model). Although it can be done, the results don’t scale well if you have many controllers or resource types
The output will be like given image shown below:
output
The same way you would have action which takes multi arguments than you can set the Attribute routing in such a way in below code segment.it makes it simple to understand and easily to execute.

  1. [HttpGet] 
  2. [Route("api/{employees}/{id}/{userName}")] 
  3. [ActionName("GetEmployeeByID")] 
  4. public Employee Get(int id, string userName) 
  5. }

I run an application again and verify that whether API is up or not. Kindly find given below image to identify this.
api
It shows API is running and ready to perform some action. Along with this I’ve Postman running aside where I paste the specific url (http://localhost:57888/api/employees/4/SachinKalia) which meets the requirement as shown below:
api
As soon as user click on send button it should reach to anticipated action method.
code
And the output will be like given below:
body
Attribute routing makes things easy and can create complex route in simpler way.
way
However there islittle issue which I confronted and would like to share with you. If you create route in such a way, that keeps parameter {controller} like in following route[Route("api/{controller}/{id}")]it prompts an error like “A direct route cannot use the parameter 'controller'. Specify a literal path in place of this parameter to create a route to a controller”. In simple words it should be a literal value.it throws same issue if you keep parameter {action} in route.
code
code
Which may consume your potential time during development?
way
Kindly add the following line in Global.asax file to initialize object as give below:

  1. GlobalConfiguration.Configuration.EnsureInitialized();  

If you don’t put this line in Global.asax file it throws an error as given below in screen shot.
code

Reference

You may downlaod the code from the given link here : Attribute Routing in ASP.NET Web API 2

Wednesday, April 6, 2016

Inject Multiple Arguments To A Web API Method

Inject Multiple Arguments To A Web API Method

Concert crowd

There can be various scenarios when you may have to pass multiple arguments in a Web API get method. Though there might be a few more ways, I have used the default configuration mapping which I am sharing here in this article.
We should pass arguments as additional parameters. It is especially easy with GET requests. This will work in Web API 1 & 2:
Here, I have a simple controller Employee which has the following Action Method defined below and performs a set of statements such as fetch a record from collection. GetEmployeeByID method takes two parameters as arguments.

  1. [ActionName("GetEmployeeByID")]   
  2. public class EmployeesController: ApiController   
  3. {   
  4.     public Employee Get(int ? id = null, string userName = null)   
  5.     {   
  6.         return listEmp.First(e => e.ID == id);   
  7.     }   

For this purpose, I have the following routing which is placed in WebApiConfig.cs as shown below in depicted image,
code

  1. public static void Register(System.Web.Http.HttpConfigurationconfig)    
  2. {   
  3.     config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new
  4.      {   
  5.         id = RouteParameter.Optional   
  6.     });   

I run my application and verify whether API is up or not. Kindly find the given below image to identify this.
asp.net
It shows the API is running and ready to perform some action. Along with this I have Postman running on the side where I paste the specific url which meets the requirement as shown below,
postman
As soon as I click on the Send button it will go to the respective controller’s action to executea  set of statements. The image depicted below shows that username argument has the value “Sachin Kalia”. In the same way, you can utilize such value at action level.
code
The output will be like given image shown below,
output
Note: Suppose you would like to get output in XML form instead of JSON, You just need to add header value in a request.
A simple example to receive output in a different form: Click on Headers button on the right side of Postman client screen. The following window will appear as shown below and fill the required details likeAccept: Application/xml in headers part.
postman
As soon as the user clicks on send button it should respond to the request in XML form as shown in below image.
postman
This is the sample code segment which fetches records from database and responds in WebAPi response form as shown below,

  1. [HttpGet]   
  2. // [Route("api/{employees}/{id}/{userName}")] 
  3. [ActionName("GetEmployeeByID")]   
  4. publicEmployee Get(int id, stringuserName)   
  5. {   
  6.     returnlistEmp.First(e => e.ID == id);   
  7.     SqlDataReader reader = null;   
  8.     SqlConnectionmyConnection = newSqlConnection();   
  9.     myConnection.ConnectionString = @ "Server=.;Database=DBCompany;User ID=sa;Password=Tpg@1234;";   
  10.     SqlCommandsqlCmd = newSqlCommand();   
  11.     sqlCmd.CommandType = CommandType.Text;   
  12.     sqlCmd.CommandText = "Select * from tblEmployee where EmployeeId=" + id + "";   
  13.     sqlCmd.Connection = myConnection;   
  14.     myConnection.Open();   
  15.     reader = sqlCmd.ExecuteReader();   
  16.     Employeeemp = null;   
  17. while (reader.Read())   
  18.     {   
  19.         emp = newEmployee();   
  20.         emp.EmployeeId = Convert.ToInt32(reader.GetValue(0));   
  21.         emp.Name = reader.GetValue(1).ToString();   
  22.         emp.ManagerId = Convert.ToInt32(reader.GetValue(2));   
  23.     }   
  24.     returnemp;   
  25.     myConnection.Close();   
  26. } 

This is one of the possible ways of doing this. In the next article we can achieve the same thing in a more linear fashion using Route Attribute.

Monday, April 4, 2016

Concert crowd
Hi Folks,
If you want to access the ModelState property in the View , you can use the ModelState in your Razor View as depicted below in image:

This is the source code as shown below:
  1. @model IEnumerable<MVCSample.Models.EmpRegistration> 
  2. @{ 
  3.     ViewBag.Title = "Verify"; 
  4. if (@ViewContext.ViewData.ModelState.IsValid) 
  5.     { 
  6.         ViewBag.Title = "Verify"; 
  7. if (TempData["EmployeeRegistration"] != null) 
  8.         { 
  9.             var tempDataEmployeeRegistration = TempData["EmployeeRegistration"]; 
  10.         } 
  11.     } 
    Thanks
To learn more about MVC please go to the following link.
MVC Articles
Thanks.
Enjoy coding and reading.