Wednesday 21 December 2016

difference between LINQ to SQL and Entity Framework

                            LINQ to SQL
                        Entity
·        It works only with SQL Server Database
·        To maintain the relation it generates a .dbml
·        It cannot generate database from model
·        It permits one to one mapping between the entity classes and relational views/tables
·        It enables you to query data using DataContext
·        It provides tightly coupled approach
·         It works with various database like DB2, MYSQL, SQL Server etc.
·        It creates an .edmx files initially and relation is maintained using 3 different files .msl, .csdl and .ssdl
·        It can generate database from model
·        Between the entity classes and relational tables, it permits one-to-one, one-to-many and many-to-many
·        It enables you to query data using EntitySQL, DBContext, and ObjectContext
·        It provides loosely coupled approach

Tuesday 13 December 2016

What is WCF throttling?

WCF throttling provides some properties that you can use to limit how many instances or sessions are created at the application level. Performance of the WCF service can be improved by creating proper instance.

The throttling of services is another key element for WCF performance tuning. WCF throttling provides the prosperities maxConcurrentCalls, maxConcurrentInstances, and maxConcurrentSessions, that can help us to limit the number of instances or sessions are created at the application level.
Attribute / PropertyDescription
maxConcurrentCallsThis specifies the maximum number of messages processed across the service host. The default value for this property is 16 (WCF 4.0 is improved to default is 16 * Processor Count).
maxConcurrentInstancesThis specifies the maximum number of instances of a context object that executes at one time with the service. The default is Int32.MaxValue.
maxConcurrentSessionsThis specifies the maximum number of sessions at one time within the service host object. The default value is 10 (WCF 4.0 increases that to 100 * Processor Count).
  1. <configuration>  
  2.     <system.serviceModel>  
  3.         <services>  
  4.             <service .... .... .... </service>  
  5.         </services>  
  6.         <behaviors>  
  7.             <serviceBehaviors>  
  8.                 <behavior name="ServiceBehavior">  
  9.                     <serviceThrottling maxConcurrentCalls="16" maxConcurrentSessions="100" maxConcurrentInstances="10" />  
  10.                     <serviceMetadata httpGetEnabled="true" /> </behavior>  
  11.             </serviceBehaviors>  
  12.         </behaviors>  
  13.     </system.serviceModel>  
  14. </configuration>  

What is Transaction Propagation?

Transaction propagation is the ability to propagate a transaction across the boundaries of a single service. Or in other words, we can say that a service can participate in a transaction that is initiated by a client. 

In a SOA environment, transaction propagation becomes a key requirement. As we know, WCF supports SOA, so it provides support for transaction propagation as well.

To enable transaction propagation, we need to set the value of the TransactionFlow property of the binding being used. This can be done programmatically as follows: 
  1. WSHttpBinding bindingBeingUsed = new WSHttpBinding();  
  2. bindingBeingUsed.TransactionFlow = "true";  
Or it can be done decoratively by updating the configuration file as follows:
  1. <bindings>  
  2.     <wsHttpBinding>  
  3.         <binding name="binding1" transactionFlow="true" />   
  4.     </wsHttpBinding>  
  5. </bindings>  
The default value for the TransactionFlow property is "False".

Do all WCF bindings support Transaction Propagation?

No. Not all WCF bindings support transaction propagation. Only the following list of bindings support it:
  • wsHttpBinding
  • netTcpBinding
  • netNamedPipeBinding
  • wsDualHttpBinding
  • wsFederationHttpBinding

WCF binding

Binding describes how a client is going to communicate to WCF service. Binding is used as per client need. It supports different types of protocol to communicate with client and different types of encoding to transfer the data over the internet. So, basically binding is nothing but it is a way of communication between client and service as per client need.

Basic binding
This binding is provided by the BasicHttpBinding class. It is designed to expose a WCF service as an ASMX web service, so that old clients (that are still using an ASMX web service) can consume the new service. By default, it uses the HTTP protocol for transport and encodes the message in UTF-8 text format. You can also use HTTPS with this binding.

Web binding

This binding is provided by the WebHttpBinding class. It is designed to expose WCF services as HTTP requests using HTTP-GET and HTTP-POST. It is used with REST based services that may provide output in XML or JSON format. This is very much used with social networks for implementing a syndication feed.

Web Service (WS) binding:

This binding is provided by the WSHttpBinding class. It is like a basic binding and uses HTTP or HTTPS protocols for transport. But this is designed to offer various WS - * specifications such as WS – Reliable Messaging, WS - Transactions, WS - Security and so on which are not supported by Basic binding.

wsHttpBinding= basicHttpBinding + WS-* specification

WS Dual binding:

This binding is provided by the WsDualHttpBinding class. It is like a WsHttpBinding except it supports bi-directional communication which means both clients and services can send and receive messages.

TCP binding:

This binding is provided by the NetTcpBinding class. It uses TCP protocol for communication between two machines within intranet (means same network). It encodes the message in binary format. This is a faster and more reliable binding compared to the HTTP protocol bindings. It is only used when the communication is WCF-to-WCF which means both client and service should have WCF.

IPC binding:

This binding is provided by the NetNamedPipeBinding class. It uses named pipe for communication between two services on the same machine. This is the most secure and fastest binding among all the bindings.

MSMQ binding:
This binding is provided by the NetMsmqBinding class. It uses MSMQ for transport and offers support to a disconnected message queued. It provides solutions for disconnected scenarios in which the service processes the message at a different time than the client sending the messages.

Federated WS binding:

This binding is provided by the WSFederationHttpBinding class. It is a specialized form of WS binding and provides support to federated security.

Binding describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.

A binding has several characteristics, including the following:
  • Transport - Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  • Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
  • Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability.

BindingDescription
BasicHttpBindingBasic Web service communication. No security by default.
WSHttpBindingWeb services with WS-* support. Supports transactions.
WSDualHttpBindingWeb services with duplex contract and transaction support.
WSFederationHttpBindingWeb services with federated security. Supports transactions.
MsmqIntegrationBindingCommunication directly with MSMQ applications. Supports transactions.
NetMsmqBindingCommunication between WCF applications by using queuing. Supports transactions.
NetNamedPipeBindingCommunication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBindingCommunication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBindingCommunication between WCF applications across computers. Supports duplex contracts and transactions

End Points of WCF

Endpoints provide the configuration required for the communication and create the complete WCF service application.

An Endpoint is a piece of information that tells WCF how to build the runtime communication channels to send and receive messages. An endpoint consists of the three things address, binding and contract. 


All communication with a Windows Communication Foundation (WCF) service occurs through the endpoints of the service. Endpoints provide clients access to the functionality offered by a WCF service.

Each endpoint consists of four properties:
  • An address that indicates where the endpoint can be found.
  • A binding that specifies how a client can communicate with the endpoint.
  • A contract that identifies the operations available.

The Structure of an Endpoint-

Each endpoint consists of the following:
  • A set of behaviors that specify local implementation details of the endpoint.
  • Address: The address uniquely identifies the endpoint and tells potential consumers of the service where it is located. It is represented in the WCF object model by theEndpointAddress class. An EndpointAddress class contains:

    • A Uri property, which represents the address of the service.
    • An Identity property, which represents the security identity of the service and a collection of optional message headers. The optional message headers are used to provide additional and more detailed addressing information to identify or interact with the endpoint.
  • Binding: The binding specifies how to communicate with the endpoint. This includes:

    • The transport protocol to use (for example, TCP or HTTP).
    • The encoding to use for the messages (for example, text or binary).
    • The necessary security requirements (for example, SSL or SOAP message security).
  • Contracts: The contract outlines what functionality the endpoint exposes to the client. A contract specifies:

    • What operations can be called by a client.
    • The form of the message.
    • The type of input parameters or data required to call the operation.
    • What type of processing or response message the client can expect.


Fault Contract in WCF

Fault Contract provides documented view for error accorded in the service to client. This help as to easy identity the what error has occurred, and where. By default when we throw any exception from service, it will not reach the client side. The less the client knows about what happened on the server side, the more dissociated the interaction will be, this phenomenon (not allowing the actual cause of error to reach client) is known as error masking. By default all exceptions thrown on the service side always reach the client as FaultException, as by having all service exceptions indistinguishable from one another, WCF decouples the client from service. 

Syntax

[OperationContract]
[FaultContract(typeof(MyException))]
string getDetails(int value);

Message Contract in WCF

A Message Contract is used to control the structure of a message body and serialization process. It is also used to send / access information in SOAP headers. By default WCF takes care of creating SOAP messages according to service DataContracts and OperationContracts. 

 
A MessageContract controls the structure of a message body and serialization process. A MessageContract can be typed or untyped and are useful in interoperability cases and when there is an existing message format we must comply with. 

When an operation contract required to pass a message as a parameter or return value as a message, the type of this message will be defined as message contract. A message contract defines the elements of the message (like as Message Header, Message Body), as well as the message-related settings, such as the level of message security.

Message contracts give you complete control over the content of the SOAP header, as well as the structure of the SOAP bod

The SOAP header is implemented in the namespace system.web.services.protocol.
  1. [MessageContract]  
  2. public class AutherRequest  
  3. {  
  4.    public string AutherId;  
  5. }  
Message Header

A Message Header is applied to a member of a message contract to declare the member within the message header.
  1. [MessageContract]  
  2. public class AutherRequest  
  3. {  
  4.    [MessageHeader]  
  5.    public string AutherId;  
  6. }  
Message Body Member

A Message Body Member is applied to the member of a message contract to declare the members within the message body.
  1. [MessageContract]  
  2. public class AuthorResponse  
  3. {  
  4.     [MessageBodyMember]  
  5.     public Auther Obj;  
  6. }  

Data Contract in WCF

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged.

Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type, for which you have to define a Data contract using [DataContract] and [DataMember] attribute.

A data contract can be defined as follows:
  • It describes the external format of data passed to and from service operations.
  • It defines the structure and types of data exchanged in service messages.
  • It maps a CLR type to an XML Schema.
  • It defines how data types are serialized and deserialized. Through serialization, you convert an object into a sequence of bytes that can be transmitted over a network. Through deserialization, you reassemble an object from a sequence of bytes that you receive from a calling application.
  • It is a versioning system that allows you to manage changes to structured data.
  1. [DataContract]   
  2. public class CuboidInfo   
  3. {   


Data Contracts define the data type for variables that are the same as get and set properties but the difference is that a Data Contract in WCF is used to serialize and deserialize the complex data. It defines how data types are serialized and deserialized. Using serialization, you can convert an object into a sequence of bytes that can be transmitted over a network. Using de-serialization, you reassemble an object from a sequence of bytes that you receive from a calling application. 

Duplex in WCF

Duplex is a Two-Way Communication Process. In which, a consumer send a message to the service and the service sends a notification that the request processing has been done. It is just like that we send some command about the printing of some papers to the Printer machine. The printer machine start communication by making the connection with our machine, and start printing the paper.
  1. Duplex service allows calling back some operation (function) on the client.
  2. Duplex service also knows as Call Backs. 
  3. All Binding does not support duplex service. 
  4. Duplex communication is not standard. They are absolute Microsoft feature. 
  5. wsDualHttpBinding supports duplex communication over HTTP binding. 
  6. Duplex communication is possible over netTcpBinding and netNamedPipeBinding

MSMQ in WCF

Microsoft Messaging Queue (MSMQ) technology is used for asynchronous communication using messages. MSMQ also can be considered to be an Inter- process communication capability.

Whenever two processes want to communicate with each other in a "Fire and Forget" manner, MSMQ is very useful for that.

Example: For example what if Billing software needs to process 1000 bills at midnight and must send mail to all those users. Such as when the operator runs the software he wants immediate notification. The operator can't wait for all the bills to be processed and gets email.

Here MSMQ plays an important role for communication by billing software to send those 1000's of customer email information into the Queue and the Queue event handler will handle the requests. In this way the Operator gets instant notification of the processes instead of knowing the "Behind the Scene" process.

SOA in WCF



SOA stands for service oriented architecture. Service Oriented Architecture is an architectural approach in software development where the application is organized as "Services". Services are a group of methods that contain the business logic to connect a DB or other services. For instance you go to a hotel and order food. Your order first goes to the counter and then it goes to the kitchen where the food is prepared and finally the waiter serves the food.

SOA is nothing but an architectural style where two non-compatible applications cancommunicate using a common language and WCF is nothing but one example of the Service Oriented Architecture (SOA).Characteristics of SOA:
  • In SOA, Services should be independent of other services. Altering a service should not affect calling service.
  • Services should be able to define themselves. Services should be able to answer a question what is does? It should be able to tell client what all operations it does, what all data types it uses and what kind of responses it will return.
  • Services should support reliable messaging. Means there should be a guarantee that request will be reached to correct destination and correct response will be obtained.
  • Services should support secure communication.

SOA is thinking, it's an architectural concept and web service is one of the technical approach to complete it. Web services are the preferred standards to achieve SOA.
  • In SOA we need the services to be loosely coupled. A web service communicates using SOAP protocol which is XML based which is very loosely coupled. SOA services should be able to describe themselves. WSDL describes how we can access the service.

What is SPA (Single page application) in Angular

Single-Page Applications (SPAs) are web applications that load a single HTML page and dynamically update that page as the user interacts with the app. SPAs use AJAX and HTML to create fluid and responsive web apps, without constant page reloads. However, this means much of the work happens on the client side, in JavaScript.

A single HTML page here means UI response page from the server. The source can be ASP, ASP.NET, ASP.NET MVC, JSP and so on.

A single-page web application, however, is delivered as one page to the browser and typically does not require the page to be reloaded as the user navigates to various parts of the application. This results in faster navigation, more efficient network transfers, and better overall performance for the end user.



Key Points of Single-Page Applications
  • The application is responsive in the UI with no page flicker
  • The Back/Forward buttons work as expected
  • More JavaScript than actual HTML
  • Dynamic data loading from the server-side API works with restful web service with JSON format
  • Rich interaction among UI components
  • Fewer data transfers from the server and most of the page processes in the UI occurs client-side.
  • The application contains tabs and subtabs with multiple HTML containers on the click of the tabs or subtabs and the specific portions of the page that are loaded into the page (the page will be one using the application)
  • Applications written in AngularJS are cross-browser compliant. Angular automatically handles the JavaScript code suitable for each browser.

Monday 12 December 2016

Routing and Attributes Routing in MVC

In .NET technology, we have seen lot of different ways to hit some specific resource or URI. In ASP.NET, we use Url Rewriting where as in ASP.NET MVC, there are two more options, first one is Convention Based Routing and other one is Attribute Routing.

What is Convention Based Routing in ASP.NET MVC?

Routing is a mechanism which is used to handle the incoming requests coming from browsers and it represent the particular action rather than any static or physical files. In ASP.NET, the Url hits any resources or files which physically exists but ASP.NET MVC Routing represents action. It is an approach to perform some action based on their definition defined in RouteConfig.cs.

Convention Based Routing
  1. public static void RegisterRoutes(RouteCollection routes)  
  2. {  
  3.     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.     routes.IgnoreRoute("favicon.ico");  
  5.     routes.IgnoreRoute("Content/img/dotnet-tutorial.ico");  
  6.     routes.MapRoute("LogOff""logOff"new  
  7.     {  
  8.         controller = "Account", action = "logoff"  
  9.     });  
  10.     routes.MapRoute("Register""register"new  
  11.     {  
  12.         controller = "Account", action = "Register"  
  13.     });  
  14.     routes.MapRoute("AboutUs""aboutus"new  
  15.     {  
  16.         controller = "Home", action = "AboutUs"  
  17.     });  
  18.     routes.MapRoute("IndividualArticlesPost""articles/{categoryslug}/{url}"new  
  19.     {  
  20.         controller = "Articles", action = "View"  
  21.     }, new  
  22.     {  
  23.         categoryslug = @ "\S+", url = @ "\S+"  
  24.     });  
  25.     routes.MapRoute("Default"// Route name  
  26.         "{controller}/{action}/{id}"// URL with parameters  
  27.         new  
  28.         {  
  29.             controller = "Home",  
  30.                 action = "Index",  
  31.                 id = UrlParameter.Optional  
  32.         });  
  33. }  
In the above code, you can see three things: “routes”, “IgnoreRoute” and “MapRoute”.

Routes: It is nothing but only a table which is a collection of routes defined in route table. When someone hits some url in the browser, application first check the existing routes table and match with routes.

IgnoreRoute: It is also a collection of url that should be ignored by application.

MapRoute: It is used to add new route into the route table.



Attribute Routing
ASP.NET MVC also supports new type of routing that is called Attribute Routing. In this, attribute participate to route url to particular action.

To enable attribute routing, we need to use MapMvcAttributeRoutes() in the RouteConfig
  1. public class RouteConfig  
  2. {  
  3.     public static void RegisterRoutes(RouteCollection routes)  
  4.     {  
  5.         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  6.         // Attribute Routing  
  7.         routes.MapMvcAttributeRoutes();  
  8.         // Convention Based Routing  
  9.         routes.MapRoute("LogOff""logOff"new  
  10.         {  
  11.             controller = "Account", action = "logoff"  
  12.         });  
  13.         routes.MapRoute("Register""register"new  
  14.         {  
  15.             controller = "Account", action = "Register"  
  16.         });  
  17.         routes.MapRoute("AboutUs""aboutus"new  
  18.         {  
  19.             controller = "Home", action = "AboutUs"  
  20.         });  
  21.         routes.MapRoute("IndividualArticlesPost""articles/{categoryslug}/{url}"new  
  22.         {  
  23.             controller = "Articles", action = "View"  
  24.         }, new  
  25.         {  
  26.             categoryslug = @ "\S+", url = @ "\S+"  
  27.         });  
  28.         routes.MapRoute("Default"// Route name  
  29.             "{controller}/{action}/{id}"// URL with parameters  
  30.             new  
  31.             {  
  32.                 controller = "Home",  
  33.                     action = "Index",  
  34.                     id = UrlParameter.Optional  
  35.             });  
  36.     }  
  37. }  


Note: Attribute Routing is configuring before the Convention Routing or simple Routing.

We can use Convention based Routing and Attribute Routing in the same project. Be sure attribute routing should be defined first to convention based routing.
  1. public static void RegisterRoutes(RouteCollection routes)  
  2. {  
  3.     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.     routes.MapMvcAttributeRoutes();  
  5.     routes.MapRoute(name: "Articles", url: "{controller}/{action}/{id}", defaults: new  
  6.     {  
  7.         controller = "Article", action = "Index", id = UrlParameter.Optional  
  8.     });  
  9.     routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new  
  10.     {  
  11.         controller = "Home", action = "Index", id = UrlParameter.Optional  
  12.     });  
  13. }  
Sample Example

The following is a sample example of attribute routing. Here you can see we have used [Route] attribute to route the action with “Home/Index”. When we define the Route attribute, it added route to route table and mapped with specific action.
  1. public class ArticleController: Controller  
  2. {  
  3.     [Route("Home/Index")] //Route: /Home/Index  
  4.     public ActionResult Index()  
  5.     {  
  6.         return View();  
  7.     }  
  8. }  
Note: If route URI is not defined in attribute routing then it will work as Convention Routing.

Comman Route Prefix with Attribute Routing
To make your url neat, clear and user friendly, we can define the prefix in URL after domain name. We can use RoutePrefix attribute to define the prefix.
  1. [RoutePrefix("Articles")]  
  2. public class ArticleController: Controller  
  3. {  
  4.     [Route("{id}")] //Route: /Articles/13  
  5.     public ActionResult Details(int id)  
  6.         {  
  7.             //other code goes here  
  8.         }  
  9.         [Route("{username}")] //Route: /Articles/mukeshkumar  
  10.     public ActionResult MyArticleDetails(string username)  
  11.     {  
  12.         //other code goes here  
  13.     }  
  14. }  
Override the common route prefix with Attribute Routing
Sometimes, it is required to show different prefix in url with particular action. If you have already defined the Prefix for the whole controller then you can override it. To override the RoutePrefix, use ~ sign with prefix name with particular action in the Route attribute.
  1. [RoutePrefix("Articles")]  
  2. public class ArticleController: Controller  
  3. {  
  4.     [Route("~/ArticleList/{id}")] //Route: /ArticleList/13  
  5.     public ActionResult Details(int id)  
  6.     {  
  7.         //other code goes here  
  8.     }  
  9. }  
Route Constraints with Attribute Routing
When we use Route Constraints with Route attribute, it basically restrict or force how parameters will match.
  1. public class ArticleController: Controller  
  2. {  
  3.     [Route("Articles/{id:int}")] //Route: /Articles/13  
  4.     public ActionResult Details(int id)  
  5.         {  
  6.             //other code goes here  
  7.         }  
  8.         [Route("Articles/{username}")] //Route: /Articles/mukeshkumar  
  9.     public ActionResult GetUserDetails(string username)  
  10.     {  
  11.         //other code goes here  
  12.     }  
  13. }  
In the above code, if you pass integer value as parameter after “Articles/” then it will hit to first route otherwise second.

Attribute Routing in Area of ASP.NET MVC
In we are using Area in ASP.NET MVC project and want to use attribute routing, we need to use RouteArea attribute to define the area name and all will be same.
  1. [RouteArea("Admin")]  
  2. [RoutePrefix("Home")]  
  3. [Route("{action}")]  
  4. public class HomeController: Controller  
  5. {  
  6.     // route: /Admin/Home/Index  
  7.     public ActionResult Index()  
  8.         {  
  9.             return View();  
  10.         }  
  11.         // route: /Admin/Home/Employees  
  12.         [Route("employees")]  
  13.     public ActionResult GetEmployees()  
  14.         {  
  15.             return View();  
  16.         }  
  17.         // route: /department  
  18.         [Route("~/Department")]  
  19.     public ActionResult Departments()  
  20.     {  
  21.         return View();  
  22.     }  
  23. }  
Name attribute
As we use Custom Routing in ASP.NET MVC. We can achieve Custom Routing to define the Name of Route and use this route on the basis of Route name.
  1.  [Route("Articles", Name = "MyArticle")]  
  2.  public ActionResult GetAllArticle()  
  3.  {  
  4.  }  
  5. <a href="@Url.RouteUrl("MyArticle ")">My Article</a>  
Which One is the Best
As per our opinion, Attribute Routing provides us more flexibilities as compared to Convention Based Routing. In Attribute Routing, we can manage route as controller level, action level and also area level. Also, it can override the child route, if required.

This is only my opinion; you can try it and see which one is better.