Search This Blog

Monday 28 April 2014

Razor View Engine

The Razor View Engine

ASP.NET MVC 3 comes with a new view engine named Razor that offers the following benefits:
  • Razor syntax is clean and concise, requiring a minimum number of keystrokes.
  • Razor is easy to learn, in part because it's based on existing languages like C# and Visual Basic.
  • Visual Studio includes IntelliSense and code colorization for Razor syntax.
  • Razor views can be unit tested without requiring that you run the application or launch a web server.
Some new Razor features include the following:
  • @model syntax for specifying the type being passed to the view.
  • @* *@ comment syntax.
  • The ability to specify defaults (such as layoutpage) once for an entire site.
  • The Html.Raw method for displaying text without HTML-encoding it.
  • Support for sharing code among multiple views (_viewstart.cshtml or _viewstart.vbhtml files).
Razor also includes new HTML helpers, such as the following:
  • Chart. Renders a chart, offering the same features as the chart control in ASP.NET 4.
  • WebGrid. Renders a data grid, complete with paging and sorting functionality.
  • Crypto. Uses hashing algorithms to create properly salted and hashed passwords.
  • WebImage. Renders an image.
  • WebMail. Sends an email message.

Thursday 24 April 2014

WCF Self Hosting

Windows Communication Foundation (WCF) is a programming interface as part of .NET Framework.
Using three types we can host service in WCF:
  1. Self-Hosting
  2. IIS Hosting
  3. WAS

1. What is Self Hosting

WCF comes with System.ServiceModel.ServiceHost class that makes you can host your services in your own application easily. With Self Hosting what you need to do is just configuring your service endpoint and calling the .open() method of ServiceHost. To host WCF service you need WCF runtime and .NET application where you want to host your service.

2. What are the advantages and Disadvantages of Self hosting

Advantages of Self Hosting:
  • It is Easy: This way of hosting don’t need many lines of code to successfully run.
  • It is Flexible: You can easily decide when your service active by calling the .open() and .close() method.
Disadvantage of Self Hosting
This self-hosting service is reachable only when the application that hosts the service is running. So, self-hosting is only suitable when the development and demonstration phase of your system.
There are two main advantages of using IIS over self-hosting:
  • Automatic activation
  • Process recycling

3. What is ServiceHost in Self Hosting

  • A Service Host basically provides you everything you need to host a WCF service in a non-IIS or WAS setting. A common place for a ServiceHost would be in a console app or Windows service.
  • You can either instantiate a Service-Host class yourself in a console app, a Windows service, or even a Win-forms app, and thus make your WCF service class available to the outside world or you can delegate that work to IIS or WAS.
  • Even IIS or WAS will use a ServiceHost to host your WCF service - they just do it automatically behind the scenes, and "on demand" - whenever a request for your WCF service comes in.

Calling WCF Services asynchronously using async and await

 

In my previous post, I covered how to use async and await keywords in C# 5 to create asynchronous methods. This post is a continuation of asynchronous programming, in which I will cover how to call WCF services from a client program using async and await.

Response of an application will be slower when it includes heavy weight operations like running complex queries against database, reading a piece of data from a file, calling a service to get some data or any remote operation. When such operations are performed synchronously, the application will be halted till the operation gets over. If we assign the slower operation to a separate task, the thread will be free to perform some other operation till the operation responds.

When a WCF service is called synchronously, the thread associated with the operation is idle till the response is obtained from the server. To avoid this in earlier versions of .NET framework (4.0 or earlier), we had an option to create asynchronous methods with an associated event. Using .NET 4.5, we can create task-based proxies while adding service reference to an application. This can be done using by clicking on the Advanced button in the Add Service Reference dialog.


To call a WCF service synchronously, you can simply use the proxy method created by the Visual Studio, similar to calling a local method.
  • To call a WCF service asynchronously, you will need to first create an "AsyncCallback" "delegate" and pass this delegate to the asynchronous proxy method generated by the Visual Studio. Since the "AsyncCallback" "delegate" is executed in a worker thread different from the UI thread, any access to the "UI elements" needs to be "Dispatched".
  • From the application point of view, either way has its advantages and disadvantages. For most applications, after the calling of a WCF service, the application will be in an intermediate state until the response from the service is received. During this time, it may be ideal to block the UI thread to prevent user actions to get into any un-predictable results. In this case, a synchronous call may be appropriate. In some other scenarios, particularly when we work on some "SOA" applications, we may need to make multiple service calls at the same time and let the services to work in parallel. In this case, asynchronous WCF calls will be the ideal.
  • One thing just came to my mind. To make an asynchronous call, you probably do not need to have the asynchronous proxies. You can well fork a worker thread by yourself and let the thread to do a synchronous call. You will achieve the same effect as using the asynchronous proxies.
  • If you are not familiar with WCF services, this link is a good place to get you started.
  • Dependency Injection (DI) in EF

    Dependency Injection (DI) is a software design pattern that allow us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable.
    The Dependency Injection pattern uses a builder object to initialize objects and provide the required dependencies to the object means it allows you to "inject" a dependency from outside the class.
    For example, Suppose your Client class needs to use a Service class component, then the best you can do is to make your Client class aware of an IService interface rather than a Service class. In this way, you can change the implementation of the Service class at any time (and for how many times you want) without breaking the host code.

    Key points about DI

    1. Reduces class coupling
    2. Increases code reusing
    3. Improves code maintainability
    4. Improves application testing
    Dependency Injection’ as a design pattern that helps develop maintainable and de-coupled code. DI is also a way to implement the ‘D’ in SOLID principles. (SOLID as stated by Uncle Bob stands for: Single responsibility, Open closed principle, Liskov substitution principle, Interface segregation principle and Dependency Inversion). Often the association of 'Design Pattern' to anything that we have not dealt with before, typically means it goes into our 'To Do' bucket which becomes very dusty over time. Time to blow the dust away! 

    What is SOLID?

     

    SOLID are five basic principles whichhelp to create good software architecture. SOLID is an acronym where:-
    • S stands for SRP (Single responsibility principle)
    • O stands for OCP (Open closed principle)
    • L stands for LSP (Liskov substitution principle)
    • I stands for ISP ( Interface segregation principle)
    • D stands for DIP ( Dependency inversion principle)

    WebAPI service and WCF service calling in client application

    WCF service details

    class TestService : ITestService
    {
        public Stream TestGet()
        {
            return new MemoryStream(Encoding.UTF8.GetBytes("Hello World. Time is: " + DateTime.Now));
        }
     
        public async Task<Stream> TestStream(Stream requestStream)
        {
            using (var reader = new StreamReader(requestStream))
            {
                var body = await reader.ReadToEndAsync();
     
                return new MemoryStream(Encoding.UTF8.GetBytes(body));
            }
     
        }
     
    }



    WebAPI service details

     
    public class TestController : ApiController
    {
        public HttpResponseMessage Get()
        {
            return new HttpResponseMessage() { Content = new StringContent("Hello World. Time is: " + DateTime.Now, Encoding.UTF8, "text/plain") };
        }
     
        public async Task<HttpResponseMessage> Post(HttpRequestMessage inputMessage)
        {
            var content = await inputMessage.Content.ReadAsByteArrayAsync();
            var response = new HttpResponseMessage { Content = new ByteArrayContent(content) };
            return response;
        }
     
        public async Task<HttpResponseMessage> Put(HttpRequestMessage inputMessage)
        {
            var content = await inputMessage.Content.ReadAsStreamAsync();
            var response = new HttpResponseMessage { Content = new StreamContent(content) };
            return response;
        }
     
     
    }

    Asp.Net Web API Vs Asp.Net MVC

    Asp.Net Web API  Vs  Asp.Net MVC

    1. Asp.Net MVC is used to create web applications that returns both views and data but Asp.Net Web API is used to create full blown HTTP services with easy and simple way that returns only data not view.
    2. Web API helps to build REST-ful services over the .NET Framework and it also support content-negotiation(it's about deciding the best response format data that could be acceptable by the client. it could be JSON,XML,ATOM or other formatted data), self hosting which are not in MVC.
    3. Web API also takes care of returning data in particular format like JSON,XML or any other based upon the Accept header in the request and you don't worry about that. MVC only return data in JSON format using JsonResult.
    4. In Web API the request are mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.
    5. Asp.Net Web API is new framework and part of the core ASP.NET framework. The model binding, filters, routing and others MVC features exist in Web API are different from MVC and exists in the new System.Web.Http assembly. In MVC, these featues exist with in System.Web.Mvc. Hence Web API can also be used with Asp.Net and as a stand alone service layer.
    6. You can mix Web API and MVC controller in a single project to handle advanced AJAX requests which may return data in JSON, XML or any others format and building a full blown HTTP service. Typically, this will be called Web API self hosting.
    7. When you have mixed MVC and Web API controller and you want to implement the authorization then you have to create two filters one for MVC and another for Web API since boths are different.
    8. Moreover, Web API is light weight architecture and except the web application it can also be used with smart phone apps.

    Web API

    What is Web API and why to use it ?
    Web API is a framework for building HTTP services that can be consume by a broad range of clients including browsers, mobiles, iphone and tablets. It is very similar to ASP.NET MVC since it contains the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection. But it is not a part of the MVC Framework.