28 June 2015

POST vs PUT in Rest

POST vs PUT in Rest 

Example :

"POST /books" with a bunch of book information might create a new book, and respond with the new URL identifying that book: "/books/5".

"PUT /books/5" would have to either create a new book with the id of 5, or replace the existing book with ID 5.
In non-resource style, POST can be used for just about anything that has a side effect. One other difference is that PUT should be idempotent - multiple PUTs of the same data to the same URL should be fine, whereas multiple POSTs might create multiple objects or whatever it is your POST action does.


Ajax call in MVC

Ajax call in MVC

The first thing to look at is the key settings options that are available for AJAX requests:

type This is type of HTTP Request and accepts a valid HTTP verb. POST is the option illustrated in this article.
url This is the location of the resource that the request will be made to.
data This is the actual data to be sent as part of the request.
contentType This is the content type of the request you are making. The default is 'application/x-www-form-urlencoded'.
dataType This is the type of data you expect to receive back. Accepted values are text, xml, json, script, html jsonp. If you do not provide a value, jQuery will examine the MIME type of the response and base its decision on that.

Example

< script >
   $( function () {
        $( "button" ).click( function () {
            var car = { Make: 'Audi', Model: 'A4 Avant', Colour: 'Black', Registered: 2013 };
            $.ajax( {
                type: "POST",
                url: "/Receiver",
                data: car,
                datatype: "html",
                success: function ( data ) {
                    $( '#result' ).html( data );
                }
            } );
        });
    } );

< /script >


Setting async false in ajax in MVC

Setting async false in ajax in MVC

Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.




By default async is true in ajax call.

MVC Life Cycle

MVC Life Cycle

Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.

Step 2 Fetch route:- Depending on the URL sent "UrlRoutingModule" searches the route table to create "RouteData" object which has the details of which controller and action to invoke.

Step 3 Request context created: - The "RouteData" object is used to create the "RequestContext" object.

Step 4 Controller instance created: - This request object is sent to "MvcHandler" instance to create the controller class instance. Once the controller class object is created it calls the "Execute" method of the controller class.

Creating Response object: - This phase has two steps executing the action and finally sending the response as a result to the view.

Step 5 Execute Action: - The "ControllerActionInvoker" determines which action to executed and executes the action.

Step 6 Result sent: - The action method executes and creates the type of result which can be a view result , file result , JSON result etc.

22 March 2015

WCF - Windows Communication Foundation

1. WCF WCF as a programming platform that is used to build Service-Oriented applications. Microsoft has unified all its existing distributed application technologies (e.g. MS Enterprise Services, ASMX web services, MSMQ, .NET Remoting etc) at one platform

2. Difference between WCF and ASMX Web Services
1.     ASP.NET web service is designed to send and receive messages using SOAP over HTTP only.
While WCF can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, Named Pipes etc)
       2.     Web services is hosted in IIS only. WCF can be hosted in IIS, WAS, Console, Windows NT Service
       3.     Web service has only  Limited security ,  WCF is consistency security programming model.
       4.     Web services uses Xml serializer and WCF uses Data contract serializer.

2.  WCF Endpoints
1.     Client uses endpoint to communicate with WCF Service.

A WCF service endpoint has three basic elements i.e. Address, Binding and Contract.
Address: It defines “WHERE”. Address is the URL that identifies the location of the service.
Binding: It defines “HOW”. Binding defines how the service can be accessed.
Contract: It defines “WHAT”. Contract identifies what is exposed by the service.

3. Operation Overloading while exposing WCF Services?
By default, WSDL doesn’t support operation overloading. Overloading behavior can be achieved by using “Name” property of OperationContract attribute.

[ServiceContract]
 interface IMyCalculator
 {
        [OperationContract(Name = “SumInt”)]
        int Sum(int arg1,int arg2);
        [OperationContract(Name = “SumDouble”)]
        double Sum(double arg1,double arg2);
  }

4.Message Exchange Patterns (MEPs) supported by WCF

                1.Request/Response
                2.One Way
                3.Duplex

Request/Response
It’s the default pattern. In this pattern, a response message will always be generated to consumer when the operation is called, even with the void return type. In this scenario, response will have empty SOAP body.
One Way
In some cases, we are interested to send a message to service in order to execute certain business functionality but not interested in receiving anything back. One way MEP will work in such scenarios.
If we want queued message delivery, One way is the only available option.
Duplex
The Duplex MEP is basically a two-way message channel. In some cases, we want to send a message to service to initiate some longer-running processing and require a notification back from service in order to confirm that the requested process has been completed.

5.Standard Bindings in WCF
1.     BasicHttpBinding  is standard binding is designed to expose a service as if it is an ASMX/ASP.NET web service.

2.     NetTcpBinding provides transport level security, Transport Level security means providing security at the transport layer itself.
        
                   
                         
                   
         
 
       3. wsHttpBinding  provides following security  None,Transport,Message and Transport with message credentials
           
                         
                                     
                         
            
    
other bindings are WebHttpBinding - Wcf Restful service, netNamedPipeBinding,netTcpBinding,netPeerTcpBinding and netmsmqBinding


6. Core components of WCF Service
Service Class:  A service class implementing in any CLR-based language and expose at least one method.
Hosting Environment: a managed process for running service.
Endpoint: a client uses it to communicate with service.

7.Multiple endpoints for different binding types
Yes, we can have multiple endpoints for different binding types. For example, an endpoint with wsHttpBinding and another one with netTcpBinding.

8. Contracts in WCF?
A Contract is basically an agreement between the two parties i.e. Service and Client.

1.     Behavioral Contracts define that what operations client can perform on a service.
ServiceContract [Interface] attribute is used to mark a type as Service contract that contains operations.    OperationContract [Method in Interface]attributes is used to mark the operations that will be exposed.           Fault Contract defines what errors are raised by the service being exposed.
      2.     Structural Contracts
                DataContract [Class] attribute define types that will be moved between the parties.
                MessageContract attribute define the structure of SOAP message.
9. Different WCF Instance Activation Methods available
Per Call: A new instance is created against each incoming request from client and later disposed off  as response generated.
Per Session: an instance for each session.
Singleton: All incoming requests are served by only one instance.
10.Different ways to handle concurrency in WCF?
Single: means at a given time, only a single request can be processed by WCF service instance. Other requests will be waiting until the first one is fully served.
Multiple: means multiple requests can be served by multiple threads of a single WCF service instance.
Reentrant: means a single WCF service instance can process one request at a given time but the thread can exit the service to call another service.

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple] public class MyService : IMyService
{
}

11.WCF throttling
WCF throttling enables us to regulate the maximum number of WCF instances, concurrent calls and concurrent sessions.

               
                               
                                                maxConcurrentInstances=”2147483647”
                                                maxConcurrentCalls=”16″
                                                maxConcurrentSessions=”10″
               

12.Fault contract
when some exception occurs at a WCF service level, it will not expose as it is to client. Reason is that WCF exception is a CLR exception and it doesn’t make sense to expose it outside CLR because it contains internal details of service code like stack trace. So, WCF handles and returns error details to client using Fault Contract.“So, fault contract is a contract that contains the details of possible exception(s) that might occur in a service code.
 [ServiceContract]
 public interface IService1
 {
                [OperationContract]
                [FaultContract(typeof(MyFaultDetails))]
                int MyOperation1();
 }
 [DataContract]
  public class MyFaultDetails
  {
                [DataMember]
                public string ErrorDetails { get; set; }
  }

public int MyOperation1()
  {
       Try{               //Do something……       }catch()
       {
                  MyFaultDetails ex = new MyFaultDetails();
                  ex.ErrorDetails = “Specific error details here.“;
                  throw new FaultException(ex,“Reason: Testing…..“);
       }
  }
13.Transfer Security Modes
None – No security at all. Very risky to choose.
Transport – Securing message transfer with transport protocol like TCP, IPs, HTTPs, MSMQ.  It’s Ideal for Intranet scenarios having point to point communication.
Message – Securing message by encrypting it. Good for scenarios even when multiple intermediaries involved.
Mixed – TransportWithMessageCredential uses transport for message privacy and service authentication with client authentication handled at message level.
Both -Using both Message as well as transport security. In this case a secured encrypted message travel over a secure transport (pipe) only supported by MSMQ Binding.

               
                               
               

14.Reliable Messaging in WCF?
We know that networks are not perfect enough and those might drop signals or in some scenarios there can be a possibility of wrong order of messages during message exchange.
WCF allows us to ensure the reliability of messaging by implementing WS-ReliableMessaging protocol.

   
                 
                                         enabled=”true”
                                        ordered=”true”
                                        inactivityTimeout=”00:02:00″ />
    
 
15.Reliable Sessions in WCF?
Reliable sessions actually ensure that the caller for messages will know about the lost message(s) but it can’t guarantee about the delivery of message(s).
There is a misconception about reliable sessions that it ensures the session will never expire or stays for a very long time. This we can achieve by using timeout for sessions.


How IIS Process Asp.net request before Asp.net Page Life cycle

How IIS Process Asp.net request before Life cycle

When client request for some information from a web server, request first reaches to HTTP.SYS of IIS. HTTP.SYS then send the request to respective  Application Pool. Application Pool then forward the request to worker process to load the ISAPI Extension which will create an HTTPRuntime Object to Process the request via HTTPModule and HTTPHanlder. After that the ASP.NET Page LifeCycle events starts.

Worker Process:  Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system.  All the ASP.Net functionality runs under the scope of worker process.  When a request comes to the server from a client worker process is responsible to generate the request and response. In a single word we can say worker process is the heart of ASP.NET Web Application which runs on IIS.
Application Pool: Application pool is the container of worker process.  Application pools is used to separate sets of IIS worker processes that share the same configuration.  Application pools enables a better security, reliability, and availability for any web application.  The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected. This makes sure that a particular web application doesn’t not impact other web application as they they are configured into different application pools.

reference
http://abhijitjana.net/2010/03/14/beginner%E2%80%99s-guide-how-iis-process-asp-net-request/

Dependency Injection

Dependency Injection

Dependency Injection is to reduce tight coupling

The Dependency Injection pattern is a particular implementation of Inversion of Control.
Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source

Advantages of using Dependency Injection pattern and Inversion of Control are the following:


Reduces class coupling,Increases code reusing,Improves code maintainability,Improves application testing

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...