• Some good resources for ASP.NET MVC

    May 2, 13 • In aspnetmvc

    My last period is one of the busiest of my life but, thanks to Chris Massey, I found the time to write about one of my favorite frameworks, ASP.NET MVC.

    Chris’s idea is to collect the most useful articles for each section (Action Filters, Deploy, and so on) of the framework, with an introduction to each topic.
    Personally, I worked on the Deploy topic (it’s easy to recognize, it’s the article with the worst English).

    I really like that approach because it is very helpful for all people who want to learn MVC, but also for those who already know it but want to increase their knowledge.

    If you have feedback or you think there are some missing arguments, you can contact directly Chris (or write me here and I will do for you).

    Enjoy the guide here.

    Permalink »
  • Caching Web API Requests

    Mar 19, 13 • In WebAPI

    I wrote many times about Web API, so you should know about the library and the main differences between the client part of Web API and the server side; in this post I’m going to write about the client side of this cool library.
    Exactly like the “old” System.Net.WebRequest class, also the Web API client can manage the caching policy for all REST requests.

    Before seeing the code, it’s important to understand what does it mean “manage the caching policy” and why we should do that.

    The class HttpClient is created for web requests and it has all problems/features of a browser without the render and Javascript stuff.

    All the modern browsers has an aggressive cache policy with the purpose of reducing the network traffic and increase the performances. The last point is really important: to execute operations faster browsers read a set of information from the response header (Etag, Cache-Control and Date), and, based on their values, it decides to take the data from the response or from the cache.

    In one of the latest projects we are working in my company (I spoke about that here), we have to call some rest services which totally ignore the cache header values. To be clear I’ve the same headers values for different results so I’ve to disable the cache for my request to that endpoint because the default behavior use the cache:

    Default cache policy (from MSDN)

    Satisfies a request for a resource either by using the cached copy of the resource or by sending a request for the resource to the server. The action taken is determined by the current cache policy and the age of the content in the cache. This is the cache level that should be used by most applications.

    To change the cache policy we need to do something like that:

    using (WebRequestHandler handler = new WebRequestHandler())
    {
      handler.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.BypassCache);
    
      using (HttpClient client = new HttpClient(handler))
      {
        response = await client.GetAsync("http://www.mysite.com/api/something/");
      }
    }

    As you can see is really simple and really important so, be careful using the right Header values in your response J

    Permalink »
  • Minify resources with source map at runtime using Web Essential

    Jan 8, 13 • In aspnetmvc, WebDev

    In one of the last versions of Web Essential Tools, Microsoft released one of my favorite features for the web development. I’m talking about the opportunity to create a bundle resource at runtime with the support of SourceMap.

    The first step to try this cool feature is to install the Visual Studio plugin so, download it from here

    After the installation Visual Studio offers you new features that are not available in the standalone version. In fact, after right clicking on a web resource (css, js, etc) in the solution explorer, you have a new “item” named Web Essential:

    001

     

    What I love most in this extension is the easy way to create the combined and minified resources (really, I’m not in love with the web optimization packages included in ASP.NET MVC 4).

    What does it give us?

    • Javascript and Css minification with SourceMap;
    • Javascript and Css bundle with SourceMap;

    As you can see in both items there is the SourceMap, but what is it?
    Source Map is a cool feature, actually supported just by Google Chrome, that allows you to understand the correct position (i.e. line of an error) in a Javascript file starting from a combined file.

    I think that feature is a killer feature for frontend developers because some errors happened in production and, in some cases, you are not able to reproduce them during the tests.

    The first things is to enable that features in chrome, so:

    002

     

    003

     

    From now, everything is easier, select your javascript files, right click and, from WebEssential Items, select “Create Javascript Bundle File”.

    004

    005

    006

     

    Drag you bundle into your page, MyExampleJavascriptBundle.min.js in my example, and everything is ready.

    From now, every time you change and save the files you selected for the bundle, Visual Studio will automatically update it; it means that minified and source map will always be up to date with the original resources without doing anything special (How f..ing cool is that?).

    As you can see in the image below there are more files that I’ve included in my page (see previous screenshots).

    007

    In fact, I didn’t added the files 001.js and 002.js but only the MyExampleJavascriptBundle.min.js.

    How is it possible? The reason is really simple; inside the MyExampleJavascriptBundle.min.js, Visual Studio added a line with the path of Source Map that includes the original not combined files.

    Chrome understands this behavior and shows you the source files (only if you use the developer tools bar).

    If you like it and you want to understand more about Source Map, take a look here and, if you like Web Essential like me you have to follow Mads on twitter

    Stay tuned!

     

    Permalink »
  • Manage cookies using Web API

    Dec 3, 12 • In WebAPI

    In my last project, I’ve deeply used WebApi, both for the client side and server side. In fact my application must call several REST endpoints developed with java and, after a code elaboration, I have to expose the data to other clients (javascript into an html page in this case).

    One of the pillars request by the Java services (really is not a technology request but just from the implementation made by the external company) is to read all cookies from the response and then send them back to the next requests (like a proxy).

    To make more clear where my app is, I realized the following chart:

    As you can see the communication between my application and the Java Rest endpoint is based on the client library released with Web API.
    In fact, Web API is more than a service library used just to expose data; it includes a client library that makes very easy to execute a REST call, so let’s start to install the client package named “Microsoft ASP.NET Web API Client Libraries” from NuGet!

    From now on, if you need to create a web request, you should do something like in the code below:

    HttpClient client = new HttpClient();
    
    HttpResponseMessage response = await client.GetAsync(requestUrl);
    
    //response contains all you need

    My problem was to manage the cookie from the response, since I needed to read the cookies and then store them somewhere for the next request.
    Obviously, the example above is really simple and it’s not enough for me because I need to read all the cookies and then send them to the browser.

    Fortunately, there is an easy way to read the cookies from an Http Response using Web Api client library.
    The first thing to do is to create an instance of HttpClientHandler, inizialize the CookieContainer collection and then use it the HttpClient Constructor:

    HttpClientHandler handler = new HttpClientHandler
                                  {
                                    UseCookies = true, 
                                    UseDefaultCredentials = true, 
                                    CookieContainer = new CookieContainer()
                                  };
    
    HttpClient client = new HttpClient(handler);
    
    HttpResponseMessage response = await client.GetAsync(requestUrl);
    
    // hanlder.CookieContainer contains your cookies

    Now, after the request, the CookieContainer should contain the correct cookies.  Now we need to manage the cookie’s type, since we have two different kind of responses: one for ASP.NET MVC and one for Web API.

    The two frameworks have no shared assemblies, it means that the cookies are represented by different classes in different namespaces with the same kind of data and I’m in a weird situation:

    • The Cookiecontainer contains a list of System.Net.Cookie;
    • The Web Api server request use System.Net.Http.Headers.CookieHeaderValue;
    • ASP.NET MVC uses System.Web.HttpCookie;

    Three different classes, the first one comes from the client and the others for the response to the browsers.

    For this reason, I created a Cookie manager class that moves the data from a cookie class to another one.
    To use the cookie in ASP.NET MVC is really simple, we just need to use the HttpContext (Request or response, depends if you need to add or read a cookie) like the code below:

    //reading
    HttpContext.Request.Cookies["cookieName"];
    
    //writing
    HttpContext.Response.Cookies.Add(new HttpCookie("cookieName"));

    For the Web API the approach is different. In fact, into the controller, there isn’t the HttpContext class like into MVC, so we need to manage the data using the HttpHeader like this:

    //reading
    var cookies = actionContext.Request.Headers.GetCookies();
    
    /adding
    response.Headers.AddCookies(cookies);

    Now I’m able to read cookies from everywhere and my last goal is to find a valid entry point where to manage the cookie read/write for MVC and Web API (easy ActionInvoker J)

     

    Permalink »
  • Different keys with RavenDb

    Nov 5, 12 • In .NET

    In last period, I am spending so times to learn document databases, in my case RavenDB and MongoDB. To be honest I am working only on Raven right now because it is friendlier for .NET developers but I promised myself to compare some features from these two awesome database engines.

    One of the big difficult I found, is to create the right model. I said big because I’m used to design the model for relation database and here is really different. For example we do not have the join and we also need to denormalize the references (http://ravendb.net/docs/faq/denormalized-references).

    It is mandatory because each document must be independent as Oren wrote on the site:

    One of the design principals that RavenDB adheres to is the idea that documents are independent, that all the data required to process a document is stored within the document itself

    Fortunately, Raven makes easy some stuff like update and loading, respectively using Patch API (http://ravendb.net/docs/client-api/partial-document-updates) and Include.

    The Include command is absolutely cool, it makes easy to load two documents with one roundtrip and it means only one thing, Faster!
    For the NHibernate users it reminds me a little the Future command, with an important different, here you can load only document that has a key to another one, in NH you can load also objects completely unlinked.

    Let’s see my domain:

    It seems more complex that it really is. There is a Post class and ItemComments. The first one includes all you need to have in the aggregate view; the second one, combined with the first one, has all you need to show in the detail view or admin area (in the most blog enginea you don’t need to show the comments in the main page, otherwise you need in the permalink).

    The only common thing between them is the property CommentsId into Post class (It’s called Id in ItemComments). With it, you can easily load both documents in the same time.
    Let’s see how to use it:

    Post item = new Post()
    //populate the properties with your values
    
    this.Session.Store(item);
    
    ItemComments comments = new ItemComments
                              {
                                Approved = new List<Comment>(), 
                                Pending = new List<Comment>(), 
                                Spam = new List<Comment>(), 
                                Item = new ItemReference
                                         {
                                           Id = post.Id, 
                                           Status = post.Status, 
                                           ItemPublishedAt = post.PublishAt
                                         }
                              };
    
    this.Session.Store(comments);
    post.CommentsId = comments.Id;
    
    this.Session.SaveChanges();
    
    //To read both with only one request:
    
    Post post = this.Session
    				.Include<Post>(x => x.CommentsId)
    				.Load(id);
    
    ItemComments comments = this.Session.Load<ItemComments>(post.CommentsId);

    As you see in the diagram, the key for the Post is a simple integer but in the ItemComments it is a string. That is mandatory if you want to use the Include because in the string there is all Raven needs to load the document (the ID and the type, in this case ItemComments/12345 where 12345 is the id).

    Different CLR types for the key means to extend the base class for all entities. Typically I have a base class (EntityBase in this model) that includes the ID, Creation Date and a calculate property to check the status of the entity.

    public class EntityBase<T>
    	{
    		#region Public Properties
    
    		public DateTimeOffset CreatedAt { get; set; }
    
    		public T Id { get; set; }
    
    		public bool IsTransient
    		{
    			get
    			{
    				return this.Id == 0;
    			}
    		}
    
    		#endregion
    	}

    The property IsTransient could be helpful to understand if you have to execute some path or not.
    Using a generic CLR type for the ID the base class must be extended like this:

    public class EntityBase<T>
    	{
    		#region Public Properties
    
    		public DateTimeOffset CreatedAt { get; set; }
    
    		public T Id { get; set; }
    
    		public bool IsTransient
    		{
    			get
    			{
    				return EqualityComparer<T>.Default.Equals(Id, default(T));
    			}
    		}
    
    		#endregion
    	}

    Now you can still use a base class with the same features having fun with RavenDB.

    Permalink »
Scroll to top