Road Map for WCF
Short Description
Road Map for WCF...
Description
Table of Contents Introduction to WCF ............................................................................................................................................... 7 Advantage ....................................................................................................................................................... 7 Disadvantage .................................................................................................................................................. 8 Development Tools ................................................................................................................................................ 8 Microsoft Visual Studio 2008 ......................................................................................................................... 8 Difference between WCF and Web service .......................................................................................................... 10 WCF Fundamental................................................................................................................................................. 11 EndPoint ................................................................................................................................................................ 11 Address ......................................................................................................................................................... 11 Binding .......................................................................................................................................................... 11 Contract ........................................................................................................................................................ 12 Binding and Behavior ............................................................................................................................................ 13 Binding .......................................................................................................................................................... 13 Contracts and Service Host ................................................................................................................................... 15 Contracts ........................................................................................................................................................... 15 Service Contract ............................................................................................................................................ 15 Data Contract ................................................................................................................................................ 15 Message Contract ......................................................................................................................................... 15 Fault Contract ............................................................................................................................................... 15 Service Host .......................................................................................................................................................... 16 Message and Channel ........................................................................................................................................... 16 Message ........................................................................................................................................................ 16 WCF Runtime ................................................................................................................................................ 16 Channels:....................................................................................................................................................... 16 WCF Client and Metadata ..................................................................................................................................... 17 WCF Client ..................................................................................................................................................... 17 Metadata....................................................................................................................................................... 17 WCF Architecture .................................................................................................................................................. 18 Contracts ....................................................................................................................................................... 19 Service contracts ........................................................................................................................................... 19 Data contract ................................................................................................................................................ 19 Message Contract ......................................................................................................................................... 19 Policies and Binding ...................................................................................................................................... 19
Service Runtime ............................................................................................................................................ 19 Messaging ..................................................................................................................................................... 20 Activation and Hosting .................................................................................................................................. 20 WCF Hosting .......................................................................................................................................................... 20 IIS 5/6 Hosting ....................................................................................................................................................... 21 Self Hosting ........................................................................................................................................................... 27 Windows Activation Service ................................................................................................................................. 34 Enable WCF for non-http protocols .............................................................................................................. 34 Create WAS hosted service ........................................................................................................................... 34 Enable different binding to the hosted service ............................................................................................ 37 Windows Service Hosting ..................................................................................................................................... 39 Binding .................................................................................................................................................................. 46 Bindings and Channel Stacks ................................................................................................................................ 47 Types of Binding .................................................................................................................................................... 48 BasicHttpBinding ........................................................................................................................................... 48 WSHttpBinding.............................................................................................................................................. 48 WSDualHttpBinding ...................................................................................................................................... 48 WSFederationHttpBinding ............................................................................................................................ 48 NetTcpBinding ............................................................................................................................................... 48 NetNamedPipeBinding.................................................................................................................................. 49 NetMsmqBinding .......................................................................................................................................... 49 NetPeerTcpBinding ....................................................................................................................................... 49 Binding configuration............................................................................................................................................ 49 Administrative (Configuration file): .............................................................................................................. 49 Programming Model: .................................................................................................................................... 50 Metadata Exchange .............................................................................................................................................. 50 Exporting Service Metadata.......................................................................................................................... 51 Publishing Service Metadata ........................................................................................................................ 51 Retrieving Service Metadata......................................................................................................................... 51 HTTP_GET Enabled Metadata ............................................................................................................................... 51 Administrative (Configuration file): .............................................................................................................. 51 Progarmming Model: .................................................................................................................................... 52 Metadata Exchange Endpoint ............................................................................................................................... 52 Administrative (Configuration file): .............................................................................................................. 53 Programming Model: .................................................................................................................................... 53 Contracts ............................................................................................................................................................... 54
Service Contract .................................................................................................................................................... 54 Data Contract ........................................................................................................................................................ 56 Client side...................................................................................................................................................... 58 Message Contract ................................................................................................................................................. 58 Message ........................................................................................................................................................ 58 Message Pattern ........................................................................................................................................... 58 What is Message contract? ........................................................................................................................... 58 Defining Message Contract ........................................................................................................................... 59 Rules : ............................................................................................................................................................ 59 MessageHeaderArray Attribute ............................................................................................................................ 60 Message Contract Properties ............................................................................................................................... 61 ProtectionLevel ............................................................................................................................................. 61 Name and Namespace: ................................................................................................................................. 61 Order ............................................................................................................................................................. 62 Fault Contract ....................................................................................................................................................... 62 Instance Management .......................................................................................................................................... 66 Configuration: ............................................................................................................................................... 66 Per-Call Service ..................................................................................................................................................... 67 Per-Session Service ............................................................................................................................................... 69 Singleton Service ................................................................................................................................................... 71 Instance Deactivation ........................................................................................................................................... 73 ReleaseInstanceMode.None ......................................................................................................................... 73 ReleaseInstanceMode.BeforeCall ................................................................................................................. 74 ReleaseInstanceMode.AfterCall ................................................................................................................... 74 ReleaseInstanceMode.BeforeAndAfterCall .................................................................................................. 74 Explicit Deactivate ......................................................................................................................................... 75 Durable Service ..................................................................................................................................................... 75 Working: ........................................................................................................................................................ 75 Defining the Durable Service ........................................................................................................................ 75 How to Create Durable Service ............................................................................................................................. 76 Throttling .............................................................................................................................................................. 86 Administrative(configuration file)................................................................................................................. 86 Programming Model ..................................................................................................................................... 87 Operations ............................................................................................................................................................ 87 Request-Reply ....................................................................................................................................................... 88 One-Way ............................................................................................................................................................... 88
Definition : .................................................................................................................................................... 89 One-Way Operations and Sessionful Services .............................................................................................. 89 One-Way Operations and Exceptions ........................................................................................................... 90 Callback Service..................................................................................................................................................... 90 Defining and configuring a callback contract ............................................................................................... 91 Client Callback Setup..................................................................................................................................... 91 Service-Side Callback Invocation .................................................................................................................. 92 How to Create Callback Service in WCF ................................................................................................................ 92 Events .................................................................................................................................................................... 99 Definition ...................................................................................................................................................... 99 Transfer mode ..................................................................................................................................................... 105 Buffer transfer............................................................................................................................................. 106 Stream transfer ........................................................................................................................................... 106 StreamRequest............................................................................................................................................ 106 StreamRespone ........................................................................................................................................... 106 Configuration .............................................................................................................................................. 106 Differences between Buffered and Streamed Transfers ............................................................................ 107 Streaming ............................................................................................................................................................ 107 Supported Bindings ..................................................................................................................................... 107 Restrictions ................................................................................................................................................. 107 I/O Streams ................................................................................................................................................. 107 Streaming and Binding ................................................................................................................................ 108 Streaming and Transport ............................................................................................................................ 108 Transaction.......................................................................................................................................................... 109 Recovery Challenge ..................................................................................................................................... 109 Solution ....................................................................................................................................................... 109 Transaction Resources ................................................................................................................................ 110 Transaction Properties ................................................................................................................................ 110 Two-phase committed protocol ......................................................................................................................... 110 Transaction Propagation ..................................................................................................................................... 112 Transaction Protocols ......................................................................................................................................... 113 Transaction Mode ............................................................................................................................................... 114 How to Create WCF Transaction ......................................................................................................................... 115 What is WCF RIA service? ................................................................................................................................... 119 Domain Service ................................................................................................................................................... 120 Problem solved in RIA ......................................................................................................................................... 121
Querying/Updating data in RIA Service .............................................................................................................. 122 How to Create WCF RIA Service .......................................................................................................................... 123 Introduction to RESTful service........................................................................................................................... 130 How to create RESTful service ............................................................................................................................ 131 JSON using WCF service ...................................................................................................................................... 137 WCF Security ....................................................................................................................................................... 140 Types of Authentication ...................................................................................................................................... 140 Transfer Security Mode ...................................................................................................................................... 141 Transport Security Protection Level ................................................................................................................... 143 Message Security Level ....................................................................................................................................... 144 WCF Service Impersonation ................................................................................................................................ 144 WCF Windows Authentication ............................................................................................................................ 145 What's new in WCF 4.5 ....................................................................................................................................... 147 What's new in WCF 4.5 - Part 1 .......................................................................................................................... 149 WCF Configuration Validation .................................................................................................................... 149 Task-based Async Support .......................................................................................................................... 149 What's new in WCF 4.5 - Part 2 .......................................................................................................................... 151 Simplified Generated Configuration Files ................................................................................................... 151 Contract-First Development ....................................................................................................................... 152 What's new in WCF 4.5 - Part 3 .......................................................................................................................... 153 Default - ASP.NET Compatibility Mode ....................................................................................................... 153 Configuration tooltips ................................................................................................................................. 154 XmlDictionaryReaderQuotas ...................................................................................................................... 154 What's new in WCF 4.5 - Part 4 .......................................................................................................................... 154 Streaming Improvements ........................................................................................................................... 154 Generating a Single WSDL Document ......................................................................................................... 155 WebSocket Support .................................................................................................................................... 156 What's new in WCF 4.5 - Part 5 .......................................................................................................................... 156 Simple to expose HTTPS with IIS ................................................................................................................. 156 Configuring WCF Services in Code .............................................................................................................. 157 What's new in WCF 4.5 - Part 6 .......................................................................................................................... 158 Compress the Binary Encoder message ...................................................................................................... 158 ChannelFactory Caching.............................................................................................................................. 158 What's new in WCF 4.5 - Part 7 .......................................................................................................................... 159 Support for UDP Endpoint .......................................................................................................................... 159 Multiple Authentication Support ................................................................................................................ 159
What's new in WCF 4.5 - Part 8 .......................................................................................................................... 160 Internationalized Domain Names support ................................................................................................. 160
Introduction to WCF Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication. Below figures shows the different technology combined to form WCF.
Advantage 1. WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net. 2. WCF services provide better reliability and security in compared to ASMX web services. 3. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
4. WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.
Disadvantage Making right design for your requirement is little bit difficult. I will try to help you on solving these difficulties in the following article.
Development Tools WCF application can be developed by the Microsoft Visual Studio. Visual studio is available at different edition. You can use Visual Studio 2008 Expression edition for the development. http://www.microsoft.com/express/product/default.aspx Visual Studio 2008 SDK 1.1 http://www.microsoft.com/downloads/details.aspx?FamilyID=59ec6ec3-4273-48a3-ba25-dc925a45584d...
Microsoft Visual Studio 2008 Microsoft Visual studio 2008 provides new features for WCF compared to Visual Studio 2005. These are the new features added to VS 2008. 1. Multi-targeting You can create application in different framework like Framework 2.0, 3.0 and 3.5
2. Default template is available for WCF
3. WCF - Test Client tools for testing the WCF service. Microsoft provides inbuilt application to test the WCF application. This can be done by opening the Visual Studio command prompt and type the wcfClient Serviceurl shows below. This will help the developer to test the service before creating the client application.
4.
WCF services can be debugged now in Visual Studio 2008. Wcfsvchost.exe will do it for you because service will be self hosted when you start debugging.
Difference between WCF and Web service Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.
Features Hosting Programming Model Operation XML Encoding
Web Service It can be hosted in IIS
WCF It can be hosted in IIS, windows activation service, Selfhosting, Windows service
[WebService] attribute has to be added to the
[ServiceContraact] attribute has to be added to the
class
class
[WebMethod] attribute represents the method
[OperationContract] attribute represents the method
exposed to client
exposed to client
One-way, Request- Response are the different
One-Way, Request-Response, Duplex are different type
operations supported in web service
of operations supported in WCF
System.Xml.serialization name space is used for
System.Runtime.Serialization namespace is used for
serialization
serialization
XML 1.0, MTOM(Message Transmission
XML 1.0, MTOM, Binary, Custom
Optimization Mechanism), DIME, Custom Transports
Can be accessed through HTTP, TCP, Custom
Protocols
Security
Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom Security, Reliable messaging, Transactions
WCF Fundamental In this part of tutorial you are going to learn about some fundamental concepts in WCF. These concepts and terms will be used throughout this tutorial.
End Point Bindings and Behavior Contracts and Service host Message and Channel WCF client and Metadata
EndPoint WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world. All the WCF communications are take place through end point. End point consists of three components.
Address Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g http://localhost:8090/MyService/SimpleCalculator.svc
Binding Binding will 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
The following table gives some list of protocols supported by WCF binding.
Binding
Description
BasicHttpBinding
Basic Web service communication. No security by default
WSHttpBinding
Web services with WS-* support. Supports transactions
WSDualHttpBinding
Web services with duplex contract and transaction support
WSFederationHttpBinding Web services with federated security. Supports transactions MsmqIntegrationBinding Communication directly with MSMQ applications. Supports transactions NetMsmqBinding NetNamedPipeBinding NetPeerTcpBinding NetTcpBinding
Communication between WCF applications by using queuing. Supports transactions Communication between WCF applications on same computer. Supports duplex contracts and transactions Communication between computers across peer-to-peer services. Supports duplex contracts Communication between WCF applications across computers. Supports duplex contracts and transactions
Contract Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply. Below figure illustrate the functions of Endpoint
Example: Endpoints will be mentioned in the web.config file on the created service.
Binding and Behavior Binding Simple definition for Binding describes how the client will communicate with service. We can understand with an example. Consider a scenario say, I am creating a service that has to be used by two type of client. One of the client will access SOAP using http and other client will access Binary using TCP. How it can be done? With Web service it is very difficult to achieve, but in WCF its just we need to add extra endpoint in the configuration file.
See how simple it is in WCF. Microsoft is making everything simple.cording to its scope: common behaviors affect all endpoints globally, service behaviors affect only service-related aspects, endpoint behaviors affect only endpoint-related properties, and operation-level behaviors affect particular operations. Example: In the below configuration information, I have mentioned the Behavior at Service level. In the service behavior I have mention the servieMetadata node with attribute httGetEnabled='true'. This attribute will specifies the publication of the service metadata. Similarly we can add more behavior to the service.
Note: Application can be controlled either through coding, configuring or through combination of both. Specification mention in the configuration can also be overwritten in code.
Contracts and Service Host Contracts In WCF, all services are exposed as contracts. Contract is a platform-neutral and standard way of describing what the service does. Mainly there are four types of contracts available in WCF
Service Contract Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute. To know more on Service contract see Service contract tutorial.
Data Contract Data contract describes the custom data type which is exposed to the client. This defines the data types, that are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method. To know more on DataContract see DataContract tutorial.
Message Contract Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute. To know more on Message Contract see Message contract tutorial.
Fault Contract Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred. To know more on Fault Contract see Fault Contract tutorial.
Service Host Service Host object is in the process of hosting the WCF service and registering endpoints. It loads the service configuration endpoints, apply the settings and start the listeners to handle the incoming request. System.ServiceModel.ServiceHostnamespace hold this object. This object is created while self hosting the WCF service. In the below example you can find that WCF service is self hosted using console application. //Creating uri for the hosting the service Uri uri = new Uri("http://localhost/CategoryService"); //Creating the host object for MathService ServiceHost host = new ServiceHost(typeof(CategoryService), uri); //Adding endpoint to the Host object host.AddServiceEndpoint(typeof(ICategoryService),new WSHttpBinding(), uri); host.Open(); //Hosting the Service Console.WriteLine("Waiting for client invocations"); Console.ReadLine(); host.Close();
Message and Channel Message WCF Message is the unit of data exchange between client and service. It consists of several parts, including a body and headers.
WCF Runtime WCF runtime is the set of object responsible for sending and receiving message. For example formatting the message, applying security and transmitting and receiving message using various protocol.
Channels: Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as Transport Channels - Handles sending and receiving message from network. Protocols like HTTP, TCP name pipes and MSMQ. Protocol Channels - Implements SOAP based protocol by processing and possibly modifying message. e.g. WS-Security and WS-Reliability.
WCF Client and Metadata WCF Client WCF client is a client application creates to expose the service operations as method. Any application can host a WCF client, including an application that host a service. Therefore it is possible to create a service that includes WCF clients of other services. A client application is a managed application that uses a WCF client to communicate with another application. To create a client application for a WCF service requires the following steps:
1. Get the Proxy class and service end point information Using SvcUtil.exe we can create proxy class for the service and configuration information for endpoints. Example type the following sentence in the Visual studio command prompt, this will generate the class file and configuration file which contain information about the endpoints. svcutil /language:vb /out:ClientCode.vb /config:app.config http://localhost:8090/MyService/SimpleCalculator.svc?wsdl
2. Call operations. Add this class files in the client application. Then create the object for this class and invoke the service operation. Configuration information we got from the above step has to be added to the client application configuration file. When the client application calls the first operation, WCF automatically opens the underlying channel. This underlying channel is closed, when the object is recycled. //Creating the proxy on client side MyCalculatorServiceProxy.MyServiceProxy proxy = new MyCalculatorServiceProxy.MyServiceProxy(); Console.WriteLine("Counter: " + proxy.MyMethod());
3. Close the WCF client object. After using the object created in the above steps, we have to dispose the object. Channel will be closed with the service, when the object is cleared.
Metadata Characteristics of the service are described by the metadata. This metadata can be exposed to the client to understand the communication with service. Metadata can be set in the service by enabling the ServiceMetadata node inside the servcieBehaviour node of the service configuration file. This metadata can be viewed while creating WCF client application using SvcUtil.exe
WCF Architecture The following figure illustrates the major components of WCF.
Figure 1: WCF Architecture
Contracts Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.
Service contracts - Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.
Data contract - It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.
Message Contract - Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.
Policies and Binding - Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.
Service Runtime - It contains the behaviors that occur during runtime of service.
Throttling Behavior- Controls how many messages are processed. Error Behavior - Specifies what occurs, when internal error occurs on the service. Metadata Behavior - Tells how and whether metadata is available to outside world. Instance Behavior - Specifies how many instance of the service has to be created while running. Transaction Behavior - Enables the rollback of transacted operations if a failure occurs. Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.
Messaging - Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as
Transport Channels Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.
Protocol Channels Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WSReliability.
Activation and Hosting - Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism
IIS Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
Windows Activation Service (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
Self-Hosting WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.
Windows Service WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).
WCF Hosting In this part of the tutorial we are going to see the four different way of hosting the WCF service. WCF service cannot exist on its own; it has to be hosted in windows process called as host process. Single host process can host multiple servers and same service type can be hosted in multiple host process. As we discussed there are mainly four different way of hosting the WCF service.
1. IIS hosting
2. Self hosting 3. Windows Activation Service 4. Windows Service Multiple hosting and protocols supported by WCF.Microsoft has introduced the WCF concept in order to make distributed application development and deployment simple.
Hosting Environment
Supported protocol
Windows console and form application
HTTP,net.tcp,net.pipe,net.msmq
Windows service application (formerly known as NT services)
HTTP,net.tcp,net.pipe,net.msmq
Web server IIS6
http, wshttp
Web server IIS7 - Windows Process Activation Service (WAS)
HTTP,net.tcp,net.pipe,net.msmq
A summary of hosting options and supported features.
Feature
Self-Hosting
IIS Hosting
WAS Hosting
Executable Process/ App Domain
Yes
Yes
Yes
Configuration
App.config
Web.config
Web.config
Activation
Manual at startup
Message-based
Message-based
Idle-Time Management
No
Yes
Yes
Health Monitoring
No
Yes
Yes
Process Recycling
No
Yes
Yes
Management Tools
No
Yes
Yes
IIS 5/6 Hosting The main advantage of hosting service in IIS is that, it will automatically launch the host process when it gets the first client request. It uses the features of IIS such as process recycling, idle shutdown, process health monitoring and message based activation. The main disadvantage of using IIS is that, it will support only HTTP protocol. Let as do some hands on, to create service and host in IIS Step 1:Start the Visual Studio 2008 and click File->New->Web Site. Select the 'WCF Service' and Location as http. This will directly host the service in IIS and click OK.
Step 2: I have created sample HelloWorld service, which will accept name as input and return with 'Hello' and name. Interface and implementation of the Service is shown below. IMyService.cs [ServiceContract] public interface IMyService { [OperationContract] string HelloWorld(string name); } MyService.cs public class MyService : IMyService { #region IMyService Members public string HelloWorld(string name) { return "Hello " + name; } #endregion
} Step 3: Service file (.svc) contains name of the service and code behind file name. This file is used to know about the service. MyService.svc Step 4: Server side configurations are mentioned in the config file. Here I have mention only one end point which is configured to 'wsHttpBinding', we can also have multiple end point with differnet binding. Since we are going to hosted in IIS. We have to use only http binding. We will come to know more on endpoints and its configuration in later tutorial.Web.Config Note: You need to mention the service file name, along with the Address mention in the config file. IIS Screen shot
This screen will appear when we run the application.
Step 5: Now we successfully hosted the service in IIS. Next we have to consume this service in client application. Before creating the client application, we need to create the proxy for the service. This proxy is used by the client application, to interact with service. To create the proxy, run the Visual Studio 2008 command prompt. Using service utility we can create the proxy class and its configuration information.
svcutil
http://localhost/IISHostedService/MyService.svc
After executing this command we will find two file generated in the default location.
MyService.cs - Proxy class for the WCF service
output.config - Configuration information about the service.
Step 6: Now we will start creating the Console application using Visual Studio 2008(Client application).
Step 7: Add the reference 'System.ServiceModel'; this is the core dll for WCF.
Step 8: Create the object for the proxy class and call the HelloWorld method. static void Main(string[] args) { //Creating Proxy for the MyService MyServiceClient client = new MyServiceClient(); Console.WriteLine("Client calling the service..."); Console.WriteLine(client.HelloWorld("Ram")); Console.Read(); } Step 9: If we run the application we will find the output as shown below.
I hope you have enjoyed the Service hosted in IIS. Now let start the look on the self hosted service.
Self Hosting In web service, we can host the service only in IIS, but WCF provides the user to host the service in any application (e.g. console application, Windows form etc.). Very interestingly developer is responsible for providing and managing the life cycle of the host process. Service can also be in-pro i.e. client and service in the same process. Now let's us create the WCF service which is hosted in Console application. We will also look in to creating proxy using 'ClientBase' abstract class. Note: Host process must be running before the client calls the service, which typically means you have to prelaunch it. Step 1: First let's start create the Service contract and it implementation. Create a console application and name it as MyCalculatorService. This is simple service which return addition of two numbers.
Step 2: Add the System.ServiceModel reference to the project.
Step 3: Create an ISimpleCalculator interface, Add ServiceContract and OperationContract attribute to the class and function as shown below. You will know more information about these contracts in later session. These contracts will expose method to outside world for using this service. IMyCalculatorService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace MyCalculatorService { [ServiceContract()] public interface ISimpleCalculator { [OperationContract()] int Add(int num1, int num2); } } Step 4: MyCalculatorService is the implementation class for IMyCalculatorService interface as shown below. MyCalculatorService.cs using System;
using System.Collections.Generic; using System.Linq; using System.Text; namespace MyCalculatorService { class SimpleCalculator : ISimpleCalculator { public int Add(int num1, int num2) { return num1 + num2; } } } Step 5: Now we are ready with service. Let's go for implementing the hosting process. Create a new console application and name it as 'MyCalculatorServiceHost'
Step 6: ServiceHost is the core class use to host the WCF service. It will accept implemented contract class and base address as contractor parameter. You can register multiple base addresses separated by commas, but address should not use same transport schema. Uri httpUrl
= new Uri("http://localhost:8090/MyService/SimpleCalculator"); Uri tcpUrl = new Uri("net.tcp://localhost:8090/MyService/SimpleCalculator"); ServiceHost host = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl, tcpUrl); Multiple end points can be added to the Service using AddServiceEndpoint() method. Host.Open() will run the service, so that it can be used by any client. Step 7: Below code show the implementation of the host process.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.ServiceModel.Description; namespace MyCalculatorServiceHost { class Program { static void Main(string[] args) { //Create a URI to serve as the base address Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator"); //Create ServiceHost ServiceHost host = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl); //Add a service endpoint host.AddServiceEndpoint(typeof(MyCalculatorService.ISimpleCalculator) , 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 key to stop"); Console.ReadLine();
} } } Step 8: Service is hosted, now we need to implement the proxy class for the client. There are different ways of creating the proxy
Using SvcUtil.exe, we can create the proxy class and configuration file with end points. Adding Service reference to the client application. Implementing ClientBase class
Of these three methods, Implementing ClientBase is the best practice. If you are using rest two method, we need to create proxy class every time when we make changes in Service implementation. But this is not the case for ClientBase. It will create the proxy only at runtime and so it will take care of everything. MyCalculatorServiceProxy.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using MyCalculatorService; namespace MyCalculatorServiceProxy { public class MyCalculatorServiceProxy : //WCF create proxy for ISimpleCalculator using ClientBase ClientBase, ISimpleCalculator { public int Add(int num1, int num2) { //Call base to do funtion return base.Channel.Add(num1, num2); } } } Step 9: In the client side, we can create the instance for the proxy class and call the method as shown below. Add proxy assembly as reference to the project. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel;
namespace MyCalculatorServiceClient { class Program { static void Main(string[] args) { MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy ; proxy= new MyCalculatorServiceProxy.MyCalculatorServiceProxy(); Console.WriteLine("Client is running at " + DateTime.Now.ToString()); Console.WriteLine("Sum of two numbers... 5+5 ="+proxy.Add(5,5)); Console.ReadLine(); } } } Step 10 : End point (same as service) information should be added to the configuration file of the client application. Step 11: Before running the client application, you need to run the service. Output of the client application is shown below.
This self host shows advantage such as in-Pro hosting, programmatic access and it can be used when there need singleton service. I hope you have enjoyed the Self hosting session, now let go for hosting using Windows Activation service.
Windows Activation Service Windows Activation service is a system service available with Windows vista and windows server 2008. It is available with IIS 7.0 and it is more powerful compared to IIS 6.0 because it supports Http, TCP and named pipes were IIS 6.0 supports only Http. It can be installed and configured separately. Hosting WCF in Activation service takes many advantages such as process recycling, isolation, idle time management and common configuration system. WAS hosted service can be created using following steps
1. Enable WCF for non-http protocols 2. Create WAS hosted service 3. Enable different binding to the hosted service
Enable WCF for non-http protocols Before Start creating the service we need to configure the system to support WAS. Following are the step to configure WAS.
1. Click Start -> Control Panel -> programs and Features and click 'Turn Windows Components On or Off' in left pane. 2. Expand 'Microsoft .Net Framework 3.0' and enable "Windows Communication Foundation HTTP Activation" and "Windows Communication Foundation Non- HTTP Activation". 3. Next we need to add Binding to the Default Web site. As an example, we will bind the default web site to the TCP protocol. Go to the Start menu -> Programs ->Accessories. Right click on the "Command Prompt" item, and select "Run as administrator" from the context menu. 4. Execute the following command 5. C:\Windows\system32\inetsrv> appcmd.exe set site "Default Web Site" -+bindings.[protocol='net.tcp', bindingInformation='808:*'] That command adds the net.tcp site binding to the default web site by modifying the applicationHost.config file located in the "C:\Windows\system32\inetsrv\config" directory. Similarly we can add different protocols to the Default Web site.
Create WAS hosted service Step 1: Next we are going to create the service, Open the Visual Studio 2008 and click New->WebSite and select WCF Service from the template and Location as HTTP as shown below.
Step 2: Create the Contract by creating interface IMathService and add ServiceContract attribute to the interface and add OperationContract attribute to the method declaration. IMathService.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; [ServiceContract] public interface IMathService { [OperationContract] int Add(int num1, int num2); [OperationContract] int Subtract(int num1, int num2); }
Step 3: Implementation of the IMathService interface is shown below. MathService.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; public class MathService : IMathService { public int Add(int num1, int num2) { return num1 + num2; } public int Subtract(int num1, int num2) { return num1 - num2; } } Step 4: Service file is shown below. MathService.svc Step 5: In web.Config file, create end point with 'netTcpBinding' binding and service metadata will be published using Metadata Exchange point. So create the Metada Exchange end point with address as 'mex' and binding as 'mexTcpBinding'. Without publishing the service Metadata we cannot create the proxy using net.tcp address (e.g svcutil.exe net.tcp://localhost/WASHostedService/MathService.svc ) Web.Config
Enable different binding to the hosted service 1. Go to the Start menu -> Programs ->Accessories. Right click on the "Command Prompt" item, and select "Run as administrator" from the context menu. 2. Execute the following command C:\Windows\system32\inetsrv>appcmd set app "Default Web Site/WASHostedServcie" /enabledProtocols:http,net.tcp Output will be shown below.
Step 6: Now the service is ready to use. Next we can create the proxy class using service uttility and add the proxy class to the client application. Creat the proxy class using Visual Studio Command prompt and execute the command svcutil.exe net.tcp://localhost/WASHostedService/MathService.svc Proxy and configuration file are generated in the corresponding location.
Step 6: Create the client application as shown below and add the reference 'System.ServiceModel', this is the core dll for WCF.
Step 8: Add the proxy class and configuration file to the client application. Create the object for the MathServiceClient and call the method. Program.cs class Program { static void Main(string[] args) { MathServiceClient client = new MathServiceClient(); Console.WriteLine("Sum of two number 5,6"); Console.WriteLine(client.Add(5,6)); Console.ReadLine(); } } The output will be shown as below.
So this tutorial clearly explains about the hosting the WCF in Windows Activation Service. So next we can see how to host the service using Windows Service
Windows Service Hosting In this tutorial we are going to see the hosting WCF service in Windows service. We will use same set of code used for hosting the WCF service in Console application to this. This is same as hosting the service in IIS without message activated. There is some advantage of hosting service in Windows service.
The service will be hosted, when system starts Process life time of the service can be controlled by Service Control Manager for windows service All versions of Windows will support hosting WCF service.
Step 1: Now let start create the WCF service, Open the Visual Studio 2008 and click New->Project and select Class Library from the template.
Step 2: Add reference System.ServiceModel to the project. This is the core assembly used for creating the WCF service. Step 3: Next we can create the ISimpleCalulator interface as shown below. Add the Service and Operation Contract attribute as shown below. ISimpleCalculator.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace WindowsServiceHostedContract { [ServiceContract] public interface ISimpleCalculator { [OperationContract] int Add(int num1, int num2); [OperationContract] int Subtract(int num1, int num2);
[OperationContract] int Multiply(int num1,int num2); [OperationContract] double Divide(int num1, int num2); } } Step 4: Implement the ISimpleCalculator interface as shown below. SimpleCalulator.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WindowsServiceHostedService { class SimpleCalculator : ISimpleCalculator { public int Add(int num1, int num2) { return num1+num2; } public int Subtract(int num1, int num2) { return num1-num2; } public int Multiply(int num1, int num2) { return num1*num2; } public double Divide(int num1, int num2) { if (num2 != 0) return num1 / num2; else return 0; }
} } Step 5: Build the Project and get the dll. Now we are ready with WCF service, now we are going to see how to host the WCF Service in Windows service. Note: In this project, I have mention that we are creating both Contract and Service(implementation) are in same project. It is always good practice if you have both in different project. Step 6: Open Visual Studio 2008 and Click New->Project and select Windows Service.
Step 7: Add the 'WindowsServiceHostedService.dll' as reference to the project. This assembly will going to act as service.
Step 8: OnStart method of the service, we can write the hosting code for WCF. We have to make sure that we are using only one service host object. On stop method you need to close the Service Host. Following code show how to host WCF service in Windows service. WCFHostedWindowsService.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.ServiceModel; using System.ServiceModel.Description; namespace WCFHostedWindowsService { partial class WCFHostedWindowsService : ServiceBase { ServiceHost m_Host; public WCFHostedWindowsService() { InitializeComponent(); } protected override void OnStart(string[] args) {
if (m_Host != null) { m_Host.Close(); } //Create a URI to serve as the base address Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator"); //Create ServiceHost m_Host = new ServiceHost (typeof(WindowsServiceHostedService.SimpleCalculator), httpUrl); //Add a service endpoint m_Host.AddServiceEndpoint (typeof(WindowsServiceHostedService.ISimpleCalculator), new WSHttpBinding(), ""); //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; m_Host.Description.Behaviors.Add(smb); //Start the Service m_Host.Open();
} protected override void OnStop() { if (m_Host != null) { m_Host.Close(); m_Host = null; } } static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new WCFHostedWindowsService() }; ServiceBase.Run(ServicesToRun); } } }
Step 9: In order to install the service we need to have the Installer class for the Windows service. So add new Installer class to the project, which is inherited from the Installer class. Please find the below code for mentioning the Service name, StartUp type etc of the service. ServiceInstaller.cs using System; using System.Collections.Generic; using System.Text; using System.ServiceProcess; using System.Configuration.Install; using System.ComponentModel; using System.Configuration;
namespace WCFHostedWindowsService { [RunInstaller(true)] public class WinServiceInstaller : Installer { private ServiceProcessInstaller process; private ServiceInstaller service; public WinServiceInstaller() { process = new ServiceProcessInstaller(); process.Account = ServiceAccount.NetworkService; service = new ServiceInstaller(); service.ServiceName = "WCFHostedWindowsService"; service.DisplayName = "WCFHostedWindowsService"; service.Description = "WCF Service Hosted"; service.StartType = ServiceStartMode.Automatic; Installers.Add(process); Installers.Add(service); } } } Step 10: Build the project, we will get the WCFHostedWindowsService.exe. Next we need to install the service using Visual Studio Command Prompt. So open the command prompt by clicking Start->All Programs-> Microsoft Visual Studio 2008> Visual Studio Tools-> Visual Studio Command Prompt Using installutil utility application, you can install the service as shown below.
Step 11: Now service is Hosted sucessfully and we can create the proxy class for the service and start using in the client applcaiton.
Binding Binding will 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. 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
Bindings and Channel Stacks In WCF all the communication details are handled by channel, it is a stack of channel components that all messages pass through during runtime processing. The bottom-most component is the transport channel. This implements the given transport protocol and reads incoming messages off the wire. The transport channel uses a message encoder to read the incoming bytes into a logical Message object for further processing.
Figure 1: Bindings and Channel Stacks (draw new diagram) After that, the message bubbles up through the rest of the channel stack, giving each protocol channel an opportunity to do its processing, until it eventually reaches the top and WCF dispatches the final message to your service implementation. Messages undergo significant transformation along the way. It is very difficult for the developer to work directly with channel stack architecture. Because you have to be very careful while ordering the channel stack components, and whether or not they are compatible with one other. So WCF provides easy way of achieving this using end point. In end point we will specify address, binding and contract. To know more about end point. Windows Communication Foundation follows the instructions outlined by the binding
description to create each channel stack. The binding binds your service implementation to the wire through the channel stack in the middle.
Types of Binding Let us see more detailed on predefined binding
BasicHttpBinding
It is suitable for communicating with ASP.NET Web services (ASMX)-based services that comfort with WS-Basic Profile conformant Web services. This binding uses HTTP as the transport and text/XML as the default message encoding. Security is disabled by default This binding does not support WS-* functionalities like WS- Addressing, WS-Security, WSReliableMessaging It is fairly weak on interoperability.
WSHttpBinding
Defines a secure, reliable, interoperable binding suitable for non-duplex service contracts. It offers lot more functionality in the area of interoperability. It supports WS-* functionality and distributed transactions with reliable and secure sessions using SOAP security. It uses HTTP and HTTPS transport for communication. Reliable sessions are disabled by default.
WSDualHttpBinding This binding is same as that of WSHttpBinding, except it supports duplex service. Duplex service is a service which uses duplex message pattern, which allows service to communicate with client via callback. In WSDualHttpBinding reliable sessions are enabled by default. It also supports communication via SOAP intermediaries.
WSFederationHttpBinding This binding support federated security. It helps implementing federation which is the ability to flow and share identities across multiple enterprises or trust domains for authentication and authorization. It supports WS-Federation protocol.
NetTcpBinding This binding provides secure and reliable binding environment for .Net to .Net cross machine communication. By default it creates communication stack using WS-ReliableMessaging protocol for reliability, TCP for message delivery and windows security for message and authentication at run time. It uses TCP protocol and provides support for security, transaction and reliability.
NetNamedPipeBinding This binding provides secure and reliable binding environment for on-machine cross process communication. It uses NamedPipe protocol and provides full support for SOAP security, transaction and reliability. By default it creates communication stack with WS-ReliableMessaging for reliability, transport security for transfer security, named pipes for message delivery and binary encoding.
NetMsmqBinding
This binding provides secure and reliable queued communication for cross-machine environment. Queuing is provided by using MSMQ as transport. It enables for disconnected operations, failure isolation and load leveling
NetPeerTcpBinding
This binding provides secure binding for peer-to-peer environment and network applications. It uses TCP protocol for communication It provides full support for SOAP security, transaction and reliability.
Binding configuration Binding can be configured either through configuration file or Programming. Let us see the binding representation in each method.
Administrative (Configuration file): In the configuration file of the hosting application, you can add the element inside the element and add the properties to particular binding type. Properties corresponding to the particular binding type can be mentioned below. Name of the binding properties that you are going to use has to be mention in the end point.
Programming Model: In the following code, I have created the WSHttpBinding object and assign the properties which to be configured. This binding object is added to the Service endpoint for client communication. Similarly you can also create any type of binding and add to endpoint. //Create a URI to serve as the base address Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator"); //Create ServiceHost ServiceHost host = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl); //Create Binding to add to end point WSHttpBinding wshttpbind = new WSHttpBinding(); wshttpbind.AllowCookies = true; wshttpbind.CloseTimeout = new TimeSpan(0, 1, 0); wshttpbind.ReceiveTimeout
= new TimeSpan(0, 1, 0);
//Add a service endpoint host.AddServiceEndpoint (typeof(MyCalculatorService.ISimpleCalculator), wshttpbind, ""); //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
key to stop");
Console.ReadLine();
Note: It is always good if you configure the binding properties using configuration file, because while moving to the production you no need to change in the code and recompile it. It is always good practice to represent in the configuration file.
Metadata Exchange WCF provides rich infrastructure for Exporting, Publishing, retrieving and Importing the metadata. WCF uses the Metadata to describe how to interact with the service endpoint. Using the metadata, client will create the proxy class for the service usingSvcUtil.exe
Exporting Service Metadata It is the process of describing the service endpoint so that client can understand how to use the service.
Publishing Service Metadata It is the process publishing metadata. It involves converting CLR type and binding information into WSDL or some other low level representation.
Retrieving Service Metadata It is the process of retrieving the metadata. It uses WS-MetadataExcahge or HTTP protocol for retrieving the metadata. Importing Service Metadata - It is the process of generating the abstract representation of the service using metadata. Now we are going to focus mainly on publishing metadata. There are two way to publish metadata, either we can use HTTP-GET or through message exchange endpoint. By default service metadata is turn-off due to security reason. WCF metadata infrastructure resides in System.ServiceModel.Description namespace. Service metadata can be used for following purpose
Automatically generating the client for consuming service Implementing the service description Updating the binding for a client
Now let us understand the publishing the metadata using HTTP-GET method.
HTTP_GET Enabled Metadata We will use ServiceBehaviour to publish the metadata using HTTP-GET. This can be configures either administratively or Programmatically. Http and Https can expose by appending "?wsdl" to the end of the service address. For example service address is http://localhost:9090/MyCalulatorService , HTTP-Get metadata address is given byhttp://localhost:9090/MyCalulatorService?wsdl.
Administrative (Configuration file): In the below mention configuration information, you can find the behavior section in the ServiceBehavior. You can expose the metadata using ServiceMetadata node with httpGetEnable='True'.
Progarmming Model: Using ServiceMetadataBehavior you can enable the metadata exchange. In the following code, I have created the ServiceMetadataBehavior object and assigned HttpGetEnabled property to true. Then you have to add the behavior to host description as shown. This set of code will publish the metadata using HTTP-GET. //Create a URI to serve as the base address Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator"); //Create ServiceHost ServiceHost host = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl); //Add a service endpoint host.AddServiceEndpoint (typeof(MyCalculatorService.ISimpleCalculator), new WSHttpBinding(), ""); //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); //Enable metadata exchange using HTTP-GET 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
key to stop");
Console.ReadLine();
Metadata Exchange Endpoint Exposing the metadata using HTTP-GET has a disadvantage, such that there is no guarantee that other platforms you interact will support it. There is other way of exposing the using special endpoint is called as Metadata Exchange Endpoint. You can have as many metadata exchange endpoints as you want. Address It is basically Uri to identify the metadata. You can specify as address in the endpoint but append with "mex" keyword. For example "http://localhost:9090/MyCalulatorService/mex"
Binding There are four types of bindings supported for metadata exchange. They are mexHttpBinding, mexHttpsBinding, mexNamedPipesBinding, mexTcpBinding. Contract IMetadataExchange is the contract used for MEX endpoint. WCF service host automatically provides the implementation for this IMetadataExcahnge while hosting the service. You can create the Metadata Exchange Endpoint either Administrative (configuration file) or programmatically.
Administrative (Configuration file): In the configuration file of the hosting application, you can add metadata exchange endpoint as shown below.
Programming Model: In the following code I have mention about creating the Metadata Exchange Endpoint through coding. Steps to create the metadata endpoint are
Create the ServiceMetadataBehavior object and add to Service host description. ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(smb);
Create the metadata binding object using MetadataExchangeBinding Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding ();
3. Add the endpoint to the service host with address, binding and contract. host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex");
Complete code for hosting the service with metadata exchange endpoint is shown below. //Create a URI to serve as the base address Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator"); //Create ServiceHost ServiceHost host = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl); //Add a service endpoint host.AddServiceEndpoint (typeof(MyCalculatorService.ISimpleCalculator), new WSHttpBinding(), ""); //Enable metadata exchange ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); host.Description.Behaviors.Add(smb); Binding mexBinding = MetadataExchangeBindings.CreateMexHttpBinding (); //Adding metadata exchange endpoint host.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, "mex"); //Start the Service host.Open(); Console.WriteLine("Service is host at " + DateTime.Now.ToString()); Console.WriteLine("Host is running... Press
key to stop");
Console.ReadLine();
Contracts Windows Communication Foundation (WCF, formerly known as Indigo) is built upon the foundation of web services messaging and related standards, while at the same time makes it possible to serialize messages in a more compact binary format, or in a more proprietary way. Still, the core message can always be represented in XML, therefore be considered compatible with any platform that understands XML, and agrees on the contract that defines said messaging between systems. The contract is a platform-neutral and standard way of describing what the service does. WCF defines four types of contracts:
Service Contract Data Contract Message Contract Fault Contract
Service Contract Service contract describes the operation that service provide. A Service can have more than one service contract but it should have at least one Service contract.
Service Contract can be define using [ServiceContract] and [OperationContract] attribute. [ServiceContract] attribute is similar to the [WebServcie] attribute in the WebService and [OpeartionContract] is similar to the [WebMethod] in WebService.
It describes the client-callable operations (functions) exposed by the service It maps the interface and methods of your service to a platform-independent description It describes message exchange patterns that the service can have with another party. Some service operations might be one-way; others might require a request-reply pattern It is analogous to the element in WSDL
To create a service contract you define an interface with related methods representative of a collection of service operations, and then decorate the interface with the ServiceContract Attribute to indicate it is a service contract. Methods in the interface that should be included in the service contract are decorated with the OperationContract Attribute. [ServiceContract()] public interface ISimpleCalculator { [OperationContract()] int Add(int num1, int num2); } Once we define Service contract in the interface, we can create implement class for this interface. public
class SimpleCalculator : ISimpleCalculator
{ public int Add(int num1, int num2) { return num1 + num2; } } With out creating the interface, we can also directly created the service by placing Contract in the implemented class. But it is not good practice of creating the service [ServiceContract()] public class SimpleCalculator { [OperationContract()] public int Add(int num1, int num2) { return num1 + num2; } }
Now you have some fundamental idea on Service contract. Next we will look into Data Contract.
Data Contract 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 t 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
We need to include System.Runtime.Serialization reference to the project. This assembly holds the DataContract andDataMember attribute. Create user defined data type called Employee. This data type should be identified for serialization and deserialization by mentioning with [DataContract] and [DataMember] attribute. [ServiceContract] public interface IEmployeeService { [OperationContract] Employee GetEmployeeDetails(int EmpId); } [DataContract] public class Employee { private string m_Name; private int m_Age; private int m_Salary; private string m_Designation; private string m_Manager; [DataMember] public string Name { get { return m_Name; } set { m_Name = value; }
} [DataMember] public int Age { get { return m_Age; } set { m_Age = value; } } [DataMember] public int Salary { get { return m_Salary; } set { m_Salary = value; } } [DataMember] public string Designation { get { return m_Designation; } set { m_Designation = value; } } [DataMember] public string Manager { get { return m_Manager; } set { m_Manager = value; } } } Implementation of the service class is shown below. In GetEmployee method we have created the Employee instance and return to the client. Since we have created the data contract for the Employee class, client will aware of this instance whenever he creates proxy for the service. public class EmployeeService : IEmployeeService { public Employee GetEmployeeDetails(int empId) { Employee empDetail = new Employee(); //Do something to get employee details and assign to 'empDetail' properties return empDetail;
} }
Client side On client side we can create the proxy for the service and make use of it. The client side code is shown below. protected void btnGetDetails_Click(object sender, EventArgs e) { EmployeeServiceClient objEmployeeClient = new EmployeeServiceClient(); Employee empDetails; empDetails = objEmployeeClient.GetEmployeeDetails(empId); //Do something on employee details }
Message Contract Message Message is the packet of data which contains important information. WCF uses these messages to transfer information from Source to destination. WCF uses SOAP(Simple Object Access Protocol) Message format for communication. SOAP message contain Envelope, Header and Body.SOAP envelope contails name, namespace,header and body element. SOAP Hear contain important information which are not directly related to message. SOAP body contains information which is used by the target. Diagram Soap envelope
Message Pattern It describes how the programs will exchange message each other. There are three way of communication between source and destination
1. Simplex - It is one way communication. Source will send message to target, but target will not respond to the message. 2. Request/Replay - It is two way communications, when source send message to the target, it will resend response message to the source. But at a time only one can send a message 3. Duplex - It is two way communication, both source and target can send and receive message simultaniouly.
What is Message contract? As I said earlier, WCF uses SOAP message for communication. Most of the time developer will concentrate more on developing the DataContract, Serializing the data, etc. WCF will automatically take care of message. On Some critical issue, developer will also require control over the SOAP message format. In that case WCF provides Message Contract to customize the message as per requirement.
WCF supports either RPC(Remote Procedure Call) or Message style operation model. In the RPC model, you can develop operation with Ref and out parameter. WCF will automatically create the message for operation at run time. In Message style operation WCF allows to customize the message header and define the security for header and body of the message.
Defining Message Contract Message contract can be applied to type using MessageContract attribute. Custom Header and Body can be included to message using 'MessageHeader' and 'MessageBodyMember'atttribute. Let us see the sample message contract definition. [MessageContract] public class EmployeeDetails { [MessageHeader] public string EmpID; [MessageBodyMember] public string Name; [MessageBodyMember] public string Designation; [MessageBodyMember] public int Salary; [MessageBodyMember] public string Location; } When I use this EmployeeDeatils type in the service operation as parameter. WCF will add extra header call 'EmpID' to the SOAP envelope. It also add Name, Designation, Salary, Location as extra member to the SOAP Body.
Rules : You have to follow certain rules while working with Message contract
1. When using Message contract type as parameter, Only one parameter can be used in servicie Operation 2. [OperationContract] 3. void SaveEmployeeDetails(EmployeeDetails emp);
4. Service operation either should return Messagecontract type or it should not return any value 5. [OperationContract] 6. EmployeeDetails GetEmployeeDetails();
7. Service operation will accept and return only message contract type. Other data types are not allowed. 8. [OperationContract] 9. EmployeeDetails ModifyEmployeeDetails(EmployeeDetails emp);
Note: If a type has both Message and Data contract, service operation will accept only message contract.
MessageHeaderArray Attribute Consider the Message contract type definition as shown below.
[MessageContract] public class Department { [MessageHeader] public string DepartmentID; [MessageHeader] public string DepartmentName; [MessageHeader] public Employees Employee(); } In this we are having array of Employee type as message header. When this converted to SOAP Header it looks as shown below. PRO1243 Production Sam Ram Raja Suppose you want to show the all employee detail in same level. We can use MessageHeaderArray attribute which will serialize the array element independently. If you use the MessageHeaderArray attribute of Employees, SOAP message will look as shown below. PRO1243 Production Sam Ram Raja Note: MessageHeaderArray Attribute is applicable only for Array, not for collection.
Message Contract Properties ProtectionLevel You can mention the MessageHeader or MessageBodyMember to be signed or Encrypted using ProtectionLevel property. Example using System.Net.Security; [MessageContract] public class EmployeeDetails { [MessageHeader(ProtectionLevel=ProtectionLevel.None)] public string EmpID; [MessageBodyMember(ProtectionLevel = ProtectionLevel.Sign )] public string Name; [MessageBodyMember(ProtectionLevel = ProtectionLevel.Sign )] public string Designation; [MessageBodyMember(ProtectionLevel=ProtectionLevel.EncryptAndSign)] public int Salary; } In the above type definition, we have made the different protection level for body. But the protection level of the body is determind by the highest ProtectionLevel property. By default if you are not specifying the protection level it takes 'EncryptAndSign'. So it good if you specify minimum ProtectionLevel required.
Name and Namespace: SOAP representation of the message element can be change by mentioning Name and Namespace property of the Header and Body member. By default namespace is the same as the namespace of the service contract that the message is participating. In the below example, I have mention the Name property to the EmpID and Name.
[MessageContract] public class EmployeeDetails { [MessageHeader(Name="ID")] public string EmpID; [MessageBodyMember(Name="EmployeeName")] public string Name; [MessageBodyMember()] public string Designation; [MessageBodyMember()] public int Salary;
} When SOAP message representation, its name is changed to ID and EmployeeName.
45634 Sam Software Engineer 25000
Order The order of the body elements are alpehabetical by default. But you can control the order, usiing Order property in theMessageBody attribute.
[MessageContract] public class EmployeeDetails { [MessageHeader()] public string EmpID; [MessageBodyMember(Order=2)] public string Name; [MessageBodyMember(Order=3)] public string Designation; [MessageBodyMember(Order=1)] public int Salary; }
Fault Contract Service that we develop might get error in come case. This error should be reported to the client in proper manner. Basically when we develop managed application or service, we will handle the exception using try- catch block. But these exceptions handlings are technology specific. In order to support interoperability and client will also be interested only, what wents wrong? not on how and where cause the error. By default when we throw any exception from service, it will not reach the client side. WCF provides the option to handle and convey the error message to client from service using SOAP Fault contract. Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error
accorded in the service to client. This help as to easy identity the what error has accord. Let us try to understand the concept using sample example. Step 1: I have created simple calculator service with Add operation which will throw general exception as shown below //Service interface [ServiceContract()] public interface ISimpleCalculator { [OperationContract()] int Add(int num1, int num2); } //Service implementation public
class SimpleCalculator : ISimpleCalculator
{ public int Add(int num1, int num2) { //Do something throw new Exception("Error while adding number"); } }
Step 2: On client side code. Exceptions are handled using try-Catch block. Even though I have capture the exception when I run the application. I got the message that exceptions are not handled properly. try { MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy = new MyCalculatorServiceProxy.MyCalculatorServiceProxy(); Console.WriteLine("Client is running at " + DateTime.Now.ToString()); Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5)); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); }
Step 3: Now if you want to send exception information form service to client, you have to use FaultException as shown below. public int Add(int num1, int num2) { //Do something throw new FaultException("Error while adding number"); } Step 4: Output window on the client side is show below.
Step 5: You can also create your own Custom type and send the error information to the client using FaultContract. These are the steps to be followed to create the fault contract.
Define a type using the data contract and specify the fields you want to return. Decorate the service operation with the FaultContract attribute and specify the type name. Raise the exception from the service by creating an instance and assigning properties of the custom exception.
Step 6: Defining the type using Data Contract [DataContract()] public class CustomException { [DataMember()] public string Title; [DataMember()] public string ExceptionMessage;
[DataMember()] public string InnerException; [DataMember()] public string StackTrace; } Step 7: Decorate the service operation with the FaultContract [ServiceContract()] public interface ISimpleCalculator { [OperationContract()] [FaultContract(typeof(CustomException))] int Add(int num1, int num2); } Step 8: Raise the exception from the service public int Add(int num1, int num2) { //Do something CustomException ex = new CustomException(); ex.Title = "Error Funtion:Add()"; ex.ExceptionMessage = "Error occur while doing add function."; ex.InnerException = "Inner exception message from serice"; ex.StackTrace = "Stack Trace message from service."; throw new FaultException(ex,"Reason: Testing the Fault contract") ; } Step 9: On client side, you can capture the service exception and process the information, as shown below. try { MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy = new MyCalculatorServiceProxy.MyCalculatorServiceProxy(); Console.WriteLine("Client is running at " + DateTime.Now.ToString()); Console.WriteLine("Sum of two numbers... 5+5 =" + proxy.Add(5, 5)); Console.ReadLine(); } catch (FaultException ex) { //Process the Exception }
Instance Management Instance management refers to the way a service handles a request from a client. Instance management is set of techniques WCF uses to bind client request to service instance, governing which service instance handles which client request. It is necessary because application will differ in their need for scalability, performance, durability, transaction and queued calls. Basically there are three instance modes in WCF:
Per-Call instance mode Per-Session instance mode Singleton Instance Mode
Configuration: Instance mode can be configured using ServiceBehavior attribute. This can be specified at implementing the service contract as shown below. [ServiceContract()] public interface IMyService { [OperationContract] int MyMethod(); }
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class MyService:IMyService { public int MyMethod() { //Do something }
}
Per-Call Service When WCF service is configured for Per-Call instance mode, Service instance will be created for each client request. This Service instance will be disposed after response is sent back to client.
Following diagram represent the process of handling the request from client using Per-Call instance mode.
Let as understand the per-call instance mode using example.
Step 1: Create the service contract called IMyService and implement the interface. Add service behavior attribute to the service class and set the InstanceContextMode property to PerCall as show below. [ServiceContract()] public interface IMyService { [OperationContract] int MyMethod(); } Step 2: In this implementation of MyMethod operation, increment the static variable(m_Counter). Each time while making call to the service, m_Counter variable is incremented and return the value to the client. [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)] public class MyService:IMyService { static int m_Counter = 0; public int MyMethod() { m_Counter++; return m_Counter; } }
Step 3: Client side, create the proxy for the service and call "myMethod" operation multiple time. static void Main(string[] args) { Console.WriteLine("Service Instance mode: Per-Call"); Console.WriteLine("Client
making call to service...");
//Creating the proxy on client side MyCalculatorServiceProxy.MyServiceProxy proxy = new MyCalculatorServiceProxy.MyServiceProxy(); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.ReadLine(); } Surprisingly, all requests to service return '1', because we configured the Instance mode to Per-Call. Service instance will created for each request and value of static variable will be set to one. While return back, service instance will be disposed. Output is shown below.
Fig: PercallOutput.
Per-Session Service When WCF service is configured for Per-Session instance mode, logical session between client and service will be maintained. When the client creates new proxy to particular service instance, a dedicated service instance will be provided to the client. It is independent of all other instance. Following diagram represent the process of handling the request from client using Per-Session instance mode.
Let as understand the Per-Session instance mode using example. Step 1: Create the service contract called IMyService and implement the interface. Add service behavior attribute to the service class and set the InstanceContextMode property to PerSession as show below. [ServiceContract()] public interface IMyService { [OperationContract] int MyMethod();
} Step 2: In this implementation of MyMethod operation, increment the static variable (m_Counter). Each time while making call to the service, m_Counter variable will be incremented and return the value to the client. [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)] public class MyService:IMyService { static int m_Counter = 0; public int MyMethod() { m_Counter++; return m_Counter; } } Step 3: Client side, create the proxy for the service and call "myMethod" operation multiple time. static void Main(string[] args) { Console.WriteLine("Service Instance mode: Per-Session"); Console.WriteLine("Client
making call to service...");
//Creating the proxy on client side MyCalculatorServiceProxy.MyServiceProxy proxy = new MyCalculatorServiceProxy.MyServiceProxy(); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.ReadLine(); } All request to service return incremented value (1, 2, 3, 4), because we configured the instance mode to Per-Session. Service instance will be created once the proxy is created at client side. So each time request is made to the service, static variable is incremented. So each call to MyMethod return incremented value. Output is shown below.
Fig: PersessionOutput.
Singleton Service When WCF service is configured for Singleton instance mode, all clients are independently connected to the same single instance. This singleton instance will be created when service is hosted and, it is disposed when host shuts down. Following diagram represent the process of handling the request from client using Singleton instance mode.
Let as understand the Singleton Instance mode using example. Step 1: Create the service contract called IMyService and implement the interface. Add service behavior attribute to the service class and set the InstanceContextMode property to Single as show below. [ServiceContract()] public interface IMyService { [OperationContract] int MyMethod(); } Step 2: In this implementation of MyMethod operation, increment the static variable(m_Counter). Each time while making call to the service, m_Counter variable is incremented and return the value to the client [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class MyService:IMyService { static int m_Counter = 0; public int MyMethod() { m_Counter++; return m_Counter;
} } Step 3: Client side, create the two proxies for the service and made a multiple call to MyMethod. static void Main(string[] args) { Console.WriteLine("Service Instance mode: Singleton"); Console.WriteLine("Client 1 making call to service..."); //Creating the proxy on client side MyCalculatorServiceProxy.MyServiceProxy proxy = new MyCalculatorServiceProxy.MyServiceProxy(); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Counter: " + proxy.MyMethod()); Console.WriteLine("Client 2 making call to service..."); //Creating new proxy to act as new client MyCalculatorServiceProxy.MyServiceProxy proxy2 = new MyCalculatorServiceProxy.MyServiceProxy(); Console.WriteLine("Counter: " + proxy2.MyMethod()); Console.WriteLine("Counter: " + proxy2.MyMethod()); Console.ReadLine(); }
When two proxy class made a request to service, single instance at service will handle it and it return incremented value (1, 2, 3, 4), because instance mode is configured to 'Single'. Service instance is created when it is hosted. So this instance will remain till host is shutdown. Output is shown below.
Fig: SingletonOutput.
Instance Deactivation In Instance Management System tutorial, you learn how to create sessionful service instance. Basically service instance is hosted in a context. Session actually correlated the client message not to the instance, but to the context that host it. When session starts, context is created and when it closes, context is terminated. WCF provides the option of separating the two lifetimes and deactivating the instance separately from its context. ReleaseInstanceMode property of the OberationalBehavior attribute used to control the instance in relation to the method call. Followings are the list Release mode available in the ReleaseInstanceMode
1. 2. 3. 4.
RealeaseInstanceMode.None RealeaseInstanceMode.BeforeCall RealeaseInstanceMode.AfterCall RealeaseInstanceMode.BeforeAndAfterCall
Below code show, how to add the 'ReleaseInstanceMode' property to the operational behavior. [ServiceContract()] public interface ISimpleCalculator { [OperationContract()] int Add(int num1, int num2); } [OperationBehavior(ReleaseInstanceMode=ReleaseInstanceMode.BeforeCall] public int Add(int num1, int num2) { return num1 + num2; }
ReleaseInstanceMode.None This property means that it will not affect the instance lifetime. By default ReleaseInstanceMode property is set to 'None'.
ReleaseInstanceMode.BeforeCall This property means that it will create new instance before a call is made to the operation. If the instance is already exist,WCF deactivates the instance and calls Dispose() before the call is done. This is designed to optimize a method such as Create()
ReleaseInstanceMode.AfterCall This property means that it will deactivate the instance after call is made to the method. This is designed to optimize a method such a Cleanup()
ReleaseInstanceMode.BeforeAndAfterCall This is means that it will create new instance of object before a call and deactivates the instance after call. This has combined effect of using ReleaseInstanceMode.BeforeCall and ReleaseInstanceMode.AfterCall
Explicit Deactivate You can also explicitly deactivate instance using InstanceContext object as shown below. [ServiceContract()] public interface IMyService { [OperationContract] void MyMethod(); }
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class MyService:IMyService { public void MyMethod() { //Do something OperationContext.Current.InstanceContext.ReleaseServiceInstance(); } }
Durable Service Durable services are WCF services that persist service state information even after service host is restarted or Client. It means that durable services have the capability to restore their own state when they are recycled. It can use data store like SQL database for maintain instance state. It is new feature in .Net 3.5 You might think that we can also maintain session using WCF sessions, but content in the session environment is not persisted by default. If the service is shut down or client closes the proxy, data will be lost. But in case of Durable service it is still maintained.
Working: When Durable service is created with database as data store, it will maintain all its state information in the table. When a client make a request to the service, instance of the service is serialized, a new GUID is generated. This serialized instance xml and key will be saved in the database. We will call this GUID as instanceID. Service will send the instanceID to the client, so later it can use this id to get the instance state back. Even when client is shut down, instanceId will be saved at the client side. So when ever client opening the proxy, it can get back the previous state.
Defining the Durable Service Durable service can be implemented using [DurableService()] attribute. It takes 'CanCreateInstance' and 'CompletesInstance' property to mention on which operation instance state has to be saved and destroyed.
CanCreateInstance = true: Calling this operation results in creating the serialization and inserting it into the datastore. CompletesInstance = true: Calling this operation results in deleting the persisted instance from the datastore.
[Serializable] [DurableService()] public class MyService :IMyservice { [DurableOperation(CanCreateInstance = true)] public int StartPersistance() { //Do Something } [DurableOperation(CompletesInstance = true)] public void EndPersistence() { //Do Something } }
How to Create Durable Service Let us understand more about the durable service by creating Simple Calculator service which persist the instance state in SQL server database. Step 1: Start the Visual Studio 2008 and click File->New->Web Site. Select the 'WCF Service' as shown below.
Step 2: Create interface and decorate with Service and Operation contract. [ServiceContract()] public interface ISimpleCalculator { [OperationContract] int Add(int num); [OperationContract] int Subtract(int num); [OperationContract] int Multiply(int num); [OperationContract] void EndPersistence(); }
Step 3: You need to add [Serializable] And [DurableService()] attribute to the service implementation. Set CanCreateInstance = true property to the operation in which instance state has to be persisted and set CompletesInstance = true when state has to be destroyed. In this implementation, we are going to persist the 'currentValue' variable value to the database.
using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.ServiceModel.Description; [Serializable] [DurableService()] public class SimpleCalculator :ISimpleCalculator { int currentValue = default(int); [DurableOperation(CanCreateInstance = true)] public int Add(int num) { return (currentValue += num); } [DurableOperation()] public int Subtract(int num) { return (currentValue -= num); } [DurableOperation()] public int Multiply(int num) { return (currentValue *= num); } [DurableOperation(CompletesInstance = true)] public void EndPersistence() { } Step 4: Before configuring the database information in the durable service, you need to set up DataStore environment. Microsoft provides inbuilt sqlPersistance provider. To set up the database environment, run the these sql query located at following location 'C:\Windows\Microsoft.NET\Framework\v3.5\SQL\EN'
SqlPersistenceProviderSchema.sql SqlPersistenceProviderLogic.sql
Step 5: In order to support durable service, you need to use Context binding type. tag is used to configure the persistence provider.
Step 6: Create the console client application and name it as DurableServiceClient
Step 7: Add following reference to client application
System.ServiceModel System.WorkflowService
Step 8: Add WCF service as Service Reference to the project and name it as SimpleCalculatorService
Step 9: Create the Helper class called it as Helper.cs. This helper class is used to Store, Retrieve and set the context at the client side. Context information will be saved in 'token_context.bin' file. Copy and paste the below code to your helper file. Helper.cs using System.ServiceModel.Channels; using System.ServiceModel; using System.Net; using System.IO; using System.Runtime.Serialization.Formatters.Binary; public class Helper { static readonly String TokenContextFileName = "token_context.bin"; public static IDictionary LoadContext() { IDictionary ctx = null; try { using (FileStream fs = new
FileStream(TokenContextFileName, FileMode.Open, FileAccess.Read)) { BinaryFormatter bf = new BinaryFormatter(); ctx = bf.Deserialize(fs) as IDictionary; fs.Close(); } } catch (Exception ex) { } return ctx; } public static void SaveContext(IClientChannel channel) { IDictionary ctx = null; IContextManager cm = channel.GetProperty(); if (cm != null) { ctx = cm.GetContext() as IDictionary; try { using (FileStream fs = new FileStream(TokenContextFileName, FileMode.CreateNew)) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, ctx); fs.Close(); } } catch (Exception ex) { } } } public static void DeleteContext() { try {
File.Delete(TokenContextFileName); } catch (Exception ex) { } } public static void SetContext(IClientChannel channel, IDictionary ctx) { IContextManager cm = channel.GetProperty(); if (cm != null) { cm.SetContext(ctx); } } } Step 10: In the main method, I was creating the proxy for the service and calling the Add operation. Call to this method will add instance state to the database. Now I have closed the proxy and creating new proxy instance. When I call the Subtract and Multiply operation, it will operate on the previously saved value (instance state). static void Main(string[] args) { //Create the proxy for the service SimpleCalculatorService.SimpleCalculatorClient client = new SimpleCalculatorService.SimpleCalculatorClient "WSHttpContextBinding_ISimpleCalculator"); int currentValue = 0; //Call the Add method from the service currentValue = client.Add(10000); Console.WriteLine("The current value is {0}", currentValue); //Save the Context from the service to the client Helper.SaveContext(client.InnerChannel); //Close the proxy client.Close(); //Create new Instance of the proxy for the service client = new SimpleCalculatorService.SimpleCalculatorClient ("WSHttpContextBinding_ISimpleCalculator"); //Load the context from the client to start from saved state IDictionary cntx=Helper.LoadContext(); //Set Context to context manager Helper.SetContext(client.InnerChannel, cntx); //Call the Subtract and Multiply method from service
currentValue = client.Subtract(2); Console.WriteLine("The current value is {0}", currentValue); currentValue = client.Multiply(5); Console.WriteLine("The current value is {0}", currentValue); //Delete the context from the client Helper.DeleteContext(); //Remove persistance state from the server client.EndPersistence(); Console.WriteLine("Press to shut down the client."); Console.ReadLine(); client.Close(); } End of the proxy 1, service instance saved in the database as shown below.
Serialized XML instance state save in the database is shown below.
Output of the client application.
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.
Attribute maxConcurrentCalls maxConcurrentInstances maxConcurrentSessions
Description Limits the total number of calls that can currently be in progress across all service instances. The default is 16. The number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue. A positive integer that limits the number of sessions a ServiceHost object can accept. The default is 10.
Service Throttling can be configured either Adminstractive or Programatically
Administrative(configuration file) Using tag of the Service Behavior, you can configure the maxConcurrentCalls, maxConcurrentInstances ,maxConcurrentSessions property as shown below.
Programming Model Use ServiceThrottlingBehavior object to set concurrent calls, session and instance property. ServiceHost host = new ServiceHost(typeof(MyService)); ServiceThrottlingBehavior throttle = host.Description.Behaviors.Find(); if (throttle == null) { throttle = new ServiceThrottlingBehavior(); throttle.MaxConcurrentCalls = 500; throttle.MaxConcurrentSessions = 200; throttle.MaxConcurrentInstances = 100; host.Description.Behaviors.Add(throttle); } host.Open();
Operations In classic object or component- oriented programming model offered only single way for client to call a method. Client will issue a call, block while the call was in progress, and continue executing once the method returned. WCF will support classical Request-Replay model, along with that it also supports One-Way call(call and forget operation) and callback(service to call back the client) Three modes of communication between client and service are
1. Request- Replay 2. One-Way 3. Callback
Request-Reply By default all WCF will operated in the Request-Replay mode. It means that, when client make a request to the WCF service and client will wait to get response from service (till receiveTimeout). After getting the response it will start executing the rest of the statement. If service doesn't respond to the service within receiveTimeout, client will receive TimeOutException. Apart from NetPeerTcpBinding and the NetMsmqBinding all other bindings will support request-reply operations.
One-Way In One-Way operation mode, client will send a request to the server and does not care whether it is success or failure of service execution. There is no return from the server side, it is one-way communication. Client will be blocked only for a moment till it dispatches its call to service. If any exception thrown by service will not reach the server. Client can continue to execute its statement, after making one-way call to server. There is no need to wait, till server execute. Sometime when one-way calls reach the service, they may not be dispatched all at once but may instead be queued up on the service side to be dispatched one at a time, according to the service's configured concurrency mode
behavior. If the number of queued messages has exceeded the queue's capacity, the client will be blocked even if it's issued a one-way call. However, once the call is queued, the client will be unblocked and can continue executing, while the service processes the operation in the background.
Definition : One-way operation can be enabled by setting IsOneWay property to true in Operation contract attribute. [ServiceContract] public interface IMyService { [OperationContract(IsOneWay=true)] void MyMethod(EmployeeDetails emp); }
One-Way Operations and Sessionful Services Let us see the example, what will happen when you use the one-way communication with Sessionful service. [ServiceContract(SessionMode = SessionMode.Required)] interface IMyContract { [OperationContract(IsOneWay = true)] void MyMethod(); } As per above configuration, when client makes one-way call using MyMethod() operation and if it close the proxy. Client will be blocked until operation completes. It will be good practice, that one-way operation should be applied on per-call and singleton service. Suppose If you want to make use of One-way operation in Sessionful service, use in the last operation of the service which will terminate the session. This operation should not return any value. [ServiceContract(SessionMode = SessionMode.Required)] interface IMyContract { [OperationContract] void MyMethod1();
[OperationContract] string MyMethod2(); [OperationContract(IsOneWay = true, IsInitiating = false, IsTerminating = true)] string CloseSessionService(int id); }
One-Way Operations and Exceptions Suppose when we are using BasicHttpBinding or WSHttpBinding, i.e. no transport session is used, if any exception throw by service will not affect the client. Client can make a call to the service using same proxy [ServiceContract] interface IMyContract { [OperationContract(IsOneWay = true)] void MethodWithError( ); [OperationContract] void MethodWithoutError( ); } //Client side without transport session MyContractClient proxy = new MyContractClient( ); proxy.MethodWithError( ); //No exception is thrown from serivce proxy.MethodWithoutError( ); //Operation will execute properly proxy.Close( ); In the presence of transport session, any exception thrown by service will fault the client channel. Client will not be able to make new call using same proxy instance. //Client side transport session MyContractClient proxy = new MyContractClient( ); proxy.MethodWithError( ); proxy.MethodWithoutError( ); //Can not executre because channel is faulted proxy.Close( );
Callback Service Till now we have seen that the all clients will call the service to get the things done. But WCF also provides the service to call the client. In which, service will act as client and client will act as service.
HTTP protocols are connectionless nature, so it is not supported for callback operation. So BasicHttpBinding and WSHttpBinding cannot be used for this operation. WCF support WSDualHttpBinding for call back operation.
All TCP and IPC protocols support Duplex communication. So all these binding will be used for callback operation.
Defining and configuring a callback contract Callback service can be enabled by using CallbackContract property in the ServiceContract attribute. In the below example you can find the decalration of the callback contract and it is configured in the ServiceContract attribute. public interface IMyContractCallback { [OperationContract] void OnCallback(); } [ServiceContract(CallbackContract = typeof(IMyContractCallback))] public interface IMyContract { [OperationContract()] void MyMethod(); }
Client Callback Setup As I said earlier, in callback operation client will act as service and service will act as client. So client has to expose a callback endpoint to the service to call. In the earlier part of the tutorial I have mention that InstanceContext is the execution scope of inner most service instance. It provides a constructor that takes the service instance to the host. IMyContractCallback callback=new MyCallback(); InstanceContext cntx=new InstanceContext(callback); MyServiceClient proxy = new MyServiceClient(cntx);
proxy.MyMethod(); The client must use a proxy that will set up the bidirectional communication and pass the callback endpoint reference to the service. This can be achieved by creating the proxy using DuplexClientBase class MyServiceClient:DuplexClientBase,IMyContract { public MyServiceClient(InstanceContext callbackCntx) : base(callbackCntx) { } public void MyMethod() { base.Channel.MyMethod(); } }
Service-Side Callback Invocation The client-side callback endpoint reference is passed along with every call the client makes to the service, and it is part of the incoming message. The OperationContext class provides the service with easy access to the callback reference via the generic method GetCallbackChannel( ). Service can call the client side callback method using reference e to the client side callback instance. The following code shows the callback method invocation. IMyContractCallback callbackInstance=OperationContext.Current.GetCallbackChannel(); callbackInstance.OnCallback();
How to Create Callback Service in WCF This tutorial gives hands-on to create a sample Callback service. Step 1: Create the sample Classlibrary project using Visual Studio 2008 and name it as CallbackService
Step 2 : Add System.ServiceModel reference to the project Step 3: Create the Callback and Service contract as shown below. You need to mention CallbackContract property in theServiceContract attribute. Implementation of the Callback contract will be done on the client side. IMyContract.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace CallbackService { public interface IMyContractCallback { [OperationContract] void OnCallback(); } [ServiceContract(CallbackContract = typeof(IMyContractCallback))]
public interface IMyContract { [OperationContract()] void MyMethod(); } } Step 4: Implement the Service contract as shown below. In the below code you will find using OperationContext is used to receive the reference to Callback instance. Using that instance we are calling the OnCallback() method from client side. MyService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace CallbackService { [ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Multiple )] public class MyService:IMyContract { public void MyMethod() { //Do something IMyContractCallback callbackInstance =OperationContext.Current.GetCallbackChannel(); callbackInstance.OnCallback(); } } } You can also note that We have set the ConcurrencyMode to Multile. If you are not using ConcurrencyMode to Multiple or Reentent, you will be end up with deadlock exception as shown below. This is because when a client made a call to the service, channel is created and lock by WCF service. If you are calling the Callback method inside the service method. Service will try to access the lock channel, this may leads to deadlock. So you can set ConcurrencyMode to Multiple or Reentent so it will release the lock silently.
Step 5: Create a Console application using Visual Studio 2008 and name it a CallbackServiceHost. This application is used to self-host the WCF service
Step 6: Main method static void Main(string[] args) {
Uri httpUrl = new Uri("http://localhost:8090/MyService/"); ServiceHost host = new ServiceHost(typeof(CallbackService.MyService), httpUrl); host.Open(); Console.WriteLine("Service is Hosted at {0}", DateTime.Now.ToString()); Console.WriteLine("Host is running...Press
key to stop the service.");
Console.ReadLine(); host.Close(); }
Step 7: Use Duplex binding to support Callback operation. Web.Config Step 8: Run the host application
Step 9: Create Console Application using Visual Studio 2008 and name it as CallbackClient. This is the client application which contain Callback implementation.
Step10: Add System.ServiceModel and CallbackService as reference to the project Step 11: Create the proxy class as shown below. Use DuplexClientBase to create the proxy, because it will support bidirectional communication. Create the contractor which will accept InstanceContext as parameter. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using CallbackService; namespace CallbackClient { class MyServiceClient:DuplexClientBase,IMyContract { public MyServiceClient(InstanceContext callbackCntx) : base(callbackCntx)
{ } public void MyMethod() { base.Channel.MyMethod(); } } } Step12: Create the implementation for Callback Contract class MyCallback : IMyContractCallback { public void OnCallback() { Console.WriteLine("Callback method is called from client side."); } } Step 13: Implementation of main method static void Main(string[] args) { IMyContractCallback callback=new MyCallback(); InstanceContext cntx=new InstanceContext(callback); MyServiceClient proxy = new MyServiceClient(cntx); Console.WriteLine("Client call the MyMethod Operation from Service."); proxy.MyMethod(); Console.ReadLine(); } Step14: Run the client application. In the output, you can see the OnCallback method called by the service
Events Events allow the client or clients to be notified about something that has occurred on the service side. An event may result from a direct client call, or it may be the result of something the service monitors. The service firing the event is called the publisher, and the client receiving the event is called the subscriber.
Publisher will not care about order of invocation of subscriber. Subscriber can be executed in any manner. Implementation of subscriber side should be short duration. Let us consider the scenario in which you what to publish large volume of event. Publisher will be blocked, when subscriber is queued on previous subscription of the event. These make publishers to put in wait state. It may lead Publisher event not to reach other subscriber. Large number of subscribers to the event makes the accumulated processing time of each subscriber could exceed the publisher's timeout Managing the list of subscribers and their preferences is a completely service-side implementation. It will not affect the client; publisher can even use .Net delegates to manage the list of subscribers. Event should always one-Way operation and it should not return any value
Definition public interface IMyEvents { [OperationContract(IsOneWay = true)] void Event1(); } Let us understand more on Event operation by creating sample service Step 1 : Create ClassLibrary project in the Visual Studio 2008 and name it as WCFEventService as shown below.
Step 2: Add reference System.ServiceModel to the project Create the Event operation at the service and set IsOnwWay property to true. This operation should not return any value. Since service has to communicate to the client, we need to use CallbackContract for duplex communication. Here we are using one operation to subscribe the event and another for firing the event. public interface IMyEvents { [OperationContract(IsOneWay = true)] void Event1(); } [ServiceContract(CallbackContract = typeof(IMyEvents))] public interface IMyContract { [OperationContract] void DoSomethingAndFireEvent(); [OperationContract] void SubscribeEvent(); }
Step 3: Implementation of the Service Contract is shown below. In the Subscription operation, I am using Operationcontext to get the reference to the client instance and Subscription method is added as event handler to the service event. DoSomethingAndFireEvent operation will fire the event as shown. MyPublisher.cs [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public
class MyPublisher : IMyContract
{ static Action m_Event1 = delegate { }; public void SubscribeEvent() { IMyEvents subscriber = OperationContext.Current.GetCallbackChannel(); m_Event1 += subscriber.Event1; } public static void FireEvent() { m_Event1(); } public void DoSomethingAndFireEvent() { MyPublisher.FireEvent(); } } Step 4: Create the Console application using Visual Studio 2008 and name it as WcfEventServiceHost. This application will be used to self-host the service.
Step 5: Add System.ServiceModel and WcfEventService as reference to the project. static void Main(string[] args) { Uri httpUrl = new Uri("http://localhost:8090/MyPublisher/"); ServiceHost host = new ServiceHost(typeof(WcfEventService.MyPublisher), httpUrl); host.Open(); Console.WriteLine("Service is Hosted at {0}", DateTime.Now.ToString()); Console.WriteLine("Host is running...Press
key to stop the service.");
Console.ReadLine(); host.Close(); }
Step 6: Use Duplex binding to support Callback operation. Web.Config
Step7: Run the host application as shown below.
Step 8: Create the console application using visual studio and name it as WcfEventServiceClient as shown below. This application will act a client which is used to subscribe the event from service.
Step 9: Create the proxy class as shown below. Use DuplexClientBase to create the proxy, because it will support bidirectional communication. Create the contractor which will accept InstanceContext as parameter. EventServiceClient.cs class EventServiceClient:DuplexClientBase,IMyContract { public EventServiceClient(InstanceContext eventCntx) : base(eventCntx) { } public void
DoSomethingAndFireEvent()
{ base.Channel.DoSomethingAndFireEvent(); } public void SubscribeEvent() { base.Channel.SubscribeEvent(); } }
Step 10: Implementation of IMyEvents at client side is shown below. This method will be called when service publish the event. class MySubscriber : IMyEvents { public void Event1() { Console.WriteLine("Event is subscribed from the service at {0}",DateTime.Now.ToString() ); } } Step 11: Main method of the client side you can find the creating Subscription instance and it passed to service usingInstanceContext static void Main(string[] args) { IMyEvents evnt = new MySubscriber(); InstanceContext evntCntx = new InstanceContext(evnt); EventServiceClient proxy = new EventServiceClient(evntCntx); Console.WriteLine("Client subscribe the event from the service at {0}",DateTime.Now.ToString()); proxy.SubscribeEvent(); Console.WriteLine("Client call operation which will fire the event"); proxy.DoSomethingAndFireEvent(); Console.ReadLine(); } Step 12: Run the client application and you see the when event is fired from the service. Subscriber got notification.
Transfer mode In our normal day today life, we need to transfer data from one location to other location. If data transfer is taking place through WCF service, message size will play major role in performance of the data transfer. Based on the size and other condition of the data transfer, WCF supports two modes for transferring messages
Buffer transfer When the client and the service exchange messages, these messages are buffered on the receiving end and delivered only once the entire message has been received. This is true whether it is the client sending a message to the service or the service returning a message to the client. As a result, when the client calls the service, the service is invoked only after the client's message has been received in its entirety; likewise, the client is unblocked only once the returned message with the results of the invocation has been received in its entirety.
Stream transfer When client and Service exchange message using Streaming transfer mode, receiver can start processing the message before it is completely delivered. Streamed transfers can improve the scalability of a service by eliminating the requirement for large memory buffers. If you want to transfer large message, streaming is the best method.
StreamRequest In this mode of configuration, message send from client to service will be streamed
StreamRespone In this mode of configuration, message send from service to client will be streamed.
Configuration
Differences between Buffered and Streamed Transfers Buffered Target can process the message once it is completely received. Performance will be good when message size is small Native channel shape is IDuplexSessionChannel
Streamed Target can start processing the data when it is partially received Performance will be good when message size is larger(more than 64K) Native channels are IRequestChannel and IReplyChannel
Streaming Client and Service exchange message using Streaming transfer mode, receiver can start processing the message before it is completely delivered. Streamed transfers can improve the scalability of a service by eliminating the requirement for large memory buffers. If you want to transfer large message, streaming is the best method.
Supported Bindings
BasicHttpBinding NetTcpBinding NetNamedPipeBinding
Restrictions There are some restriction, when streaming is enabled in WCF
Digital signatures for the message body cannot be performed Encryption depends on digital signatures to verify that the data has been reconstructed correctly. Reliable sessions must buffer sent messages on the client for redelivery if a message gets lost in transfer and must hold messages on the service before handing them to the service implementation to preserve message order in case messages are received out-of-sequence. Streaming is not available with the Message Queuing (MSMQ) transport Streaming is also not available when using the Peer Channel transport
I/O Streams WCF uses .Net stream class for Streaming the message. Stream in base class for streaming, all subclasses like FileStream,MemoryStream, NetworkStream are derived from it. Stream the data, you need to do is, to return or receive a Stream as an operation parameter. [ServiceContract] public interface IMyService
{ [OperationContract] void SaveStreamData(Stream emp); [OperationContract] Stream GetStreamData(); } Note:
1. Stream and it's subclass can be used for streaming, but it should be serializable 2. Stream and MemoryStream are serializable and it will support streaming 3. FileStream is non serializable, and it will not support streaming
Streaming and Binding Only the TCP, IPC, and basic HTTP bindings support streaming. With all of these bindings streaming is disabled by default.TransferMode property should be set according to the desired streaming mode in the bindings. public enum TransferMode { Buffered, //Default Streamed, StreamedRequest, StreamedResponse } public class BasicHttpBinding : Binding,... { public TransferMode TransferMode {get;set;} //More members }
StreamedRequest - Send and accept requests in streaming mode, and accept and return responses in buffered mode StreamResponse - Send and accept requests in buffered mode, and accept and return responses in streamed mode Streamed - Send and receive requests and responses in streamed mode in both directions Buffered -Send and receive requests and responses in Buffered mode in both directions
Streaming and Transport The main aim of the Streaming transfer mode is to transfer large size data, but default message size is 64K. So you can increase the message size using maxReceivedMessageSize attribute in the binding element as shown below.
Transaction A transaction is a collection or group of one or more units of operation executed as a whole. It provides way to logically group single piece of work and execute them as a single unit. In addition, WCF allows client applications to create transactions and to propagate transactions across service boundaries.
Recovery Challenge Let us discuss more on challenge we will phased and how to recover from it.
1. Consider a system maintained in consistent state, when application fail to perform particular operation, you should recover from it and place the system in the consistent state. 2. While doing singe operation, there will be multiple atomic sub operation will happen. These operations might success or fail. We are not considering about sub operation which are failed. We mainly consider about the success operation. Because we have to recover all these state to its previous consistence state. 3. Productivity penalty has to be payee for all effort required for handcrafting the recovery logic 4. Performance will be decreased because you need to execute huge amount of code.
Solution Best way to maintain system consistence and handling error-recovery challenge is to use transactions. Below figure gives idea about transaction.
Committed transaction: Transaction that execute successfully and transfer the system from consistence state A to B. Aborted transaction: Transaction encounters an error and rollback to Consistence State A from intermediate state. In-doubt transaction: Transactions fail to either in commit or abort.
Transaction Resources Transactional programming requires working with a resource that is capable of participating in a transaction, and being able to commit or roll back the changes made during the transaction. Such resources have been around in one form or another for decades. Traditionally, you had to inform a resource that you would like to perform transactional work against it. This act is called enlisting. Some resources support auto-enlisting.
Transaction Properties Transaction can be said as pure and successful only if meets four characteristics.
Atomic - When transaction completes, all the individual changes made to the resource while process must be made as to they were all one atomic, indivisible operation. Consistent - transaction must leave the system in consistent state. Isolated - Resources participating in the transaction should be locked and it should not be access by other third party. Durable - Durable transactions must survive failures.
Two-phase committed protocol Consider the scenario where I am having single client which use single service for communication and interacting with single database. In which service starts and manage the transaction, now it will be easy for the service to manage the transaction. Consider for example client calling multiple service or service itself calling another service, this type of system are called as Distributed Service-oriented application. Now the questions arise that which service will begin the transaction? Which service will take responsibility of committing the transaction? How would one service know what the rest of the service feels about the transaction? Service could also be deployed in different machine and site. Any network failure or machine crash also increases the complexity for managing the transaction.
In order to overcome these situations, WCF come up with distributed transaction using two way committed protocol and dedicated transaction manager. Transaction Manager is the third party for the service that will manage the transaction using two phase committed protocol. Let us see how Transaction manager will manage the transaction using two-phase committed protocols.
Transaction Propagation In WCF, transaction can be propagated across service boundary. This enables service to participate in a client transaction and it includes multiple services in same transaction, Client itself will act as service or client. We can specify whether or not client transaction is propagated to service by changing Binding and operational contract configuration Even after enabling transaction flow does not mean that the service wants to use the client’s transaction in every operation. We need to specify the “TransactionFlowAttribute― in operational contract to enable transaction flow. [ServiceContract] public interface IService { [OperationContract] [TransactionFlow(TransactionFlowOption.Allowed)] int Add(int a, int b); [OperationContract] int Subtract(int a, int b);
}
Note: TransactionFlow can be enabled only at the operation level not at the service level.
Binding configuration
TransactionFlowOption
transactionFlow="true" NotAllowed
or transactionFlow="false"
Allowed
transactionFlow="true"
Allowed
transactionFlow="false"
Mandatory
transactionFlow="true"
Client cannot propagate its transaction to service even client has transaction Service will allow to flow client transaction. It is not necessary that service to use client transaction. If service disallows at binding level, client also should disable at binding level else error will be occurred. Both Service and client must use transaction aware binding InvalidOperationException will be throw when serice binding
Mandatory
transactionFlow="false"
disables at binding level. FaultException will be thrown when client disable at its binding level.
Transaction Protocols As a developer we no need to concern about transaction protocols and transaction manager used by WCF. WCF itself will take care of what kind of transaction protocols should be used for different situation. Basically there are three different kinds of transaction protocols used by WCF.
Transaction Mode This article explains about the how to configure the service and client transaction mode in WCF service.
Client transaction – Transaction setting propagated or initiated from the client side Server transaction – Transaction setting propagated or initiated from server side
Client/Server transaction mode: This setting ensures that service uses the client‟s transaction if possible or a server side transaction when the client does not have a transaction.
1. Enable the TransactionFlow=true in binding configuration 2. Set TransactionFlowOption.Allowed in the operation contract 3. Set TransactionScopeRequired=true in the operation contract Client transaction mode: This settings ensures the service uses only the client‟s transaction
1. Enable the TransactionFlow=true in binding configuration 2. Set TransactionFlowOption.Mandatory in the operation contract 3. Set TransactionScopeRequired=true in the operation contract
Service transaction mode: This seeing ensures that the service always has a transaction, separated from any transaction its client may or may not have.
1. Disable the TransactionFlow=false in binding configuration 2. Set TransactionFlowOption.NotAllowed in the operation contract 3. Set TransactionScopeRequired=true in the operation contract None transaction mode: This setting ensures service does not use transaction
1. Disable the TransactionFlow=false in binding configuration 2. Set TransactionFlowOption.NotAllowed in the operation contract 3. Set TransactionScopeRequired=false in the operation contract Below table explains about the Transaction mode activation based on the binging, contract and behavior settings
Binding Transaction flow TransactionFlowOption TransactionScopeRequired Transaction mode False
Allowed
False
None
False
Allowed
True
Service
False
NotAllowed
False
None
False
Allowed
True
Service
True
Allowed
False
None
True
Allowed
True
Client/Service
True
Mandatory
False
None
True
Mandatory
True
Client
How to Create WCF Transaction This article explains about the how to create a WCF service with transaction enabled. Refer “Transaction Mode” article to learn more about the server side and client side transaction mode. WCF transaction was explained with below employee service
1. 2. 3. 4. 5.
Create the Employee WCF service to allow client user to insert employee detail Enable the transaction from server side by setting proper attributes Create the client application by consuming the Employee Service and insert the employee details Run the client application to successfully insert the employee detail Modify the service application to throw exception explicitly after successfully insert statement execution and check the transaction behavior.
Step 1:Create the Employee service that allows the addition of new employee details in DB. Decorate the operation contract with TransactionFlow attribute for enabling the transaction. TransactionFlowOption take three set of values.
TransactionFlowOption.Allowed TransactionFlowOption.Mandatory TransactionFlowOption.NotAllowed
[ServiceContract] public interface IService { [OperationContract] [TransactionFlow(TransactionFlowOption.Allowed
)]
bool AddEmployee(int id, string name, int salary); } Step 2:Create the service class which implements the service contract and set the operation behavior withTransactionScopeRequired = true . This attribute is used to enable the service transaction when the client transaction is not available.
public class Service : IService { [OperationBehavior(TransactionScopeRequired = true)] public bool AddEmployee(int id, string name, int salary) { try { //Insert the employee tables inside the transaction SqlConnection conn = new SqlConnection(@"Data Source=.\eaudit;Initial Catalog=Test01;Integrated Security=SSPI;"); SqlCommand cmd = new SqlCommand("INSERT INTO [Test01].[dbo].[Employee] VALUES("+id.ToString ()+",'"+name +"', "+salary.ToString ()+")", conn); cmd.CommandType = System.Data.CommandType.Text; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); return true; } catch(Exception ex) { //return false ; throw new FaultException(ex.Message);
} } }
Step 3:Update the service endpoint to enable transactions for wsHttpBinding by setting the transactionFlow attribute to true. Setting transactionFlow at config level doesn‟t mean that the service wants to use the client‟s transaction in every operation. It is required to set the transaction at the service contract level as mention in Step 1. Step 4:Now service creation is completed and let‟s starts with the client application. Create a new console application from add Employee service as ServiceReference
Step 5:Create a new proxy object for the employee service and call the AddEmployee method.
static void Main(string[] args) { bool result=false ; using (TransactionScope ts = new TransactionScope (TransactionScopeOption.RequiresNew)) { try { EmployeeService.ServiceClient service = new EmployeeService.ServiceClient(); result = service.AddEmployee(1, "raj", 3000); ts.Complete(); } catch (Exception ex) { ts.Dispose(); Console.WriteLine(ex.Message); } }
if( result == true ) Console.WriteLine("Employee details add successfully"); else Console.WriteLine ("Error while adding employee details"); Console.ReadLine(); } Output: Output shows the employee detail is added successfully and DB also shows the new entry is made
Step 6:Now everything works fine, let‟s test the transaction by throwing the exception from server side after successful execution of employee details insert statement
try { //Insert the employee tables inside the transaction SqlConnection conn = new SqlConnection(@"Data Source=.\eaudit; Initial Catalog=Test01;Integrated Security=SSPI;"); SqlCommand cmd = new SqlCommand("INSERT INTO [Test01].[dbo].[Employee] VALUES("+id.ToString ()+",'"+name +"',"+salary.ToString ()+")", conn); cmd.CommandType = System.Data.CommandType.Text; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); //Throw Exception after successful insert statement execution throw new Exception("Sample exeception for testing"); return true; } catch(Exception ex) { //return false ; throw new FaultException(ex.Message); }
Step 7:Run the client application and check the output. Result clearly says that even insert statement is executed successfully and error is thrown after insert statement, DB is not updated. Because all the code execution is comes under the transaction so failure in any module of code will revert back all code execution.
What is WCF RIA service? WCF RIA service is a framework to develop n-tier application for Rich Internet Application (RIA). It is mainly used in RIA applications like Silverlight, AJAX client, etc. It solves the major problem while developing business application like decoupling the resource access, application logic and presentation layer. WCF RIA service was introduced in Silverlight 4 with .net framework 4, and it can be developed using visual studio2010. Main problem developer are facing while developing the n-tier RIA application will be coordinating the application logic between middle tier and presentation tier. This problem will be solved by using WCF RIA service, it will synchronize the code between middle and presentation tier.
WCF RIA service will allow developer to write the set of service code and this server code will be available to the client side without manually duplicate that programming logic. RIA service client will be updated with business rule and entity present at the server side, when your recompile your project solution. WCF RIA service will generate the code at the client side related to the service and domain entities declared at the server side. RIA service exposes the data from server side to client side using Domain service, RIA service framework implements the each domain service as WCF service to access the data as business entity.
1. 2. 3. 4.
WCF RIA Domain Service Problems solved in RIA Service Query/Update process in RIA How to create Silverlight-WCF RIA service
fig: WCF RIA Serive architecture
Domain Service Domain services are WCF services that expose the business logic of a WCF RIA Services application. Domain service contains set of business related data operation and it is exposed as WCF service. Below diagram explains integration of the RIA service with WCF The DomainService class is the base class for all classes that serve as domain services.
DomainServiceHost is the hosting class for domain service; internally DomainServiceHost uses the WCF ServiceHost class to host the application.
A domain service class must be marked with the EnableClientAccessAttribute attribute to make the service available to the client project. The EnableClientAccessAttributeattribute is automatically applied to a domain service when you select the Enable client access check box in the Add New Domain Service Class dialog box. When the EnableClientAccessAttribute attribute is applied to a domain service, RIA Services generates the corresponding classes for the client project.
Example: [EnableClientAccess()] public class EmployeeDomainService : DomainService { private EmployeeData data = EmployeeData.Instance; public IEnumerable < Employee> GetEmployees() { return data.EmployeeList; } }
DomainContext class at the client side is used to consume the Domain service by using DomainClient object. DomainContext class available inside the name space "System.ServiceModel.DomainServices.Client"
fig: WCF RIA Domain Serive architecture
Problem solved in RIA 1. To have best performance of the RIA application, app logic need to be available in client and server side. This problem is solved by auto generating the code at the client side while recompiling the project. 2. Asynchronous call – Asynch service call are supported in Domain service by using WCF infrastructure 3. Handling large data and data across different tier – Large amount of data can be access and filter using IQueryable object. Since entity objects used in domain service are serializable and so it can be access across different layer 4. Security/Access control – ASP.Net membership frameworks are integrated with RIA service to provide security systems to RIA service 5. Validation – Entity can be validated based using adding attribute to the class members
Example:
public class Member { [Key] public int MemberId { get; set; }
public string Fname { get; set; } [Required] public string Lname { get; set; } public DateTime JoinDate { get; set; } [Range(30,90, ErrorMessage="sorry, you are either too young or too old for our club!")] public int Age { get; set; } }
Querying/Updating data in RIA Service The below diagram are self explanatory to discuss about the querying or updating the data using RIA service
fig: WCF RIA to Query data
fig: WCF RIA to update data
How to Create WCF RIA Service Let us understand more about the WCF RIA service by creating Silverlight client application which read and updated the Employee details from WCF RIA Service. Step 1:Start the Visual Studio 2010 and click File -> New-> Project. Enter the project name and click “Create”
Step 2:Select “Enable WCF RIA Services”. This will make your Silverlight application to user WCF RIA service
Step 3:Create “Data” folder and add DataModel” class as shown below. This is the data class which will return list of Employee and update the employee list
Data Model class: public class Employee { [Key] public int EmpId { get; set; } public string Fname { get; set; } public string Lname { get; set; } public DateTime JoinDate { get; set; } public int Age { get; set; } }
public partial class EmployeeData { private static readonly EmployeeData _instance = new EmployeeData(); private EmployeeData() { } public static EmployeeData Instance
{ get { return _instance; } }
private List < Employee > empList = new List < Employee>() { new Employee() { EmpId
= 1, Fname = "Sam", Lname = "kumar",
JoinDate=new DateTime(2010,7, 21), Age=30}, new Employee() { EmpId = 2, Fname = "Ram", Lname = "kumar", JoinDate=new DateTime(2009,6,8), Age=35}, new Employee() { EmpId = 3, Fname = "Sasi", Lname = "M", JoinDate=new DateTime(2008,3,5), Age=39}, new Employee() { EmpId = 4, Fname = "Praveen", Lname = "KR", JoinDate=new DateTime(2010, 5,1), Age=56}, new Employee() { EmpId = 5, Fname = "Sathish", Lname = "V", JoinDate = new DateTime(2006,12,15), Age=72}, new Employee() { EmpId = 6, Fname = "Rosh", Lname = "A", JoinDate=new DateTime(2009,2,2), Age=25} }; public IEnumerable< Employee > EmployeeList { get { return empList; } }
public void Update(Employee updEmployee) { Employee existing = empList.Find(p => p.EmpId == updEmployee.EmpId); if (existing == null) throw new KeyNotFoundException("Specified Employee cannot be found"); existing.Fname = updEmployee.Fname; existing.Lname = updEmployee.Lname; existing.JoinDate = updEmployee.JoinDate; existing.Age = updEmployee.Age; } }
Step 4:To expose the Employee related operation to the client side, Create domain service class. By right click project file and select Add new item.
Step 5:Add code to return the Employee list
Domain Service class: // TODO: Create methods containing your application logic. [EnableClientAccess()] public class EmployeeDomainService : DomainService { //Create instance of the Data access layer private EmployeeData data = EmployeeData.Instance; public IEnumerable< Employee> GetEmployee() { return data.EmployeeList ; } public void UpdateEmployee(Employee emp) { data.Update(emp); } }
Step 6:Compile the solution – After compilation RIA service will generate the application logic at the client side using DomainContext object. Enable show all files option for the solution and view the auto generated code.
Step 7:View the DomainContext class are created at the client side.
Domain Context class at client: /// /// The DomainContext corresponding to the 'EmployeeDomainService' DomainService. /// public sealed partial class EmployeeDomainContext : DomainContext { #region Extensibility Method Definitions /// /// This method is invoked from the constructor once initialization is complete and /// can be used for further object setup. /// partial void OnCreated(); #endregion
/// /// Initializes a new instance of the < see cref="EmployeeDomainContext"/> class.
/// public EmployeeDomainContext() : this(new WebDomainClient< IEmployeeDomainServiceContract>(new Uri("MyFirstRIAApplication-Web-EmployeeDomainService.svc", UriKind.Relative))) { } ........ ........ Step 8:Add DataGrid to Main.xaml file to display the employee details query from DataModel and add two buttons to update and reject the data changed from client side.
Main.xaml < Grid x:Name="LayoutRoot" Background="White"> < StackPanel Orientation="Vertical" HorizontalAlignment="Left"
>
< sdk:DataGrid x:Name="EmployeeGrid" AutoGenerateColumns="True" RowEditEnded="EmployeeGrid_RowEditEnded" /> < Button Content="Accept" Height="23" Name="btnAccept" Width="75" Margin="5" Click="btnAccept_Click" < Button Content="Reject" Height="23" Name="btnReject" Width="75" Margin="5" Click="btnReject_Click"/>
Main.xaml.vb public partial class MainPage : UserControl { //create instance of Doman context class EmployeeDomainContext ctx = new EmployeeDomainContext(); public MainPage() { InitializeComponent(); //Load query data , Read data from DAL layer to UI EntityQuery< Employee> query = ctx.GetEmployeeQuery(); LoadOperation< Employee> lo = ctx.Load< Employee>(query); EmployeeGrid.ItemsSource = lo.Entities; } private void EmployeeGrid_RowEditEnded(object sender, DataGridRowEditEndedEventArgs e)
/>
{ } private void btnAccept_Click(object sender, RoutedEventArgs e) { //Update the DAL with user changes ctx.SubmitChanges(); } private void btnReject_Click(object sender, RoutedEventArgs e) { //Roll back the user changes ctx.RejectChanges(); } } Step 9:Run the application and see the output as shown below
Introduction to RESTful service REST – Representational State Transfer "REST, an architectural style for building distributed hypermedia driven applications, involves building Resource-Oriented Architecture (ROA) by defining resources that implement uniform interfaces using standard HTTP verbs (GET, POST, PUT, and DELETE), and that can be located/identified by a Uniform Resource Identifier (URI)." Any Service which follows this REST architecture style is called as RESTful service. It became very popular because of it behavior, it is similar to the website i.e we can load the server information using web url in the browser. similarly we can also access/modify the server resource using Url in RESTful service
RESTful service will allow the client (written in different language)to access or modify the resource in the server using URL. RESTful service uses the http protocol for its communication and it is stateless RESTful service can transfer the data in XML,JSON,RSS,ATOM
SOAP
Simple Object Application Protocol SOAP – is a package contain message information and it will be delivered by HTTP Developers are mainly preferred to user because of its increase interoperability Lot of tools are available in the market to generate the clients code from WSDL
POX(plain-old XML)
Plain raw XML message will be used for communication Developers using POX had to write their own code for XML and HTTP for request/response message. So most of the developers moved back to SOAP
REST
REST defines more of a transport-specific model In reality HTTP is the only protocol that is used in practice today for building RESTful architecture.
This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods. According to this mapping
To create a resource on the server, use POST. To retrieve a resource, use GET. To change the state of a resource or to update it, use PUT. To remove or delete a resource, use DELETE.
RESTful service can be created by using WebGetAttribute and WebInvokeAttribute attribute. RESTful service has provided separate attribute for GET operation (WebGet) because it want to make use of complete features. Other operations like POST,PUT,DELETE will come under the WebInvoke attribute.
1. How to create RESTful Service 2. JSON using WCF service
How to create RESTful service This sample explains about the creating the RESTful service to create and updating the resource information available at the sever side. This Restful service will be consumed using client console application. Step 1: For our example we are suing “EmployeeData” class as Data Access Layer for storing and reading the employee information.
Data Model class: namespace MyFirstRESTfulService { [DataContract] public class Employee { [DataMember] public int EmpId { get; set; } [DataMember] public string Fname { get; set; } [DataMember] public string Lname { get; set; } [DataMember ] public DateTime JoinDate { get; set; } [DataMember] public int Age { get; set; } [DataMember] public int Salary { get; set; } [DataMember] public string Designation { get; set; } }
public partial class EmployeeData { private static readonly EmployeeData _instance = new EmployeeData(); private EmployeeData() { } public static EmployeeData Instance { get { return _instance; } }
private List< Employee> empList = new List < Employee>() { new Employee() { EmpId = 1, Fname = "Sam", Lname = "kumar", JoinDate=new DateTime(2010,7, 21), Age=30,Salary=10000,Designation="Software Engineer"}, new Employee() { EmpId = 2, Fname = "Ram", Lname = "kumar", JoinDate=new DateTime(2009,6,8), Age=35,Salary=10000,Designation="Senior Software Engineer"},
new Employee() { EmpId = 3, Fname = "Sasi", Lname = "M", JoinDate=new DateTime(2008,3,5), Age=39,Salary=10000,Designation="Projet Manager"}, new Employee() { EmpId = 4, Fname = "Praveen", Lname = "KR", JoinDate=new DateTime(2010, 5,1), Age=56,Salary=10000,Designation="Projet Manager"}, new Employee() { EmpId = 5, Fname = "Sathish", Lname = "V", JoinDate = new DateTime(2006,12,15), Age=72,Salary=10000,Designation="Senior Software Engineer"}, new Employee() { EmpId = 6, Fname = "Rosh", Lname = "A", JoinDate=new DateTime(2009,2,2), Age=25,Salary=10000,Designation="Software Engineer"} }; public List< Employee> EmployeeList { get { return empList; } }
public void Update(Employee updEmployee) { Employee existing = empList.Find(p => p.EmpId == updEmployee.EmpId); if (existing == null) throw new KeyNotFoundException("Specified Employee cannot be found"); existing.Fname = updEmployee.Fname; existing.Lname = updEmployee.Lname; existing.Age = updEmployee.Age; } public void Delete(int empid) { Employee existing = empList.Find(p => p.EmpId == empid); empList.Remove(existing); } public void Add(Employee newEmployee) { empList.Add(new Employee { EmpId = newEmployee.EmpId, Fname = newEmployee.Fname, Lname = newEmployee.Lname, Age = newEmployee.Age, JoinDate = DateTime.Now, Designation = newEmployee.Designation, Salary = newEmployee.Salary }); } } }
Step 2: Let‟s start create EmployeeService (simple WCF) with ServiceContract, OperationContract and DataContract as shown below.
Interface and Implementation: [ServiceContract()] public interface IEmployeeService { [OperationContract] List< Employee > GetAllEmployeeDetails(); [OperationContract] Employee GetEmployee(int Id); [OperationContract] void AddEmployee(Employee newEmp); [OperationContract] void UpdateEmployee(Employee newEmp); [OperationContract] void DeleteEmployee(string empId); } [AspNetCompatibilityRequirements(RequirementsMode= AspNetCompatibilityRequirementsMode.Allowed )] public class EmployeeService: IEmployeeService { public List < Employee > GetAllEmployeeDetails() { return EmployeeData.Instance.EmployeeList; } public Employee GetEmployee(int id) { IEnumerable< Employee > empList = EmployeeData.Instance.EmployeeList.Where(x => x.EmpId == id); if (empList != null) return empList.First< Employee >(); else return null; }
public void AddEmployee(Employee newEmp) { EmployeeData.Instance.Add(newEmp); }
public void UpdateEmployee( Employee newEmp) { EmployeeData.Instance.Update(newEmp);
}
public void DeleteEmployee(string empId) { EmployeeData.Instance.Delete(System.Convert .ToInt32 (empId)); } } Step2: This service can be hosted as normal WCF service by creating the ServiceHost object and adding endpoint with different binding. This is already explained in “ConsoledHosted WCF Service”. As it is mention in introduction section of RESTful service, all the resource located in server side can be accessed using url. Method exposed at the server side can be call using url, to do that we need to decorate the service method with “WebGet” or “WebInvoke” attribute as mention below
[ServiceContract()] public interface IEmployeeService { [WebGet(UriTemplate = "Employee")] [OperationContract] List< Employee > GetAllEmployeeDetails(); [WebGet(UriTemplate = "Employee?id={id}")] [OperationContract] Employee GetEmployee(int Id); [WebInvoke(Method = "POST", UriTemplate = "EmployeePOST")] [OperationContract] void AddEmployee(Employee newEmp); [WebInvoke(Method = "PUT", UriTemplate = "EmployeePUT")] [OperationContract] void UpdateEmployee(Employee newEmp); [WebInvoke(Method = "DELETE", UriTemplate = "Employee/{empId}")] [OperationContract] void DeleteEmployee(string empId); } Step4: In the above interface declaration, you can find that we have added UriTemplate”, it is nothing but a relative path for accessing the service method using url. These methods can be called from client application or browser by typing url as “WCf Service url” + “Relative Path” E.g: http://localhost:8090/MyService/EmployeeService/Employee Step 5: “Method” is another option we can add to the WebInvoke attribute to specify the mode of transfer like “PUT”, “POST”, or “DELETE” Step 6: Now we have completed with service implementation project. Let‟s start with Hosting the RESTful service. For this example we are using console application for hosting service. WCF framework has provided new class to host the RESTful service i.e WebServiceHost. By hosting the restful service with WebServiceHost host class will automatically set the binding and other configuration setting. In the below code you can see that I have only mention url for the hosting.
Uri httpUrl = new Uri("http://localhost:8090/MyService/EmployeeService"); WebServiceHost host = new WebServiceHost(typeof(MyFirstRESTfulService.EmployeeService), httpUrl); host.Open(); foreach (ServiceEndpoint se in host.Description.Endpoints) Console.WriteLine("Service is host with endpoint " + se.Address); //Console.WriteLine("ASP.Net : " + ServiceHostingEnvironment.AspNetCompatibilityEnabled); Console.WriteLine("Host is running... Press < Enter > key to stop"); Console.ReadLine(); Step 7: We can access the RESTful service using browser. Just type the url in the web browser to read all the employee details
If we need to get specific employee details, pass the employee as query parameter as we mention in UriTemplate of the service.
Step 8:Now we can start with client application. For this example we can create a console application to read the employee information and add new employee to the server resource. Below code first read the employee details from the server and add new employee and once again it read the employee details to confirm the added resource.
WebChannelFactory < IEmployeeService > cf = new WebChannelFactory< IEmployeeService >( new Uri("http://localhost:8090/MyService/EmployeeService")); IEmployeeService client = cf.CreateChannel(); var d = client.GetEmployee(1); //Load all the Employee from the server and display foreach (Employee e in client.GetAllEmployeeDetails() ) { Console.WriteLine(string.Format("EmpID:{0}, Name:{1} {2}",e.EmpId ,e.Fname ,e.Lname )); } //Add new user client.AddEmployee(new Employee() { EmpId = 11, Fname = "John", Lname = "J", JoinDate = new DateTime(2010, 7, 24), Age = 34, Salary = 10000, Designation = "Software Engineer" }); Console.WriteLine("******************After adding new user ****************"); //Load all the Employee from the server and display foreach (Employee e in client.GetAllEmployeeDetails() ) { Console.WriteLine(string.Format("EmpID:{0}, Name:{1} {2}",e.EmpId ,e.Fname ,e.Lname )); } Console.ReadLine(); }
Step 9: Run the application to view the output as shown below
JSON using WCF service This article explains about configuring the WCF service to send the response business entity as JSON objects. JSON –JavaScript Object Notation. “The JSON text format is syntactically identical to the code for creating JavaScript objects “. In most of the browser based application, WCF can be consumed using javascript or jquery. When client makes the call to the WCF, JSON or XML is used for mode of communication. WCF has option to send the response in JSON object. This can be configured with WebGet or WebInvoke attribute. In this sample we can create the sample RESTful service to expose the method to read/add/update/delete the employee information. Read the “How to create REST ful Service” articles for more information. On top of the Restful service we need to update the ResponseMode attribute to send the business entity as JSON object. Below code shows how to configure the JSON response format.
[ServiceContract()] public interface IEmployeeService { [WebGet(UriTemplate = "Employee", ResponseFormat=WebMessageFormat.Json )] [OperationContract] List < Employee > GetAllEmployeeDetails(); [WebGet(UriTemplate = "Employee?id={id}", ResponseFormat = WebMessageFormat.Json)] [OperationContract] Employee GetEmployee(int Id); [WebInvoke(Method = "POST", UriTemplate = "EmployeePOST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] [OperationContract] void AddEmployee(Employee newEmp);
[WebInvoke(Method = "PUT", UriTemplate = "EmployeePUT", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] [OperationContract] void UpdateEmployee(Employee newEmp); [WebInvoke(Method = "DELETE", UriTemplate = "Employee/{empId}", ResponseFormat = WebMessageFormat.Json)] [OperationContract] void DeleteEmployee(string empId); } You can see that WCF response are send as JSON object while accessing data using browser.
Below sample is the ASP.Net web application is used to explains about the CRUD from WCF service with response as JSON object. GET Method
function RefreshPage() { var serviceUrl = "http://saravana:8090/MyService/EmployeeService/Employee"; $.ajax({ type: "GET", url: serviceUrl, dataType: 'json', contentType: "application/json; charset=utf-8", success: function (data) { var itemRow = "< table >"; $.each(data, function (index, item) { itemRow += "" + item.EmpId + "" + item.Fname + ""; }); itemRow += ""; $("#divItems").html(itemRow); }, error: ServiceFailed }); } POST Method
function POSTMethodCall() {
var EmpUser = [{ "EmpId": "13", "Fname": "WebClientUser", "Lname": "Raju", "JoinDate": Date(1224043200000), "Age": "23", "Salary": "12000", "Designation": "Software Engineer"}]; var st = JSON.stringify(EmpUser); debugger; $.ajax({ type: "POST", url: "http://saravana:8090/MyService/EmployeeService/EmployeePOST", data: JSON.stringify(EmpUser), contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { // Play with response returned in JSON format }, error:ServiceFailed }); } < PUT Method
function PUTMethodCall() { var EmpUser = [{ "EmpId": "3", "Fname": "WebClientUser", "Lname": "Raju", "JoinDate": Date(1224043200000), "Age": "23", "Salary": "12000", "Designation": "Software Engineer"}]; $.ajax({ type: "PUT", url: "http://saravana:8090/MyService/EmployeeService/EmployeePUT", data: EmpUser, contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { // Play with response returned in JSON format }, error: ServiceFailed }); } < DELETE Method
function DELETEMethodCall() { $.ajax({ type: "DELETE", url: "http://saravana:8090/MyService/EmployeeService/Employee/2", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json",
success: function (data) { // Play with response returned in JSON format }, error: function (msg) { alert(msg); } }); }
WCF Security This article explains about the security system available in WCF service. When WCF service is created, it is required to secure the service so that only required client can consume the service. This will make sure that communication channel between client and service is secured.
1. 2. 3. 4.
Types Of Authentication Transfer Security Mode Transport Security Protection Level Message Security Level
Types of Authentication WCF Authentication is basically referred to the verification of the caller who claims to the call the service. Verification of caller will be referring as service authentication. WCF offers various authentication mechanisms No authentication: Service does not authenticate its caller and it will allow all clients to access. Windows authentication: Services use Kerberos when a windows domain service is available or NTLM when deployed in workgroup configuration. In this mode caller provides the windows credential tickets/token to the service authentication. UserName/Password: Explicit username and password is provided to authenticate the service. X509 certificates: In this mode of security, client will send his certificate information to the service communication. Service host will check and validate the caller certificate information to authenticate the service.
Custom mechanism: WCF allows developers to replace the build-in authentication mechanism by providing user own protocol and credential type for authentication. Issue token: The caller and the service can both rely on a secure token service to issue the client a token that service identify and trust. E.g windows card space
Transfer Security Mode When we talk about the client server secured communication, we have consider the three aspects to transfer security
1. Message integrity – it ensures that message used in communication is not tampered by any malicious party. 2. Message privacy – It ensures confidentiality of the msessage so that no third part can even read the message. 3. Transfer security – it ensures that only authenticated user can able to read the content of the message. WCF supports five different modes of transfer security to accomplish above three aspects. No transfer security mode: This ensure that no security is applied while communication between server and client Transport security mode: When system is configured with „Transport‟ mode, WCF uses secured communication protocol. The available secure transports are HTTPS, TCP, IPC and MSMQ. Transport security encrypts all communication on the channel and provides integrity, privacy and mutual authentication. It provides point-to-point security. One of main disadvantage is that it can only guarantee transfer security point-to-point, meaning it secure only at channel level. Message inside the channel will not get secured. In case of distributed communication, multiple intermediaries between service and client will not be secure. It is mainly used in intranet application
Message security mode: In this mode of configuration, message will get encrypted. Encrypting the message rather than transport enables the service to communicate securely over non secure transport such as HTTP. It provides end-to-end security. One of the disadvantages of message security is that it may introduce call latency due to its inherent overhead. It is mainly used in internet application. Mixed transfer security mode: It uses Transport security for message integrity, privacy and service authentication and it uses Message security for securing client credential. One of disadvantage of the mixed mode is that it will secure only point-to-point as nature of Transport security. Both security modes: This mode Both transfer security mode uses both Transport security and Message security. So message is secured using Message security and then it is transferred to the service using secure transport. This mode will maximize the security but overload the performance.
Name
None
Transport
Message
Mixed
Both
BasicHttpBinding
Yes(default)
Yes
Yes
Yes
No
NetTcpBinding
Yes
Yes(default)
Yes
Yes
No
NetNamedPipeBinding
Yes
Yes(default)
No
No
No
WsHttpBinding
Yes
Yes
Yes(default)
Yes
No
WsDualHttpBinding
Yes
No
Yes(default)
No
No
NetMsmqHttpBinding
Yes
Yes
Yes(default)
No
Yes
Transport Security Protection Level This article explains about the how to configure the service with Transport security settings and what are the protection level available. When configure transfer security for Transport security, not all bindings support all client credential type Below table list client credential for different binding
Name
None
Windows
Username
Certificate
BasicHttpBinding
Yes(default)
Yes
Yes
Yes
NetTcpBinding
Yes
Yes(default)
No
Yes
NetNamedPipeBinding
No
Yes(default)
No
No
WsHttpBinding
Yes
Yes(default)
Yes
Yes
WsDualHttpBinding
N/A
N/A
N/A
N/A
NetMsmqHttpBinding
Yes
Yes(default)
No
Yes
Below diagram explain about how set the client credential in configuration file
While developing Intranet application, it is good to go with Transportnode for transfer security because calls are invariably point-to-point. In NetTcpBinding/NetNamedPipeBinding/NetMsmqBinding supports three level of protection to transfer message
>
None: Message does not get protected while transfer from client and service Signed: this protection level make sure that message is received from authenticated user, but it message can be tampered by any third party. Encrypted and Signed: This level makes sure that message is received from authenticated user and it also encrypts the message
Message Security Level This article explains about the how to configure the service with Message security settings and what are the client credential available for this mode. When configure transfer security for Message security, not all bindings support all client credential type Below table list client credential for different binding
Name
None
Windows
Username
Certificate
Issued token
BasicHttpBinding
No
No
No
Yes
No
NetTcpBinding
Yes
Yes(default)
Yes
Yes
Yes
NetNamedPipeBinding
N/A
N/A
N/A
N/A
N/A
WsHttpBinding
Yes
Yes(default)
Yes
Yes
Yes
WsDualHttpBinding
Yes
Yes(default)
Yes
Yes
Yes
NetMsmqHttpBinding
Yes
Yes(default)
Yes
Yes
Yes
Below diagram explain about how set the client credential in configuration file
WCF Service Impersonation This article explains about how to impersonate the service call, when client request for the operation When client try to access the service resource, it does not have permission to do so. In this case, developer can impersonate the client request authorize to access the resource.
[OperationBehavior (Impersonation = ImpersonationOption.Allowed )] public string GetData(int value)
{ return string.Format("You entered: {0}", value); }
Impersonation takes three level of setting
1. NotAllowed : This indicate the service should not auto-impersonate 2. Allowed : automatically impersonate the caller whenever Windows authentication is used, but it has no effect with other authentication mechanisms 3. Required: It makes sure that Windows authentication is used else it will throw exception. Impersonate all operation: Impersonation can be allowed for all operation by setting the service Authorization in service behavior section as shown below.
WCF Windows Authentication This article explains about the creating the WCF service with Windows Authentication enabled. Step 1: Create the WCF service and hosted in IIS, change the configuration sections as mention below
Step 2: Verify that only "Windows Authentication" is enabled in IIS Authentication settings
Step 3: Create client application and create the proxy for the WCF service Step 4: Make sure that client side configuration are updated with "Windows" Authentication as mention below
Step 5: Sample client code to consume the service
Note: If Metadata Exchange Endpoint is enabled in service configuration , you will get below error. Make sure it is commented. Security settings for this service require 'Anonymous' Authentication but it is not enabled for the IIS application that hosts this service If Client and Service configuration is not properly configured with “Windows Authentication”, you will get below error. Make sure both are using same config settings. The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'.
What's new in WCF 4.5 This article explains about the new features introduced in WCF 4.5. Microsoft has brought new feautes in WCF 4.5 to reduce the developers job and maintain the code
All new features of WCF 4.5 is explained in different parts
Task-based Async Support, Config Validation Contract-First Development, Simplified config XmlDictionaryReaderQuotas, Configuration tooltips Streaming Improvements, WebSocket, Single WSDL HTTPS with IIS, Configuring WCF Services in Code Compress the Binary Encoder, ChannelFactory Caching UDP Endpoint, Multiple Authentication IDN Support
What's new in WCF 4.5 - Part 1 WCF Configuration Validation In old version of WCF, configuration files are not validated while building the project. But in WCF 4.5 while compiling the project, validation errors will be displayed as warning message in visual studio.
Task-based Async Support In WCF4.5, by default Task based async service operations methods are generated while Adding Service Reference. This is done for both synchronous and asynchronous method. This allows the client application to call the service operation using Task based programming model. In WCF 4.5, if you select the “Generate asynchronous operations” while adding service reference. Old form of async operations methods are created in the proxy class Fig 1: Add service Reference from WCF 3.5
Fig 2: Add service Reference from WCF 4.5
Fig 3: Service Client proxy generated using WCF 3.5
Fig 4: Service Client proxy generated using WCF 4.5
What's new in WCF 4.5 - Part 2 Simplified Generated Configuration Files In old version WCF, configuration files generated at the client side will have all default setting and it looks complex. But in WCF 4.5, when you generate the configuration file using SvcUtil.exe tool or Service Reference only non-default value will be available in the configuration file. Fig 1: Configuration file generated in WCF 4.0
Fig 2: Configuration file generated in WCF 4.5
Contract-First Development In WCF4.5, Using "SvcUtil.exe" you can generate only the contract files, in old version this feature is not available. If you create the proxy using "SvcUtil.exe", system will generate the contract, service client operation and data contract in single "service.cs" file. If you want to generate only contract you can use this simple command "/serviceContract". Fig 3:Contract file creation using SvcUtil.exe
What's new in WCF 4.5 - Part 3 Default - ASP.NET Compatibility Mode In general WCF service hosting AppDomain can run in two different mode
Mixed Transports Mode(Default): In this mode does not participate in ASP.NET HTTP pipeline and it behaves consistently independent of hosting environment and transport. ASP.Net Compatibility Mode: In this mode, service will participate in ASP.Net HTTP pipeline and it is similar to old web service (.asmx). ASP.NET features such as File Authorization, UrlAuthorization, and HTTP Session State are applicable to services running in this mode
In WCF 4.5 default aspNetCompatibilityEnabled attribute to true in web.config Fig 1: WCF 4.5 Configuration file
Fig 2: WCF 4.0 Configuration file
Configuration tooltips In WCF 4.5, tooltips are provided for configuration file, this makes the developers job simple.
XmlDictionaryReaderQuotas XmlDictionaryReaderQuotas contains configurable quota values for XML dictionary readers which limit the amount of memory utilized by an encoder while creating a message. While these quotas are configurable, the default values have changed to lessen the possibility that a developer will need to set them explicitly MaxArrayLength
Int32.MaxValue
MaxBytesPerRead
Int32.MaxValue
MaxDepth
128 nodes deep
MaxNameTableCharCount Int32.MaxValue MaxStringContentLength Int32.MaxValue
What's new in WCF 4.5 - Part 4 Streaming Improvements WCF 4.5 support for true asynchronous streaming. Let see what is mean by true asynchronous streaming
In previous version, When WCF service is sending streamed messages to multiple clients. Service will be block its thread to transfer to next client till the slow client is received the message. But in case of WCF4.5, service does not block one thread per client anymore and will free up the thread to service another client
How to enable asynchronous streaming?
In previous versions of WCF when receiving a message for an IIS-hosted service that used streaming message transfer, ASP.NET would buffer the entire message before sending it to WCF. This would cause large memory consumption. This buffering has been removed in .NET 4.5 and now IIS-hosted WCF services can start processing the incoming stream before the entire message has been received, thereby enabling true streaming.
Generating a Single WSDL Document In WCF 4.0 and lower version, generated wsdl file does not contain all metadata information in single file. WSDL file will refer the other document using „import‟ statement as shown below. So when third party try to consume the service using WSDL has to explicitly add these references. In WCF 4.5, service provide two option to create the wsdl, we can create wsdl information in single file
WebSocket Support WebSocket is a web technology providing dbi directional communications channels over a single TCP connection. WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application. The WebSocket Protocol is an independent TCP-based protocol. Two new bindings are added in WCF4.5 to support communication over WebSocket. NetHttpBinding NetHttpsBinding
What's new in WCF 4.5 - Part 5 Simple to expose HTTPS with IIS WCF 4.0 WCF 4.0 has one of new feature called default endpoint, when ever new service is created default endpoint created with „basicHttpBinding‟. But if you need to expose the service in „HTTPS‟ binding then you need to Explicitly create the endpoint and provide all information. WCF 4.5 In WCF 4.5, default endpoint can be created with HTTPS binding, by simply specifying the SSL and enabling „https‟ in IIS setting How to create HTTPS with default endpoint? Step 1:Create the WCF service and browse the WSDL, you will find only basicHttpBinding as shown below Fig 1 : default 'basicHttpBinding'
Step 2:Host the WCF service in IIS and set the „https‟ binding for the website
Step 3:Browse the wsdl file from IIS, you can see the https enabled by default. It is so simple WCF 4.5
Configuring WCF Services in Code In general, WCF provides option to configure the service using config file or through code. In older version of WCF (4.0 or older), if you want to configure the web hosted service, then you need to create aServiceHostFactory that created the ServiceHost and performed any needed configuration. But in case of WCF 4.5 it is very simple, you need to define a public static method called Configure with the following signature in your service implementation class. This method will be called before service host is opened. Note: If static Configuration() method is specified, setting mention in app.config or web.config file will be ignored. Code sample: public class Service : IService { public static void Configure(ServiceConfiguration config) { ServiceEndpoint se = new ServiceEndpoint(new ContractDescription("IService1"), new BasicHttpBinding(), new EndpointAddress("basic")); se.Behaviors.Add(new MyEndpointBehavior()); config.AddServiceEndpoint(se); config.Description.Behaviors.Add(new ServiceMetadataBehavior { HttpGetEnabled = true });
config.Description.Behaviors.Add(new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true }); } public string GetData(int value) { return string.Format("You entered: {0}", value); } }
What's new in WCF 4.5 - Part 6 Compress the Binary Encoder message Begging from WCF 4.5 onwards, WCF binary message encoder supports message compression. Type of compression can be mention in the binding settings Points to remember:
1. Both the client and the service must configure the CompressionFormat property, if service is configured with compression and client is not configured then system will throw exception. 2. Compression will work for HTTP, HTTPS and TCP protocol 3. You need to create the custom binding to use this feature 4. Compression is mostly useful if network bandwidth is a bottleneck. In the case where the CPU is the bottleneck, compression will decrease throughput.
ChannelFactory Caching In some client application ChannelFactory is used to create a communication between Client and Service. Creating ChannelFactor will increase the overhead by following operation.
1. 2. 3. 4.
Constructing the ContractDescription tree Reflecting all of the required CLR types Constructing the channel stack Disposing of resources
In order to avoid this overhead, WCF 4.5 introduced the caching mechanism for ChannelFactor. Caching will take three types of values
CacheSetting.AlwaysOn - All instances of ClientBase within the app-domain can participate in caching CacheSetting.AlwaysOff - Caching is turned off for all instances of ClientBase CacheSetting.Default - Only instances of ClientBase created from endpoints defined in configuration files participate in caching within the app-domain ClientBase < IService>.CacheSetting
= CacheSetting.AlwaysOn;
foreach (string id in lstEmpIds) { using (TestClient proxy = new TestClient(new BasicHttpBinding(), new EndpointAddress(address))) { // ... proxy.GetEmployeeDetails(id); // ... } }
What's new in WCF 4.5 - Part 7 Support for UDP Endpoint WCF 4.5 allows to use the UDP protocol for communication, so that developer can create the oneway operation message(fire and forget). In certain scenario UDP is much faster than TCP protocol, because TCP add extra validation to check message are delivered in order. But in case of UDP data deliver is not guaranteed Configuration settings
Multiple Authentication Support When you develop an ASP.Net application, multiple authentication modes are enabled by changing the “Authentication” setting on virtual directory Similarly WCF4.5 provides multiple authentications for single endpoint when using the HTTP transport and transport security. In old version WCF, multiple authentications for single service can be provided by creating different endpoint. But in case of WCF4.5 multiple authentications can be configured using single endpoint.
Steps to enable Multiple Authentication in WCF Step 1: Create WCF service in host in IIS, Set the authentication as mention below
Step 2: Set the security mode to Transport or TransportCredentialOnly and clientCredentialType to "InheritedFromHost"
What's new in WCF 4.5 - Part 8 Internationalized Domain Names support Internationalized domain name is a domain name that contains non-ASCII characters. Now WCF 4.5 support the IDN. Means ?
1. Ability to host WCF with IDN name 2. Client can call the service by using IDN name Fig 1: Display the config settings
Uri has two properties Host and DnsSafeHost. These properties contain Unicode or Punycode values depending upon the IDN configuration settings
"None" - no conversions are performed by Uri.Host or Uri.DnsSafeHos "AllExceptIntranet" - uri.Host remains Unicode and uri.DnsSafeHost is converted to Punycode "All" - uri.DnsSafeHost is converted to Punycode for internet addresses, and remains Unicode for intranet addresses
Note:This setting is not required to be configured for Windows 8 and newer versions.
View more...
Comments