Archive | May 2013

Learning ASP.NET SignalR – Part 1

Code Wala

Hello All,

Today I am going to discuss one of the new technologies that changed the way we used to think about How the web works. I’ll be writing a series on this technology and this post is first part of it.

You must have been working on the ASP.NET for long or might be since inception. And till date (or till this technology got introduced) , You got to know from every where that Web is stateless. A webpage is recreated every time from scratch it is posted back to server. In traditional web programming, all the information within the page and control gets wiped off on every postback.

I have taken the above lines from one of my post which I had written long back.

View original post 629 more words

Advertisements

Implementing Entity Tag in ASP.NET Web API

Entity tags are a way of incorporating caching into the http protocol. When a server returns the response it attached a unique identifier (ETag) to the response back to the client, which represents the state of the object. So when the client makes a request for the same response, it will send the ETag in its request using the If-None-Match header and the server will use to determine whether to send a new response or response with a 304 (Not modified response which the gives the client a go ahead to use the local cache copy) The main advantage for this is to save the bandwidth since if the response has not changed there is no need to resend the same response as before. In this article we will implement ETag using action filter and so we will extend ActionFilterAttribute. Here is the full implementation

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WebAPIETag.Models
{
public class EnableETag : ActionFilterAttribute
{
//This could be from a network source e.g database
private static ConcurrentDictionary<string, EntityTagHeaderValue> _etTagHeaderValues =
new ConcurrentDictionary<string, EntityTagHeaderValue>();

public override void OnActionExecuting(HttpActionContext actionContext)
{
//Get the request
var request = actionContext.Request;
if (request.Method == HttpMethod.Get)
{
var key = GetKey(request);

//Get if If-None match header
ICollection clientEtags = request.Headers.IfNoneMatch;

if (clientEtags.Count > 0)
{
EntityTagHeaderValue etag = null;
if (_etTagHeaderValues.TryGetValue(key, out etag) && clientEtags.Any(t => t.Tag == etag.Tag))
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.NotModified);
SetCacheControl(actionContext.Response);
}
}
}
}

private void SetCacheControl(HttpResponseMessage httpResponseMessage)
{
httpResponseMessage.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromSeconds(6),
MustRevalidate = true,
Private = true
};
}

private string GetKey(HttpRequestMessage request)
{
return request.RequestUri.ToString();
}

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
var request = actionExecutedContext.Request;
var key = GetKey(request);

EntityTagHeaderValue entityTag;

if (!_etTagHeaderValues.TryGetValue(key, out entityTag) || request.Method == HttpMethod.Post || request.Method == HttpMethod.Post)
{
entityTag = new EntityTagHeaderValue("\"" + Guid.NewGuid().ToString() + "\"");
_etTagHeaderValues.AddOrUpdate(key, entityTag, (k, val) => entityTag);
}

actionExecutedContext.Response.Headers.ETag = entityTag;
SetCacheControl(actionExecutedContext.Response);
}
}
}

And this is how you apply the filter to the actions

[EnableETag]
public Order Get(int id)
{
return new Order
{
Id = "One",
OrderDate = DateTime.Now,
Owner = "Joe Doe"
};
}

On the index.cshtml we have

<div id="body">
<div>
<div>
<h1>Orders</h1>
<input id="details" type="button" value="Details" />
</div>
<div>
<ul id="orders" />
</div>
<div>
<ul id="employee" />
</div>
</div>

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

$('#details').click(function () {
$('#orders').empty();
$.getJSON("/api/Order/12345", function (order) {
var now = new Date();
var ts = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
var content = order.Id + ' ' + order.Owner;
content = content + ' ' + order.OrderDate + ' ' + ts;
$('#orders').append($('<li/>', { text: content }));
});
});
});
</script>
}

You will now notice that once a request is sent, the result are cached on the client for 6 seconds. But after 6 seconds the cache expires and a new request is sent to the server. And since the result has not been modified since the last request, the response is 304.

In the initial request you will see this in the response headers

ETag:"3c45741e-df14-42d8-8e93-86a773620e3d"

And in the consequent request for the same resource then the request header will include:

If-None-Match:"3c45741e-df14-42d8-8e93-86a773620e3d"

NB: The value might change since I am using guid for this

Of  importance to note are the two functions override
-OnActionExecuting: This runs before the action and looks for an Etag in the if-none-match header. If the header is present it is compared to check if it exists in the dictionary, and if  it matches then a 304 is sent back
-OnActionExecuted: runs after the action method. If the HTTP POST or a PUT method is used, then a new ETag is issued and gets stored in the dictionary and gets sent in the ETag header

Happy coding!!!

Comments are highly appreciated and lets meet here again…:)

Using Json.NET to implement your own json serializer (ASP NET MVC)

Code! Code! Code!

When working with even the latest version of ASP NET MVC 4, there are times when you will need to return Json from you controllers.  In this case the framework utilizes the JavascriptSerializer. This is the default for ASP NET MVC unlike the ASP NET WEB API which uses Json.Net

Also worthy noting is that JsonValueProviderFactory uses the JavascriptSerializer to deserialize request body to action parameters.  My problems with JavascriptSerializer on ASP NET MVC  as follows:

1.  The date format that is returned: Most of the times I have come across this date format ( Date(1365850930898)).

2. Circular reference which is a common issue when working with Entity framework. Though there are work around for this like disable lazy loading, its not an ideal solution as lazy loading is one for main reason for the ORM like EF.

To solve all these related issue, JSON.NET comes into play as it has solution to…

View original post 128 more words

Upgrading ASP NET MVC 3 to ASP MVC 4

Recently, asp net mvc 4 has been released, and it happened that i wanted to convert my mvc 3 application to mvc 4.  The steps are really easy since all you need is to change the configuration files of the application

  1. To manually upgrade an existing ASP.NET MVC 3 application to version 4, do the following:
    1. In all Web.config files in the project (there is one in the root of the project, one in the Views folder, and one in the Views folder for each area in your project), replace every instance of the following text (note: System.Web.WebPages, Version=1.0.0.0 is not found in projects created with Visual Studio 2012):System.Web.Mvc, Version=3.0.0.0
      System.Web.WebPages, Version=1.0.0.0
      System.Web.Helpers, Version=1.0.0.0
      System.Web.WebPages.Razor, Version=1.0.0.0

      with the following corresponding text:

      System.Web.Mvc, Version=4.0.0.0
      System.Web.WebPages, Version=2.0.0.0
      System.Web.Helpers, Version=2.0.0.0,
      System.Web.WebPages.Razor, Version=2.0.0.0,

    2. In the root Web.config file, update the webPages:Version element to “2.0.0.0” and add a newPreserveLoginUrl key that has the value “true”:<appSettings>
        <add key=”webpages:Version” value=”2.0.0.0″ />
        <add key=”PreserveLoginUrl” value=”true” />
      </appSettings>
    3. In Solution Explorer, right-click on the References and select Manage NuGet Packages. Search for Microsoft.AspNet.Mvc and install the Microsoft ASP.NET MVC 4 package. Click OK.
    4. In Solution Explorer, right-click the project name and then select Unload Project. Then right-click the name again and select Edit ProjectName.csproj.
    5. Locate the ProjectTypeGuids element and replace {E53F8FEA-EAE0-44A6-8774-FFD645390401} with {E3E379DF-F4C6-4180-9B81-6769533ABE47}.
    6. Save the changes, close the project (.csproj) file you were editing, right-click the project, and then select Reload Project.
    7. If the project references any third-party libraries that are compiled using previous versions of ASP.NET MVC, open the root Web.config file and add the following three bindingRedirect elements under the configuration section:

      <configuration>
        <!–… elements deleted for clarity …–>
         <runtime>
          <assemblyBinding xmlns=”urn:schemas-microsoft-com:asm.v1″>
            <dependentAssembly>
              <assemblyIdentity name=”System.Web.Helpers” 
                   publicKeyToken=”31bf3856ad364e35″ />
              <bindingRedirect oldVersion=”1.0.0.0″ newVersion=”2.0.0.0″/>
            </dependentAssembly>
            <dependentAssembly>
              <assemblyIdentity name=”System.Web.Mvc” 
                   publicKeyToken=”31bf3856ad364e35″ />
              <bindingRedirect oldVersion=”1.0.0.0-3.0.0.0″ newVersion=”4.0.0.0″/>
            </dependentAssembly>
            <dependentAssembly>
              <assemblyIdentity name=”System.Web.WebPages” 
                   publicKeyToken=”31bf3856ad364e35″ />
              <bindingRedirect oldVersion=”1.0.0.0″ newVersion=”2.0.0.0″/>
            </dependentAssembly>
          </assemblyBinding>
        </runtime>
      </configuration>

Easy 🙂 You have you application on asp net mvc 4. Hope you enjoy!!

%d bloggers like this: