Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Tuesday, 31 October 2017

Create RESTful WCF Service

Introduction

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types. In this article, I am going to explain how to implement restful service API using WCF 4.0 . The Created API returns XML and JSON data using WCF attributes.

What is REST?

Based on the Roy Fielding theory "Representational State Transfer (REST), attempts to codify the architectural style and design constraints that make the Web what it is. REST emphasizes things like separation of concerns and layers, statelessness, and caching, which are common in many distributed architectures because of the benefits they provide. These benefits include interoperability, independent evolution, interception, improved scalability, efficiency, and overall performance."
Actually only the difference is how clients access our service. Normally, a WCF service will use SOAP, but if you build a REST service, clients will be accessing your service with a different architectural style (calls, serialization like JSON, etc.).
REST uses some common HTTP methods to insert/delete/update/retrieve information which is below:
  1. GET - Requests a specific representation of a resource
  2. PUT - Creates or updates a resource with the supplied representation
  3. DELETE - Deletes the specified resource
  4. POST - Submits data to be processed by the identified resource

Why and Where to Use REST?

Few days back, I was writing a service which was supposed to be accessed by heterogeneous language/platform/system. It can be used by iPhone, Android, Windows Mobile, .NET web application, JAVA or PHP. Using web service, it was bit complex for me to expose it to everyone using uniform system. Then we decided to use REST, which was easily espoused over cloud. This was a great example which shows the capability of SIMPLE RESTful SERVICE :). Below are some points which will help you to understand why to use the RESTful services.
  1. Less overhead (no SOAP envelope to wrap every call in)
  2. Less duplication (HTTP already represents operations like DELETEPUTGET, etc. that have to otherwise be represented in a SOAP envelope).
  3. More standardized - HTTP operations are well understood and operate consistently. Some SOAP implementations can get finicky.
  4. More human readable and testable (harder to test SOAP with just a browser).
  5. Don't need to use XML (well, you kind of don't have to for SOAP either but it hardly makes sense since you're already doing parsing of the envelope).
  6. Libraries have made SOAP (kind of) easy. But you are abstracting away a lot of redundancy underneath as I have noted. Yes, in theory, SOAP can go over other transports so as to avoid riding atop a layer doing similar things, but in reality just about all SOAP work you'll ever do is over HTTP.

Step by Step Guide

Generally, a developer is scared to use WCF because of a lot of confusing configuration. I will try to use minimum configuration so that it will be easier to understand for us. We will develop Restful WCS API in 6 steps. So let’s start now.

STEP 1

First of all launch Visual Studio 2010. Click FILE->NEW->PROJECT. Create new "WCF Service Application".

STEP 2

Once you create the project, you can see in solution that By Default WCF service and interface file are already created. Delete By default created file as we will create our own interface and WCF service file.

STEP 3

Now right click on solution and create one new WCF service file. I have given name to the service file as “RestServiceImpl.svc”.

STEP 4

As I explained at the start of the article that we will be writing an API which can return data in XML and JSON format, here is the interface for that. In IRestServiceImpl, add the following code:

In the above code, you can see two different methods of IRestService which are XMLData and JSONDataXMLData returns result in XML whereas JSONData in JSON.

STEP 5

Open the file RestServiceImpl.svc.cs and write the following code over there:

STEP 6

Now let’s move to configuration part which is the last one. There will be two basic parts of the configurations file which we must have to understand.
<services> 
This part contains information about the End Point. Below are the code details.
Click to enlarge image
<behaviors>
This part contains details about service and endpoint behavior.

And that’s it. Our Restful WCF service is ready for test purposes.

Service Ready to Test Now

Now I launch the application in the browser to see the result. I launch this service in Internet Explorer and my URL is now http://localhost:35798/RestServiceImpl.svc. Now if I use http://localhost:35798/RestServiceImpl.svc/xml/123 URL, I get the following response on the browser which is an XML format and that was my task to achieve.

Now if I use http://localhost:35798/RestServiceImpl.svc/json/123 URL, I get the following response on the browser which is an XML format and that was my task to achieve.

Sunday, 29 October 2017

Difference between WCF and Web API and WCF REST and Web Service

The .Net framework has a number of technologies that allow you to create HTTP services such as Web Service, WCF and now Web API. There are a lot of articles over the internet which may describe to whom you should use. Now a days, you have a lot of choices to build HTTP services on .NET framework. In this article, I would like to share my opinion with you over Web Service, WCF and now Web API. For more information about Web API refers What is Web API and why to use it ?.

Web Service

  1. It is based on SOAP and return data in XML form.
  2. It support only HTTP protocol.
  3. It is not open source but can be consumed by any client that understands xml.
  4. It can be hosted only on IIS.

WCF

  1. It is also based on SOAP and return data in XML form.
  2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
  3. The main issue with WCF is, its tedious and extensive configuration.
  4. It is not open source but can be consumed by any client that understands xml.
  5. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest

  1. To use WCF as WCF Rest service you have to enable webHttpBindings.
  2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
  3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
  4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
  5. It support XML, JSON and ATOM data format.

Web API

  1. This is the new framework for building HTTP services with easy and simple way.
  2. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
  3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
  4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
  5. It can be hosted with in the application or on IIS.
  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

To whom choose between WCF or WEB API

  1. Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
  2. Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
  3. Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
  4. Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

Tuesday, 3 October 2017

Create RESTful WCF Service API

Introduction

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types. In this article, I am going to explain how to implement restful service API using WCF 4.0 . The Created API returns XML and JSON data using WCF attributes.

What is REST?

Based on the Roy Fielding theory "Representational State Transfer (REST), attempts to codify the architectural style and design constraints that make the Web what it is. REST emphasizes things like separation of concerns and layers, statelessness, and caching, which are common in many distributed architectures because of the benefits they provide. These benefits include interoperability, independent evolution, interception, improved scalability, efficiency, and overall performance."
Actually only the difference is how clients access our service. Normally, a WCF service will use SOAP, but if you build a REST service, clients will be accessing your service with a different architectural style (calls, serialization like JSON, etc.).
REST uses some common HTTP methods to insert/delete/update/retrieve information which is below:
  1. GET - Requests a specific representation of a resource
  2. PUT - Creates or updates a resource with the supplied representation
  3. DELETE - Deletes the specified resource
  4. POST - Submits data to be processed by the identified resource

Why and Where to Use REST?

Few days back, I was writing a service which was supposed to be accessed by heterogeneous language/platform/system. It can be used by iPhone, Android, Windows Mobile, .NET web application, JAVA or PHP. Using web service, it was bit complex for me to expose it to everyone using uniform system. Then we decided to use REST, which was easily espoused over cloud. This was a great example which shows the capability of SIMPLE RESTful SERVICE :). Below are some points which will help you to understand why to use the RESTful services.
  1. Less overhead (no SOAP envelope to wrap every call in)
  2. Less duplication (HTTP already represents operations like DELETEPUTGET, etc. that have to otherwise be represented in a SOAP envelope).
  3. More standardized - HTTP operations are well understood and operate consistently. Some SOAP implementations can get finicky.
  4. More human readable and testable (harder to test SOAP with just a browser).
  5. Don't need to use XML (well, you kind of don't have to for SOAP either but it hardly makes sense since you're already doing parsing of the envelope).
  6. Libraries have made SOAP (kind of) easy. But you are abstracting away a lot of redundancy underneath as I have noted. Yes, in theory, SOAP can go over other transports so as to avoid riding atop a layer doing similar things, but in reality just about all SOAP work you'll ever do is over HTTP.

Step by Step Guide

Generally, a developer is scared to use WCF because of a lot of confusing configuration. I will try to use minimum configuration so that it will be easier to understand for us. We will develop Restful WCS API in 6 steps. So let’s start now.

STEP 1

First of all launch Visual Studio 2010. Click FILE->NEW->PROJECT. Create new "WCF Service Application".

STEP 2

Once you create the project, you can see in solution that By Default WCF service and interface file are already created. Delete By default created file as we will create our own interface and WCF service file.

STEP 3

Now right click on solution and create one new WCF service file. I have given name to the service file as “RestServiceImpl.svc”.

STEP 4

As I explained at the start of the article that we will be writing an API which can return data in XML and JSON format, here is the interface for that. In IRestServiceImpl, add the following code:

In the above code, you can see two different methods of IRestService which are XMLData and JSONDataXMLData returns result in XML whereas JSONData in JSON.

STEP 5

Open the file RestServiceImpl.svc.cs and write the following code over there:

STEP 6

Now let’s move to configuration part which is the last one. There will be two basic parts of the configurations file which we must have to understand.
<services> 
This part contains information about the End Point. Below are the code details.
Click to enlarge image
<behaviors>
This part contains details about service and endpoint behavior.

And that’s it. Our Restful WCF service is ready for test purposes.

Service Ready to Test Now

Now I launch the application in the browser to see the result. I launch this service in Internet Explorer and my URL is now http://localhost:35798/RestServiceImpl.svc. Now if I use http://localhost:35798/RestServiceImpl.svc/xml/123 URL, I get the following response on the browser which is an XML format and that was my task to achieve.

Now if I use http://localhost:35798/RestServiceImpl.svc/json/123 URL, I get the following response on the browser which is an XML format and that was my task to achieve.

Tuesday, 26 September 2017

WCF Concurrency (Single, Multiple, and Reentrant) and Throttling

Table of contents

Introduction and goal

In this article, we will concentrate on WCF concurrency and throttling. We will first try to understand what is WCF concurrency and the three important types of WCF concurrency. We will then see a small sample of WCF concurrency with Single and Multiple. We will then go through 9 combinations of WCF concurrency and instancing. Finally we will try to understand how to configure throttling using the WCF ‘web.config’ file.



Pre-requisites

In order to understand WCF concurrency well, it’s important to understand the concepts around WCF instancing. So before moving ahead with this article, please do read about WCF instancing from here.

Why do we need concurrency in WCF?

If you search on the web for the dictionary meaning of concurrency, you will find the following definition:
“Happening at the same time”
WCF concurrency helps us configure how WCF service instances can serve multiple requests at the same time. You will need WCF concurrency for the below prime reasons; there can be other reasons as well but these stand out as important reasons:
  • Increase throughput: Many times you want to increase the amount of work your WCF service instance does at any moment of time. In other words, you would like to increase the throughput. Throughput means how much work a given thing can do.
  • By default, a WCF service handles only one request at a given moment of time.
  • Integration with a legacy system: Many times your WCF services interact with legacy systems like VB6, COM, etc. It’s very much possible that these systems are not multithreaded, in other words they handle only one request at any given time. So even though your WCF service has concurrent capabilities, you would still like to handle one request at a time. This is achieved by using throttling in combination with WCF concurrency capabilities.

WCF concurrency and instancing – Two different things

In our previous article, we had discussed about WCF instances. WCF instancing and WCF concurrency are two different things. WCF instance dictates how objects are created while WCF concurrency dictates how many requests can be handled by WCF objects.
I do understand that many of our developer friends know this difference, but as you go deeper into WCF concurrency, there is lot of connection with WCF instancing also, so I wanted to just emphasize the differences.
WCF instancing gives three levels of WCF object instance controls: per call, per session, and single. In case you are not aware of this, read my article: 3 way to do WCF instance management. In similar lines, WCF also has three ways of implementing WCF concurrency.

Three types of WCF concurrency

There are three ways by which you can handle concurrency in WCF: single, multiple, and reentrant. To specify WCF concurrency, we need to use the ServiceBehavior tag as shown below, with the appropriate ‘ConCurrencyMode’ property value.
Single: A single request has access to the WCF service object at a given moment of time. So only one request will be processed at any given moment of time. The other requests have to wait until the request processed by the WCF service is completed.
Multiple: In this scenario, multiple requests can be handled by the WCF service object at any given moment of time. In other words, requests are processed at the same time by spawning multiple threads on the WCF server object. So you have great throughput here but you need to ensure concurrency issues related to WCF server objects.
Reentrant: A single request thread has access to the WCF service object, but the thread can exit the WCF service to call another WCF service or can also call a WCF client through callback and reenter without deadlock.

Sample code demonstration

In order to demonstrate this, let’s create a simple sample code as shown below. We will create a simple WCF service with a method name Call. When a client calls this WCF service, it will display the following details:
  • Client name that made the call. This value will be provided as an input when the client wants to make a call to the WCF service.
  • Instance number, this will represent the number of WCF instances which are serving the request.
  • Thread number which is executing the method.
  • Time when the Call method was actually called.
Below is the service contract of the Call method. Please note that OperationContract is defined with IsOneWay as true.
[ServiceContract]
public interface IHelloWorldService
{
    [OperationContract(IsOneWay=true)]
    void Call(string ClientName);
}
Below is a simple implementation of the service contract IHelloWorldService interface. It has an instance variable i which helps us maintain the instance counter and a simple Console.Writeline which displays the client name, instance number, thread number, and time when the method was called.
This method waits for 5 seconds using the ‘Thread.Sleep’ function.
public class HelloWorldService : IHelloWorldService
{
    // maintain instance count 
    public int i;
    public void Call(string ClientName)
    {
        // increment instance counts
        i++;




        // display client name, instance number , thread number and time when 
        // the method was called




        Console.WriteLine("Client name :" + ClientName + " Instance:" + 
          i.ToString() + " Thread:" + Thread.CurrentThread.ManagedThreadId.ToString() + 
          " Time:" + DateTime.Now.ToString() + "\n\n");




        // Wait for 5 seconds
        Thread.Sleep(5000);
    }
}
This WCF service will be self hosted using WsHttpBinding as shown below. We have chosen self hosting so that we can monitor the time, threads, and number of instances of the WCF service.
static void Main(string[] args)
{
    //Create a URI to serve as the base address
    Uri httpUrl = new Uri("http://localhost:8010/MyService/HelloWorld");




    //Create ServiceHost
    ServiceHost host = new ServiceHost(typeof(ClassLibrary1.HelloWorldService), httpUrl); 




    //Add a service endpoint
    host.AddServiceEndpoint(typeof(ClassLibrary1.IHelloWorldService), new WSHttpBinding(), "");




    //Enable metadata exchange
    ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
    smb.HttpGetEnabled = true;
    host.Description.Behaviors.Add(smb);




    //Start the Service
    host.Open();




    Console.WriteLine("Service is host at " + DateTime.Now.ToString());
    Console.WriteLine("Host is running... Press <Enter> key to stop");
    Console.ReadLine();
}
From the client side, we will make five continuous calls simultaneously on the WCF service. Below is the code snippet for this:
Console.WriteLine("Enter Client name");
string str = Console.ReadLine();
ServiceReference1.HelloWorldServiceClient obj = 
             new ServiceReference1.HelloWorldServiceClient();




for(int i=0;i<5;i++)
{
    obj.Call(str);
}
If you run the above project and monitor your WCF server service, you will see the screenshot. There are two important points to note:
  • When you run using per call new instances are created every time the service runs. Instance 1 indicates new instances created for every method call.
  • By default the concurrency is single so the same thread is used to service all five requests which are sent from the WCF client side. You can see the value of the thread is always 4.
  • The most important factor is time. As concurrency is configured as single, it will be called one after another sequentially. You can notice this from the time difference of method calls of 5 seconds.
Let’s go and change the concurrency mode to multiple. In order to change the concurrency mode to multiple, we need to specify Multiple as the concurrency mode as shown in the below code snippet.
If you run the client now, you can see different threads (i.e., thread 4, 5, 6, 7, and 8) are spawned to serve the request and the time of the method calls are almost same. In other words, the methods are executed concurrently on different threads.
In short, you are now having a higher throughput in less amount of time.

9 combinations of Instancing and Concurrency

There are 9 combinations of concurrency and instancing as shown in the below table. In the sections below, we will discuss this in more detail.
InstanceContext
Mode
ConcurrencyMode
Single (Default)MultipleReentrant
Single
(Single instance for all clients)
Single thread for all clients.Multiple threads for all clients.Single threads for all clients, locks are released when calls diverted to other WCF services.
PerSession (Default)
(Multiple instance per client)
Single thread for every client.Multiple threads for every request.Single threads for all clients, locks are released when calls diverted to other WCF services.
PerCall (Multiple instances for every method call)Single thread for every client.Single thread for every clientSingle threads for all clients, locks are released when calls diverted to other WCF services.

Instance mode = Per Call and Concurrency = Single

With Per Call, new WCF instances are created for every method call made to the WCF server service. The default concurrency is Single so only one thread will be used to serve all instances.
Below is a simple pictorial representation of what will happen in Per Call and Single concurrency scenarios:
  • For every client instance, a single thread will be allocated.
  • For every method call, a new service instance will be created.
  • A single thread will be used to serve all WCF instances generated from a single client instance.
If you refer the previous sample, you can see how threads are the same and the halt of 5 seconds on the WCF service.

Instance mode = Per Call and Concurrency = Multiple

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall, 
                 ConcurrencyMode = ConcurrencyMode.Multiple)]
public class HelloWorldService : IHelloWorldService
{
}
In this combination, multiple instances are created for every call but multiple threads serve every method call to a WCF service instance. You can see in the below figure we have two WCF service instances and every instance has multiple WCF service objects created for every method call. Every method call is handled by multiple threads.
In the above sample, if you remember, we have multiple threads serving every method call and the time difference between every method call is reduced considerably. The method calls are fired approximately at the same time.

Instance mode = Per Session and Concurrency = Single

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession, 
                 ConcurrencyMode = ConcurrencyMode.Single)]
public class HelloWorldService : IHelloWorldService
{
}
In this combination, one WCF service instance is created for every WCF client session because the WCF instance mode is set to per session. All the method calls are executed in a sequential manner one by one. In other words, only one thread is available for all method calls for a particular service instance.
If you run the sample code with Per Session and Single combination mode, you will find the same thread executes all requests with the same WCF instance per session.

Instance mode = Per Session and Concurrency = Multiple

[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession, 
                 ConcurrencyMode = ConcurrencyMode.Multiple)]
public class HelloWorldService : IHelloWorldService
{
}
Instance mode ‘PerSession’ concurrency is the default setting in WCF
In this combination, one WCF instance is created for every WCF client session and every method call is run over multiple threads. Below is a pictorial representation:
If you run the sample code attached with this article, you will find the same instance with every method call running on different methods.
To get a better idea, you can run different client exe instances with different names as shown below. You will notice how every client gets its own WCF service instance with every method allocated to run on different threads.

Instance mode = Single and Concurrency = Single

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, 
                 ConcurrencyMode = ConcurrencyMode.Single)]
public class HelloWorldService : IHelloWorldService
{
}
In this combination, only one instance of a WCF service instance is created which serves all requests which are sent from all WCF clients. These requests are served using only one thread.
You can see in the below figure approximately one thread is assigned for every WCF client call and only one instance of the WCF service is created.

Instance mode = Single and Concurrency = Multiple

[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single, 
                 ConcurrencyMode = ConcurrencyMode.Multiple)]
public class HelloWorldService : IHelloWorldService
{}
In this combination, one WCF service instance is created for serving all WCF clients. All requests are served using multiple / different threads.
You can see from the output that we have 6 threads serving 10 requests, as compared to previously we had approximately only two threads.

Reentrant

In this mode, only one thread runs to serve all requests. If your WCF service makes an outbound call to some other WCF service, or makes a client call, it releases the thread lock. In other words, until the outbound call is completed, other WCF clients can not make calls.

Throttling behavior

WCF throttling helps you to put an upper limit on the number of concurrent calls, WCF instances, and concurrent sessions. WCF provides three ways by which you can define upper limits: MaxConcurrentCallsMaxConcurrentInstances, and MaxConcurrentSessions.
  • MaxConcurrentCalls: Limits the number of concurrent requests that can be processed by WCF service instances.
  • MaxConcurrentInstances: Limits the number of service instances that can be allocated at a given time. When it’s PerCall services, this value matches the number of concurrent calls. For PerSession services, this value equals the number of active session instances. This setting doesn’t matter for Single instancing mode, because only one instance is ever created.
  • MaxConcurrentSessions: Limits the number of active sessions allowed for the service.
All the above three settings can be defined in the servicebehaviors tag as shown in the below XML snippet:
<serviceBehaviors> 




<behavior name="serviceBehavior"> 




<serviceThrottling maxConcurrentCalls="16"

   maxConcurrentInstances="2147483647" maxConcurrentSessions="10" /> 




</behavior> 




</serviceBehaviors>

Default values for WCF throttling

Below is a simple table which shows the default settings for throttling for different WCF versions:
MaxConcurrentSessionsMaxConcurrentCalls MaxConcurrentInstances 
WCF 3.0 / 3.562610
WCF 4.016 * processorcount MaxConcurrentCallsMaxConcurrentCalls
+
MaxConcurrentSessions 100 * processorcount
100 * processorcount