Wednesday, November 26, 2014

Celebrating 250th post in roadmap of Microsoft technology


This is my 250th post in my own blog (this one). I was thinking how to celebrate this post? What to write? Another technical article or something else?

As a fan of Microsoft ‘s technology I am working in Microsoft’s stack for almost 2 years but started to write/blog almost 3 years back. Yes, from my college days when I was chosen this platform.  We are seeing Microsoft has made it’s server stack as open source and lot of new technology and thoughts are in queue, yet not in reality.  

I remember, when I was in my secondary school, one of my cousin (who is experienced software engineer) told me “Software developer should have dynamic mentality“. I did not understand that advice on that day but now realizing and experiencing with Microsoft technology.

So, in reality technology is getting change with expectation and human behavior, with their daily habit.  The day has gone where steve ballmer is shouting  “Developer! Developer ! Develop” ! and it’s echoing like “Windows ! Windows !Windows.”

Yes, Microsoft is trying to migrate its application in its comparative’s platform, i.e. MAC and LINUX. Trying to inject something (XAMARIN ) in it’s most popular IDE(Visual Studio) , so that people can able to develop application which will run in all Smartphone.

The huge change in cloud platform too. Now, Azure is supporting LINUX infrastructure too to host application, which will boost customer’s sleep at night (people sleep happily when they do not spent much on that day , hahhah..)

Not only hosting and infrastructure, Microsoft is giving focus in application level too. It market the old good MVC framework in very fantastic and tricky way on top of ASP.NET , people started to love it use it, that gave an extra millage to ASP.NET developer. In effect, their market value has increased.
But there is little unhappiness in heart of .NET Developer, They are not as popular as Java developer (hahaha…).

We can think that the game changing decision taken by Microsoft( to make open source of it’s server stack) is just to bring C# by side of Java in race .It is a to make C# as a default language in all platforms (as java already did).

Now, how developer will get benefit? Yes, good time is coming for .NET developer too.  I wish, more companies will adapt .NET after this decision with free visual studio 2013. (As Microsoft announced, VS 2013 is free for small companies for non-enterprise product)

 The question is when the good day will come. Java is open source for last one decade and Microsoft just announced.  It is time to press accelerator for long run to Microsoft.  

Friday, November 21, 2014

API documentation using GetApiExplorer() function.

We know documentation and help file is very much needed for any application. It‘s more essential if the application expose any API where program from outer world will communicate. There are many solutions to implement documentation. We can use Sandcastle where we can get complete book like documentation of entire application.

Web API has built in class and functions where we can expose documentation page by using same technology.


In this example we will see to expose documentation using GetApiExplorer() function. So, take one Web API application and Add below action to some Controller class.

public ActionResult Index()
 {
var ApiDescription = GlobalConfiguration.Configuration.Services.GetApiExplorer();
         return View("ApiDesc", ApiDescription);
 }   

We know GlobalConfiguration static class is responsible for configuration in project level and we can access GetApiExplorer() with the help of couple of properties of GlobalConfiguration class.

Now, let’s add View (ApiDesc) where we will show the documentation of API functions. Here is example of sample view.


@Model System.Web.Http.Description.IApiExplorer
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ApiDesc</title>
</head>
<body>
    <div>
    @foreach (var api in Model.ApiDescriptions)
    {
       <h5>@api.HttpMethod @api.RelativePath</h5>
       <p>@api.Documentation</p>
      
       if(api.ParameterDescriptions.Count > 0)
       {
           <h6>Parameters</h6>
           <ul>
           @foreach (var parameter in api.ParameterDescriptions)
           {
               <li>@parameter.Name: @parameter.Documentation (@parameter.Source)</li>
           }
           </ul>
       }
   }
    </div>
</body>
</html>

Before hitting run button please make sure that the ValuesController is present in application, which creates by default in default MVC template. The spatiality of ValuesController is that, this is Api Controller, not MVC controller (Hm, wait, in future we will not see them separately)  or make sure that some api controller is present in applications by containing some actions.

Now, let us run the application and we will see below screen.

As discussed, we are seeing the detail documentation of Web API actions. 

Thursday, November 20, 2014

Which browser is standing where ? a real study from this blog.


This is the real graph taken from this blog which represents the usage of browser in current web scenario.


Oh, Chrome market has taken 60+ %.

Monday, November 17, 2014

Send data through HTTP request BODY and URI

We know that every HTTP request/response has two sections. Head and body. The head section contains information, which represents the information about current http request. The body section contains data in general.
There are two ways to send data to server using HTTP request. One is through url which will carry in head section or through Body which will encode data in string format and embed it in http body section.

Generally, when we perform Get HTTP request to server, the client agent attach data through uri and thus pass data to server through header section.

However, when we make HTTP Post request, the client agent encode data and attach it in body section of request. As the data passes through body section, it is not visible to end user.

It does not mean that the data or HTTP request is very much secure. Because when data is encoded, it encodes in plain string format and easily anyone can decode it. The solution is to use HTTPS protocol.

Now, it’s not necessary to pass data from uri or request body depending on nature of request. I mean, we can send data through url even it is Post request. We will test it on ASP.NET MVC framework using Fiddler as client agent.

Pass data through URI

Here we will pass data through URI even it is Post type HTTP request. Here is sample code

   public class DummyController : ApiController
    {
       public void Post([FromUri] Object data)
       {
          
       }
       
    }

We are seeing that the data will come as object format and “FromUri” attribute has specified before parameter.


Once we hot on to Action , we will see that the data has came in parameter.


Now, how we will make sure that data has pass through URI not Body ? If we open the http request in Inspectors tab in fiddler, we will see the transformed URI and data is getting pass as query string.


Now, we will try to pass data through body of HTTP request.  For that we have to make little change in code. Here is modified code. Just we have change the “FromUri” attribute to “FromBody” attribute.

public class DummyController : ApiController
    {
       public void Post([FromBody] Object data)
       {
          
       }
       
    }

And if we generate one http Post request by specifying data in http body ,we will see that the data has embedded in body section of http request.


So, the conclusion is, there is complete freedom to choose way to send data in http request irrespective of method type.


Sunday, November 16, 2014

Transfer unlimited data using HTTP GET in Web API by JSON payload

Its general, when we pass data using GET request we know it passes through URL. There is limitation of characters in URL depends on browser. Now, the question is, if there is bulky data and we want to pass the data using GET method, how we can do it?

Thought, let us try to send json payload to API controller using GET method. I have used fiddler to generate HTTP GET.


In fiddler we are generating GET request and the data is payload as JSON format in HTTP body. The Content-Type header is specified as application/json


Now, we are seeing that the data has reached in test object.


Here is definatin if test class, It is too simple.

    public class test
    {
        public string name { get; set; }
    }

And in length property it’s show 486 characters which is higher than 256 limitation. So, we are sending more than 256 characters using HTTP GET method.




Saturday, November 15, 2014

Specify route order in Web API 2.0

Web API 2.0 provides attribute routing, which allows us to specify routing template for each action. Now, the question is if we specify same routing template in two different actions when which one will execute at first?

In case of tie, routes are ordered by a case-insensitive order string comparison (OrdinalIgnoreCase) of the route template.


If we want to specify sequence of execution then we can specify it by setting value in Order property.  Have a look on below example.

public class BlogController : ApiController
    {
        [Route("blog/getBlog/{id}", Order = 0) ]
        public void Get(Int32 Id)
        {
        }

        [Route("blog/getBlog/{id}", Order = 1)]
        public void GetById(Int32 Id)
        {
        }
    }


We have defined Get() and GetById() actions in Blog controller. Just have a look on Route template above actions. Both are defined same. But the first Action (Get) enjoying the lower Order means if request comes for this route pattern then Get() will execute at first .

Let us look in action. I am using fiddler to generate HTTP payload. This is the url which matches with same pattern.



We are seeing that the Get() has executed because it’s enjoying lower Order. Let’s change the order now.
If we execute same url then we will see that GetById() has executed now because now it’s enjoying lower Order value


Order property is really helpful if there are same routing template in both actions. 


Specify Route Name to implement smart routing in Web API 2.0

We know the feature of Attributing routing in Web API 2.0,that gives more flexible routing mechanism on top of MVC routing.

Using Attributing routing we can specify each action with a unique route template and we can tag unique name to the template. The naming of each route template is not mandatory but ASP.NET MVC environment assign a unique name to each route template if we do not specify explicitly.


Now, the question is! What is the advantage of tagging unique name in route template? In this article, we will discuss one good advantage of naming of route.

namespace WebAPI.Controllers
{
   public class blog
   {
       public int Id { get; set; }
       public string Title { get; set; }
   }

    public class BlogController : ApiController
    {
        List<blog> blogCollection = new List<blog>();

        [Route("show/blog/id", Name="ShowBlogById")]
        public blog Get(Int32 id)
        {
            return blogCollection[id];
        }
       
        public HttpResponseMessage Post(blog blog)
        {
            blogCollection.Add(blog);
            //You may choose some other storage rather than In-memory collection

            var response = Request.CreateResponse(System.Net.HttpStatusCode.Created);
            string Uri = Url.Link("ShowBlogById", new { Id = blog.Id});
            response.Headers.Location = new Uri(Uri);
            return response;
        }

    }
}

In example we have defined blog model and using same model in both Get() and Post() actions. Have a look that Get() action is routed with this routing template.

“show/blog/id”

In addition, we have specified the routing name as “ShowBlogById”.  Now, have a look into body of Post() action.  When we are creating response object we are attaching header location by mentioning the route name of Get() action.

Now, let’s see how HTTP response comes after insertion of any model.


We are seeing that the status code is 201 means Created and the location of new resource is highlighted.  
Now, if we click on the link, it will redirect us to Get() action 


So, the advantage is that In time of resource location creation in Post() we did not specify actual path of created resource rather we specified the route name.




Thursday, November 13, 2014

Latest joke in VisualStudio -2015

Hey, Microsoft has released VisualStudio-2015. Yes obviously they are targeting year 2015 to release full version.
Did you notice the all-new features of 2015? Yes, many are there and which looks most interesting is.

     It’s now more easy to report bug.


Here is the report bug screen. Looks like Microsoft has predicted already the feature of Visual Studio. J


Wednesday, November 12, 2014

It is time to boost performance of MVC using CourtesyFlush

Yes, CourtesyFlush is available is NuGet package which can able to flash out content from Action. So, how does it can improve performances?

Well, think about one application where some heavy weight processing is being performed within some controller. As we know the nature of MVC, Once operation within action get finish, it returns view and the view get render in UI.

Now, the problem is, the UI will not get render until the heavy operation completes.  It would good if we could show something in time of execution of heavy work.

Here is the solution, give reference of CourtesyFlush package in your application. Here is command to install it.
  
    Ø  Install-Package CourtesyFlush


After installation just give reference of  below namespace in application.
using CourtesyFlush;

Let’s have a look on class definition for CourtesyFlush. There are 6 functions (basically 2 functions) where FlushHead () is overloaded 5 times in 5 different flavours.


Let us have a look on, how it works. As the class and the functions are static, we will call the function using this operator. Here we will use flush function to flash one view in time of execution of process.  Here is sample code.

public ActionResult Index()
        {
            ViewResult vr = new ViewResult();
            vr.ViewName = "_data";

            this.Flush(vr);

            System.Threading.Thread.Sleep(5000);
            ViewBag.message = "long process completed";
            return View();
        }

Just have a look that before the Sleep(500) function(heavy task) we are flushing some output in UI and the view (data view) is getting render in UI immediately. 


So, this is the beauty of Flushing concept. Oh, the _data view is plain .cshtml view, which is located within view folder under proper controller name.
Now, let’s see how we can use FlushHead() extension method. Here is one working example.

public ActionResult Index()
        {
            //_Head view is located within
            //Shared folder under view
            this.FlushHead();

            System.Threading.Thread.Sleep(5000);
            ViewBag.message = "long process completed";
            return View();
        }

As, seen in class definition , there are five flavor of FlushHead() function and we are implementing the first one, which does not talk any argument.
If we don not pass any argument then it will search for _Head view within Shared folder.  I have kept one same in my shared view folder already.
Again, the concept of flush is very similar, we are seeing some content in UI even before execution of Action.


In this example, we will not discuss all overloaded function of FlushHead() but those are very easy and self explanatory to implement. 

Saturday, November 8, 2014

Always choose generic type as return type of function.

It is good practice to choose Generic type as return type of function. The advantage is that we can return anything, which derived from the generic type. Let’s have a look on below example.

    public IEnumerable<string> Return()
            {
                List<string> data = new List<string> { "str1", "str2", "str3" };
                return data;

                string[] array = new string[] { "str1", "str2", "str3" };
                return array;

                ICollection<string> col = new List<string> { "str1", "str2", "str3" };
                return col;
            }

Here the return type of function is IEnumerable<string>. We know most of Collection implement this parameterized interface(IEnumerable<T>) and so that we can return those implemented collection when the return type is IEnumerable<T>.

In place of Ienumerable<T> we can return ICollection<T> too. Just like below example

    public ICollection<string> Return()
            {
                List<string> data = new List<string> { "str1", "str2", "str3" };
                return data;

                string[] array = new string[] { "str1", "str2", "str3" };
                return array;

                ICollection<string> col = new List<string>
 { "str1", "str2", "str3" };
                return col;
            }

In example, I have used multiple return statements in same scope, which is not meaningless programmatically but I wanted to just show that we can return many types when return type of function is generic type.
Anyway, we have seen example with collection of class library. The same is applicable in our own data type too. Let us see another example.

interface A
        { }

        class X : A
        {

        }
        class Y : A
        {

        }

        class Z
        {
            public A GetObject()
            {
                return new X(); // Return object of X class
                return new Y(); // Return object of Y class
            }
        }

The interface A is implemented in both X and Y concrete type. And when the return type of GerObject() method is A type we can return both object of X and Y.

So, it’s giving us more freedom in terms of return type.