Thursday, 27 July 2017

Various types of WCF bindings

Choosing an Appropriate WCF binding



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 (which are still using ASMX web service) can consume new service. By default, it uses Http protocol for transport and encodes the message in UTF - 8 text for-mat. 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 by using HTTP-GET, HTTP-POST. It is used with REST based services which may give output as an 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 as 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 as wsHttpBinding except it supports bi-directional communication 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 with in intranet (means same network). It encodes the message in binary format. This is faster and more reliable binding as compared to the Http protocol bindings. It is only used when communication is WCF - to – WCF 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 sup-port to disconnected message queued. It provides solutions for disconnected scenarios in which service processes the message at a different time than the client send 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.

Peer Network binding

This binding is provided by the NetPeerTcpBinding class. It uses TCP protocol but uses peer networking as transport. In this networking each machine (node) acts as a client and a server to the other nodes. This is used in the file sharing systems like torrent.

MSMQ Integration binding

This binding is provided by the MsmqIntegrationBinding class. This binding offers support to communicate with existing systems that communicate via MSMQ.
Continue Reading →

Download RDLC File in PDF Format

In This Article The below Code is for, to download Rdlc report content in PDF Format.

        protected void btnExport_Click(object sender, EventArgs e)
        {
            Warning[] warnings;
            string[] streams;
            string reportType = "PDF";
            string mimeType;
            string encoding;
            string fileNameExtension;
            string deviceInfo = "";

            byte[] renderedBytes = rptViewer.LocalReport.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
            Response.ClearHeaders();
            Response.Clear();
            Response.ContentType = mimeType;
            string FileName = ("ECOMMERCEReport" + DateTime.Now.Date.ToString()) + "." + fileNameExtension;
            Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
            Response.BinaryWrite(renderedBytes);
            Response.End();
        }


Continue Reading →

Tuesday, 25 July 2017

Message Exchange Patterns (MEPs) - WCF

Windows Communication Foundation supports the following Message Exchange Patterns (MEPs):
  • Request/Response
  • One Way
  • 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 (void return type), 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. OneWay MEP will work in such scenarios. If we want queued message delivery, OneWay 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.




Continue Reading →

Friday, 14 July 2017

Method Overloading in WCF

Method overloading is the process of implementing Polymorphism in Object-Oriented Programming. A method can be overloaded on the basis of type of parameters, number of parameters, and an order of parameters.
As we know, WCF code is always coded on OOP's based programming language so that it does support method overloading.

Service Interface

[ServiceContract]
public interface ITest
{
    [OperationContract]
    string TestMethod(int para1,int para2);
    //Initail method
    [OperationContract]
    string TestMethod(string para1, string para2);
    //Overloading on the basis of type of parameters.
    [OperationContract]
    string TestMethod(int para1, string para2);
    //Overloading on the basis of  an order of parameters.
    [OperationContract]
    string TestMethod(int para1, string para2,double para3);
    //Overloading on the basis of the numbers of parameters
}

Service implementation



public class Test : ITest
{

    public string TestMethod(int para1, int para2)
    {
        return "TestMethod1";
    }

    public string TestMethod(string para1, string para2)
    {
        return "TestMethod2";
    }

    public string TestMethod(int para1, string para2)
    {
        return "TestMethod3";
    }

    public string TestMethod(int para1, string para2, double para3)
    {
        return "TestMethod4";
    }
}

Issues of method overloading in WCF


Once test the above code on WCF test client, it will throw an error contract mismatch because of the WSDL that does n't allow to create duplicate methods for clients.

Error: Cannot obtain Metadata from http://localhost:61489/Test.svc If this is a Windows (R) Communication Foundation 
service to which you have access, please check that you have enabled metadata publishing at the specified address. 
For help enabling metadata publishing, 
please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata

Exchange Error    URI: http://localhost:61489/Test.svc    Metadata contains a reference that cannot 

be resolved: 'http://localhost:61489/Test.svc'.    The server did not provide a meaningful reply; this might 
be caused by a contract mismatch, a premature session shutdown or an internal server error.

HTTP GET Error    URI: http://localhost:61489/Test.svc    There was an error downloading 

'http://localhost:61489/Test.svc'.    The request failed with the error message:--<html>
<head>        <title>The type 'MethOverWCF.Test', provided as the Service attribute
value in the ServiceHost directive, or provided in the configuration element 
system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found

Solution of method overloading issue in WCF



By adding unique operationcontract behavior, we can be achieved method overloading in WCF.OperationContract has the Name property that exposes the WCF methods to WSDL Schemas.

[ServiceContract]
public interface ITest
{
    [OperationContract(Name="Method1")]
    string TestMethod(int para1,int para2);
    //Initail method
    [OperationContract(Name = "Method2")]
    string TestMethod(string para1, string para2);
    //Overloading on the basis of type of parameters.
    [OperationContract(Name = "Method3")]
    string TestMethod(int para1, string para2);
    //Overloading on the basis of  an order of parameters.
    [OperationContract(Name = "Method4")]
    string TestMethod(int para1, string para2,double para3);
    //Overloading on the basis of the numbers of parameters
}

Creating Client and Consuming overloaded WCF service methods

In WCF client, all service methods are called by exact same name as define in the OperationContract but method overloaded methods are called by their attribute name. In the given sample code has four different attributes (Method1Method2Method3, and Method4) which are exposed by overloaded TestMethod of WCF.


using WCFConsoleClentApp.MyTest;
namespace WCFConsoleClentApp
{
    class Program
    {
        static void Main(string[] args)
        {
            TestClient client = new TestClient();
            string callMethod1 = client.Method1(1, 1);
            string callMethod2 = client.Method2("Test", "Test");
            string callMethod3 = client.Method3(1, "Test");
            string callMethod4 = client.Method4(1, "Test", 3.5);
        }
    }
}



Continue Reading →

Wednesday, 12 July 2017

Abstract Class level Interview Questions - C#

Output Related Programs.

   public abstract class absClass
    {
        public abstract string sayhello();
    }

    public class childClass : absClass
    {
        public override string sayhello()
        {
            return "hello";
        }
    }
    public class childClass2
    {
        public string getName()
        { return "suraj"; }
    }


 public class Program2
    {
      
        static void Main()
        {
           
            absClass absObj = new absClass(); 
// Cannot create an instance of the abstract class or interface 'absClass'
            absClass absObj2 = new childClass();
            absClass absObj3 = new childClass2();
//Cannot implicitly convert type 'testDemo.childClass2' to 'testDemo.absClass'
            childClass obj1 = new childClass();
            childClass obj2 = new absClass(); 
//Cannot create an instance of the abstract class or interface 'absClass'
            childClass obj3 = new childClass2(); 
//Cannot implicitly convert type 'testDemo.childClass2' to 'testDemo.childClass'
            childClass2 cobj1 = new childClass2();
            childClass2 cobj2 = new childClass();
//Cannot implicitly convert Cannot implicitly convert type 'testDemo.childClass' to 'testDemo.childClass2'
            
            childClass2 cobj3 = new absClass(); 
//Cannot create an instance of the abstract class or interface 'absClass'
            
            Console.Read();
        }

       
    }
Continue Reading →

lock Statement- C#

The lock keyword marks a statement block as a critical section by obtaining the mutual-exclusion lock for a given object, executing a statement, and then releasing the lock. The following example includes a lock statement.

class Account { decimal balance; private Object thisLock = new Object(); public void Withdraw(decimal amount) { lock (thisLock) { if (amount > balance) { throw new Exception("Insufficient funds"); } balance -= amount; } } }

Remarks

The lock keyword ensures that one thread can not enter in a critical section of code while another thread is in the critical section. If another thread tries to enter a locked code, it will wait, block, until the object is released.

References: click here
Continue Reading →

Tuesday, 11 July 2017

$Broadcast(), $Emit() And $On() In AngularJS

AngularJS applications may need to communicate across the controllers. Such a communication might be needed to send notifications or to pass data between the controllers. Although there can be different approaches to achieve this goal, one that is readily available is the event system of $scope and $rootScope. Both of these objects - $scope and $rootScope - support three methods namely $broadcast(), $emit() and $on() that facilitate event driven publisher-subscriber model for sending notifications and passing data between the controllers. In this article I will discuss how to raise events using $broadcast() and $emit() and then how to handle those events using $on().

Overview of $broadcast(), $emit() and $on()

Before you dig into the examples discussed below it would be worthwhile to take a quick look at the purpose and use of $broadcast(), $emit() and $on().
$broadcast() as well as $emit() allow you to raise an event in your AngularJS application. The difference between $broadcast() and $emit() is that the former sends the event from the current controller to all of its child controllers. That means $broadcast() sends an even downwards from parent to child controllers. The $emit() method, on the other hand, does exactly opposite. It sends an event upwards from the current controller to all of its parent controllers. From the syntax point of view a typical call to $broadcast() and $emit() will look like this:

$scope.$broadcast("MyEvent",data);
$scope.$emit("MyEvent",data); 

Here, MyEvent is the developer defined name of the event that you wish to raise. The optional data parameter can be any type of data that you wish to pass when MyEvent is dispatched by the system. For example, if you wish to pass data from one controller to another that data can go as this second parameter.

An event raised by $broadcast() and $emit() can be handled by wiring an event handler using $on() method. A typical call to $on() will look like this:

$scope.$on("MyEvent", function(evt,data){ 
  // handler code here });

Now that you know what $broadcast(), $emit() and $on() do let's put them to use in the following examples.

Event system on $scope and $rootScope

When it comes to communicating between two or more AngularJS controllers there can be two possible arrangements:
  • Controllers under consideration are nested controllers. That means they have parent-child relationship.
  • Controllers under consideration are sibling controllers. That means they are at the same level without any parent-child relationship.
In the former case you will use $broadcast(), $emit() and $on() on the $scope object whereas in the later case you will use these methods on the $rootScope object. Let's see each of the possibility with an example.

Nested controllers

To see how $broadcast(), $emit() and $on() can be used with nested controllers, you will develop a simple application as shown below:


The above application consists of three AngularJS controllers - MyController1, MyController2 and MyController3 - nested inside each other. The outermost <div> (MYController1) has a button for raising an event handled SendDown. Similarly, the innermost <div> (MyController3) has a button for raising an event named SendUp. Thus the SendDown event is raised in MyController1 and can be handled by MyController1, MyController2 and MyController3. On the same lines SendUp event us raised inside MyController3 and is handled by MyController3, MyController2 and MyController1. Notice that although both the events look similar, the SendDown event travels from MyController1 to MyController3 whereas SendUp travels from MyController3 to MyController1.

Both the events send a string data ("some data") when the corresponding event is dispatched. You can easily substitute an object instead of string data. Upon handling the respective events a message is shown inside each <div> just to confirm that the handler has indeed executed and the data is received successfully.

Ok. Now let's see the code of all the controllers mentioned above. The MyController1 looks like this:

app.controller("MyController1", function ($scope, $rootScope) {

    //broadcast the event down
    $scope.OnClick = function (evt) {
        $scope.$broadcast("SendDown", "some data");
    }

    //handle SendDown event
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside SendDown handler 
                          of MyController1 : " + data;
    });

    //handle SendUp event
    $scope.$on("SendUp", function (evt, data) {
        $scope.Message = "Inside SendUp handler 
                          of MyController1 : " + data;
    });
});

MyController1 does three things. Firstly, it raises SendDown event using $broadcast() method. It uses $broadcast() because we wish to send the event from parent controller to child controllers. So, the SendData is dispatched by MyController inside the click event handler of the Broadcast button. Secondly, MyController1 handles SendData event using $on(). Since SendData is raised by MyController itself this step might not be needed at all. I am still handling the event just to point out that something like that is possible. The SendDown handler simply sets Message property of the $scope object. This Message will be displayed in the corresponding <div> element. Thirdly, MyController1 handles SendUp event. Recollect that this event is raised by MyController3 in the upward direction (child to parent) and MyController1 simply handles it.

The code of MyController2 is quite straightforward and is shown below:

app.controller("MyController2", function ($scope, $rootScope) {

    //handle SendDown event
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside SendDown handler of 
                          MyController2 : " + data;
    });

    //handle SendUp event
    $scope.$on("SendUp", function (evt, data) {
        $scope.Message = "Inside SendUp handler of 
                          MyController2 : " + data;
    });

});

MyController2 simply handles SendDown and SendUp events and sets Message property on the $scope object.

Finally, MyController3 does the following:

app.controller("MyController3", function ($scope, $rootScope) {

    //handle SendDown event
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside SendDown handler of 
                          MyController3 : " + data;
    });

    //emit SendUp event up
    $scope.OnClick = function (evt) {
        $scope.$emit("SendUp", "some data");
    }

    //handle SendUp event
    $scope.$on("SendUp", function (evt, data) {
        $scope.Message = "Inside SendUp handler of 
                          MyController3 : " + data;
    });
});

MyController3 is quite similar to MyController1. However, it raises SendUp event using $emit() method. This way SendUp event travels from child (MyController3) to the parents (MyController2 and MyController1). The event handlers of SendDown and SendUp simply assign the Message property.

The HTML markup of the page will look like this:

<body ng-app="MyApp">
 <div ng-controller="MyController1">
  <input type="button" value="Broadcast Down" 
         ng-click="OnClick($event)" />
  <h4>{{Message}}</h4>
   <div ng-controller="MyController2">
    <h4>{{Message}}</h4>
    <div ng-controller="MyController3">
     <h4>{{Message}}</h4>
     <input type="button" value="Emit Up" 
            ng-click="OnClick($event)" />
    </div>
   </div>
  </div>
</body>

If you run the application and click on the Broadcast button you should get results as shown above. Clicking on Emit button will produce the following result:


Sibling controllers

The above examples achieves communication and passes data between controllers having parent-child relationship. What if you wish to achieve the communication between sibling controllers? If so, you need to use $rootScope instead of $scope. That's because since there is no parent-child relationship, each controller will have its own scope and there won't be any inherited scope as in the previous example. Moreover, $emit() won't serve much purpose in case of sibling controllers. This is because $rootScope is a container scope for all the other scopes and can dispatch events only to its child controllers. So, only $broadcast() will serve some useful purpose in this case.

Assuming that there are three sibling controllers - MyController1, MyController2 and MyController3 - the application will take this form:


As before there are three controllers but they are siblings. The topmost <div> (MyController1) has Broadcast button that raises SendDown event on $rootScope object. All the controllers handle the SendData event and set Message property on their individual $scope object. The complete code of all the three controllers is shown below:

app.controller("MyController1", function ($scope, $rootScope) {
    //raise event on $rootScope
    $scope.OnClick = function (evt) {
        $rootScope.$broadcast("SendDown", "some data");
    }

    //event handler
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside MyController1 : " + data;
    });

});

app.controller("MyController2", function ($scope, $rootScope) {
    //event handler
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside MyController2 : " + data;
    });

});

app.controller("MyController3", function ($scope, $rootScope) {
    //event handler
    $scope.$on("SendDown", function (evt, data) {
        $scope.Message = "Inside MyController3 : " + data;
    });
});

As you can see, this time $broadcast() is called on $rootScope object to raise SendDown event. SendDown is handled by individual $scope objects as before.
A word of caution before I conclude this article - although event system discussed above looks straightforward and simple, if used excessively it can get messy in terms of overall management and application flow. So, give a thought before you jump in to raise too many events.

That's it for this article! Keep coding.

Continue Reading →

Monday, 10 July 2017

Select and SelectMany in LINQ

Select and SelectMany are projection operators. Select operator is used to select value from a collection and SelectMany operator is used to select values from a collection of collection i.e. nested collection.

Example: 

class Employee
{
 public string Name { get; set; }
 public List<string> Skills { get; set; }
}
 
class Program
{
 static void Main(string[] args)
 {
 List<Employee> employees = new List<Employee>();
 Employee emp1 = new Employee { Name = "Deepak", Skills = new List<string> { "C", "C++", "Java" } };
 Employee emp2 = new Employee { Name = "Karan", Skills = new List<string> { "SQL Server", "C#", "ASP.NET" } };
 
 Employee emp3 = new Employee { Name = "Lalit", Skills = new List<string> { "C#", "ASP.NET MVC", "Windows Azure", "SQL Server" } };
 
 employees.Add(emp1);
 employees.Add(emp2);
 employees.Add(emp3);
 
 // Query using Select()
 IEnumerable<List<String>> resultSelect = employees.Select(e=> e.Skills);
 
 Console.WriteLine("**************** Select ******************");
 
 // Two foreach loops are required to iterate through the results
 // because the query returns a collection of arrays.
 foreach (List<String> skillList in resultSelect)
 {
 foreach (string skill in skillList)
 {
 Console.WriteLine(skill);
 }
 Console.WriteLine();
 }
 
 // Query using SelectMany()
 IEnumerable<string> resultSelectMany = employees.SelectMany(emp => emp.Skills);
 
 Console.WriteLine("**************** SelectMany ******************");
 
 // Only one foreach loop is required to iterate through the results 
 // since query returns a one-dimensional collection.
 foreach (string skill in resultSelectMany)
 {
 Console.WriteLine(skill);
 }
 
 Console.ReadKey();
 }
}
 
/* Output
 
**************** Select ******************
 
C
C++
Java
 
SQL Server
C#
ASP.NET
 
C#
ASP.NET MVC
Windows Azure
SQL Server
 
**************** SelectMany ******************
 
C
C++
Java
SQL Server
C#
ASP.NET
C#
ASP.NET MVC
Windows Azure
SQL Server
*/
Continue Reading →

Thursday, 6 July 2017

Scopes in AngularJS Custom Directives

In this post we will learn about different kinds of scopes in AngularJS custom directives. First we’ll start with a high level introduction of directives and then focus on scopes.

Directives

Directives are one of the most important components of AngularJS 1.X, and have the following purposes:
1.       Gives special meaning to the existing element
2.       Creates a new element
3.       Manipulates the DOM

Beyond ng-app, ng-controller, and ng-repeat, there are plenty of built-in directives that come with AngularJS, including:
·         ng-maxlength
·         ng-minlength
·         ng-pattern
·         ng-required
·         ng-submit
·         ng-blur
·         ng-change
·         ng-checked
·         ng-click
·         ng-mouse
·         ng-bind
·         ng-href
·         ng-init
·         ng-model
·         ng-src
·         ng-style
·         ng-app
·         ng-controller
·         ng-disabled
·         ng-cloak
·         ng-hide
·         ng-if
·         ng-repeat
·         ng-show
·         ng-switch
·         ng-view

Mainly, directives perform either of the following tasks:
·         Manipulate DOM
·         Iterate through data
·         Handle events
·         Modify CSS
·         Validate data
·         Data Binding

Even though there are many built-in directives provided by the Angular team, there are times when you might need to create your own custom directives. A custom directive can be created either as an element, attribute, comment or class. In this post, a very simple custom directive can be created as shown in the listing below:


MyApp.directive('helloWorld', function () {
    return {
        template: "Hello IG"
    };
});

While creating custom directives, it’s important to remember:

• The directive name must be in the camel case;
• On the view, the directive can be used by separating the camel case name by using a dash, colon, underscore, or a combination of these.

Scopes in Custom Directives

Scopes enter the scene when we pass data to custom directives. There are three types of scopes:

1.       Shared scope
2.       Inherited scope
3.       Isolated scope

Shared scope
This type is requested when scope is false in the definition object or when scope is not specified (false is the default value of the property).
Shared scope simply means that the directive works with the same scope that is already available for the DOM node where the directive appears without creating a new one.


// 1. Shared scope (scope: false)
  .directive("nghSharedScopeDir", function ()
  {
    return {
      scope: false,
      template:
        '<label>First name: <input type="text" ng-model="firstName"/></label><br />' +
        '<label>Last name: <input type="text" ng-model="lastName"/></label><br />' +
        '<br />' +
        '<strong>First name:</strong> {{firstName}}<br />' +
        '<strong>Last name:</strong> {{lastName}}'
    };
  })

Inherited scope
This type is requested when scope is true in the definition object.
A new scope is created for our directive, but it inherits all the properties of the parent scope through JavaScript's prototypal inheritance: when the directive accesses a property on it's new scope, the property is first searched on the current scope and if it's found then it's value is returned, otherwise, if it's not found, the same property name is searched in the parent scope and that value is returned (the search traverses all the parents until the property is found or until there are no more parents); if a value is assigned to a property on the new directive's scope and the same property already exists in the parent, accessing the property value directly in the new scope will in fact override the parent's property value and any change to the property in the parent will not be propagated anymore to the child scope.


// 2. Inherited scope (scope: true)
  .directive("nghInheritedScopeDir", function ()
  {
    return {
      scope: true,
      template:
        '<label>First name: <input type="text" ng-model="firstName"/></label><br />' +
        '<label>Last name: <input type="text" ng-model="lastName"/></label><br />' +
        '<br />' +
        '<strong>First name:</strong> {{firstName}}<br />' +
        '<strong>Last name:</strong> {{lastName}}'
    };
  })

Isolated Scope
In Isolated scope, the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.
1.       Data can be passed as a string using the @ string literal
2.       Data can be passed as an object using the = string literal
3.       Data can be passed as a function using  the & string literal

// 3. Isolated scope (scope: {})
  .directive("nghIsolatedScopeDir", function ()
  {
    return {
      scope:
        {
          firstName: '@dirFirstName',
          lastName: '=dirLastName',
          setNameMethod: '&dirUpdateNameMethod'
        },
      template:
        '<label>First name: <input type="text" ng-model="firstName"/></label><br />' +
        '<label>Last name: <input type="text" ng-model="lastName"/></label><br />' +
        '<button ng-click="execSetNameMethod()">Set name on external scope</button><br />' +
        '<br />' +
        '<strong>First name:</strong> {{firstName}}<br />' +
        '<strong>Last name:</strong> {{lastName}}',
      link: function (scope, element, attrs)
      {
        scope.execSetNameMethod = function ()
        {
          scope.setNameMethod(
            {
              newFirstName: scope.firstName,
              newLastName: scope.lastName
            });
        };
      }
    };
  })


Continue Reading →

New Features in ASP.NET Web API 2

ASP.NET Web API 2 has been released with a number of new exciting features.

1. Attribute Routing
Along with convention-based routing, Web API 2 now supports attribute routing as well.

In case of convention-based routing, we can define multiple route templates. When a request comes, it will be matched against already defined route templates, and forwarded to specific controller action according to matched template.

You can see the following default route template in routing table for Web API:





Config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{Controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

This routing approach has benefits that all routing templates are defined at one common location but for certain URI patterns, it really becomes difficult to support (like nested routing on same controller).

With ASP.NET Web API 2, we can easily support above mentioned URI pattern and others as well. Following shows an example of a URI pattern with attribute routing. URI Pattern --> books/1/authors



[Route("books/{bookId}/authors")]
public IEnumerable<Author> GetAuthorByBook(int bookId) { ..... }

2. CORS - Cross Origin Resource Sharing
Normally, browsers don't allow making cross-domain calls due to same-origin policy and we know that. So, what exactly is CORS (Cross Origin Resource Sharing)?

CORS is a mechanism that allows a web page to make an AJAX call to a domain other than the domain which actually rendered that specific web page. CORS is compliant with W3C standards and now ASP.NET Web API has support for it in version 2.

3. OWIN (Open Web Interface for .NET) self hosting
ASP.NET Web API 2 comes with a new self hosting package i.e. Microsoft.AspNet.WebApi. OwinSelfHost.   According to http://owin.org/
“OWIN defines a standard interface between .NET web servers and web applications. The goal of the OWIN interface is to decouple server and application, encourage the development of simple modules for .NET web development, and, by being an open standard, stimulate the open source ecosystem of .NET web development tools.”

So, according to above description, OWIN is an ideal option for self hosting a web application in a process other than IIS process.

There are a number of OWIN implementations like Giacomo, Kayak, Firefly etc. available (some may be partial or outdated) but Katana is the recommended one for Microsoft servers and Web API frameworks.

4. IHttpActionResult
Along with the existing two approaches of creating response from controller action, ASP.NET Web API 2 now supports another way of doing the same. IHttpResponseMessage is basically an interface which acts as a factory for HttpResponseMessage. It's very powerful because it extensify web api. Using this approach we can compose any specific type of response.
Please follow the link to know how to serve HTML with IHttpActionResult.

5. Web API OData
The Open Data Protocol (OData) is actually a web protocol for querying and updating data. ASP.NET Web API 2 has added support for $expand, $select, and $value options for OData. By using these options, we can control the representation that is returned from the server.

$expand: Normally, response doesn’t include related entities if we query an OData collection. By using $expand, we can get related entities inline in response.
$select: It’s used if we wanted to include subset of properties in response instead of all.
$value: It allows to return raw value of the property instead returning in OData format.
Continue Reading →

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)