□Chapter 3: Exploring the WCF Programming Model. . This book is a complete guide to Windows Communication Foundation (WCF) from a service-oriented architecture (SOA) perspective. ws//04/discovery/caite.info WCF stands for Windows Communication Foundation. It is a framework for This tutorial explains the fundamentals of WCF and is conveniently divided into various sections. Microsoft Visual Studio is a complete package of development. object references as parameters: only primitive types or data contracts are Each call made by a WCF client must complete within a configurable timeout. If, for.
|Language:||English, Spanish, French|
|Genre:||Politics & Laws|
|ePub File Size:||30.76 MB|
|PDF File Size:||15.12 MB|
|Distribution:||Free* [*Regsitration Required]|
that addressed WCF from the perspective of the client such as consuming .. pending transactions will be complete when the current session is closed: To specify one of the following values, you will need to add a reference to the System. 12 Implementing a WCF Service for Good Performance. You'll need the following hardware and software to complete the practice exercises in this Browse tab, and add references to the following assemblies required by the DAAB caite.info caite.info caite.info and complete the form there to send us the error you have found. However, the other option is to add a reference to the WCF service from.
Gets or sets the namespace for the data contract for the type. It is a programming model for building service-oriented applications. Visual studio is available at different edition. Use when service needs to notify the client that it finished processing an operation or when service can publish events to which client can subscribe. It is two way communications.
As an example. Execute the following command 5. Similarly we can add different protocols to the Default Web site. Right click on the "Command Prompt" item.
Create the Contract by creating interface IMathService and add ServiceContract attribute to the interface and add OperationContract attribute to the method declaration.
Next we need to add Binding to the Default Web site. Create WAS hosted service Step 1: Next we are going to create the service. Service file is shown below. Implementation of the IMathService interface is shown below. Without publishing the service Metadata we cannot create the proxy using net.
Config file. Execute the following command C: In web.
So create the Metada Exchange end point with address as 'mex' and binding as 'mexTcpBinding'. Next we can create the proxy class using service uttility and add the proxy class to the client application. Create the client application as shown below and add the reference 'System. Creat the proxy class using Visual Studio Command prompt and execute the command svcutil. Now the service is ready to use. WriteLine "Sum of two number 5. WriteLine client. Create the object for the MathServiceClient and call the method.
Add the proxy class and configuration file to the client application. We will use same set of code used for hosting the WCF service in Console application to this. Now let start create the WCF service. ServiceModel to the project. This is same as hosting the service in IIS without message activated.
There is some advantage of hosting service in Windows service. Add reference System. This is the core assembly used for creating the WCF service. Next we can create the ISimpleCalulator interface as shown below. Add the Service and Operation Contract attribute as shown below.
Implement the ISimpleCalculator interface as shown below. 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. Build the Project and get the dll. In this project. Now we are ready with WCF service.
On stop method you need to close the Service Host. We have to make sure that we are using only one service host object. Following code show how to host WCF service in Windows service. Add the 'WindowsServiceHostedService. OnStart method of the service. This assembly will going to act as service. So add new Installer class to the project.
StartUp type etc of the service. Run ServicesToRun. In order to install the service we need to have the Installer class for the Windows service. Please find the below code for mentioning the Service name. Next we need to install the service using Visual Studio Command Prompt. Add process. Add service. Build the project. Binding has several characteristics.
Binding Binding will describes how client will communicate with service. Now service is Hosted sucessfully and we can create the proxy class for the service and start using in the client applcaiton. 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. 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.
The binding binds your service implementation to the wire through the channel stack in the middle. It is suitable for communicating with ASP. Duplex service is a service which uses duplex message pattern, which allows service to communicate with client via callback.
It also supports communication via SOAP intermediaries. 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 WSFederation protocol.
NetTcpBinding This binding provides secure and reliable binding environment for. Net to. Net cross machine communication. 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.
By default it creates communication stack with WS-ReliableMessaging for reliability, transport security for transfer security, named pipes for message delivery and binary encoding. Binding configuration Binding can be configured either through configuration file or Programming.
Let us see the binding representation in each method. Administrative Configuration file: 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. Press key to stop". Similarly you can also create any type of binding and add to endpoint. 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.
In the following code. Http and Https can expose by appending "? Now we are going to focus mainly on publishing metadata.
Publishing Service Metadata It is the process publishing metadata. WCF uses the Metadata to describe how to interact with the service endpoint. HTTP-Get metadata address is given byhttp: There are two way to publish metadata. Retrieving Service Metadata It is the process of retrieving the metadata. WCF metadata infrastructure resides in System. It is always good practice to represent in the configuration file. Importing Service Metadata. It is always good if you configure the binding properties using configuration file.
By default service metadata is turn-off due to security reason. Using the metadata. Description namespace. It is the process of generating the abstract representation of the service using metadata. This can be configures either administratively or Programmatically.
For example service address is http: Using ServiceMetadataBehavior you can enable the metadata exchange. In the below mention configuration information. Then you have to add the behavior to host description as shown. Open ; Console. ToString ; Console.
WriteLine "Host is running Press key to stop" ; Console. 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: 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. In the configuration file of the hosting application, you can add metadata exchange endpoint as shown below. In the following code I have mention about creating the Metadata Exchange Endpoint through coding. Create the ServiceMetadataBehavior object and add to Service host description. Add smb ;. CreateMexHttpBinding ;.
Add the endpoint to the service host with address, binding and contract. Complete code for hosting the service with metadata exchange endpoint is shown below. 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 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. 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.
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. Data Contract A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged.
Next we will look into Data Contract. This data type should be identified for serialization and deserialization by mentioning with [DataContract] and [DataMember] attribute. Serialization reference to the project. This assembly holds the DataContract andDataMember attribute. Through deserialization. Data contract can be explicit or implicit. Simple type such as int.
Through serialization. A data contract can be defined as follows: Create user defined data type called Employee. User defined object are explicit or Complex type. Since we have created the data contract for the Employee class. In GetEmployee method we have created the Employee instance and return to the client. It is two way communication. SOAP body contains information which is used by the target. But at a time only one can send a message 3.
WCF uses these messages to transfer information from Source to destination. It is two way communications. The client side code is shown below. SOAP message contain Envelope. Diagram Soap envelope Message Pattern It describes how the programs will exchange message each other. Source will send message to target. Employee empDetails. Header and Body. SOAP envelope contails name.
It is one way communication. SOAP Hear contain important information which are not directly related to message. GetEmployeeDetails empId. There are three way of communication between source and destination 1. Serializing the data. WCF will automatically create the message for operation at run time. Only one parameter can be used in servicie Operation 2. In the RPC model. Let us see the sample message contract definition. On Some critical issue. What is Message contract?
As I said earlier. It also add Name. When using Message contract type as parameter. WCF will automatically take care of message. In Message style operation WCF allows to customize the message header and define the security for header and body of the message.
You have to follow certain rules while working with Message contract 1. Most of the time developer will concentrate more on developing the DataContract. If a type has both Message and Data contract. Other data types are not allowed.
EmployeeDetails GetEmployeeDetails. Service operation will accept and return only message contract type. Service operation either should return Messagecontract type or it should not return any value 5. Example using System. SOAP message will look as shown below. None ] public string EmpID. Suppose you want to show the all employee detail in same level. MessageHeaderArray Attribute is applicable only for Array.
EncryptAndSign ] public int Salary. So it good if you specify minimum ProtectionLevel required. If you use the MessageHeaderArray attribute of Employees. Sign ] public string Name. Sign ] public string Designation.
But the protection level of the body is determind by the highest ProtectionLevel property. We can use MessageHeaderArray attribute which will serialize the array element independently. By default if you are not specifying the protection level it takes 'EncryptAndSign'. In the below example. By default namespace is the same as the namespace of the service contract that the message is participating.
But you can control the order. Name and Namespace: Basically when we develop managed application or service.
This error should be reported to the client in proper manner. Fault Contract provides documented view for error accorded in the service to client. Let us try to understand the concept using sample example. By default when we throw any exception from service. This help as to easy identity the what error has accord.
But these exceptions handlings are technology specific. Suppose the service I consumed is not working in the client application. In order to support interoperability and client will also be interested only. On client side code.. Exceptions are handled using try-Catch block. WriteLine ex.. Now if you want to send exception information form service to client. I got the message that exceptions are not handled properly. Even though I have capture the exception when I run the application. Output window on the client side is show below.
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. Instance management is set of techniques WCF uses to bind client request to service instance. It is necessary because application will differ in their need for scalability. On client side. Basically there are three instance modes in WCF: Raise the exception from the service public int Add int num1.
Add ".. Testing the Fault contract". Instance mode can be configured using ServiceBehavior attribute. This Service instance will be disposed after response is sent back to client. Single ] public class MyService: This can be specified at implementing the service contract as shown below.
Service instance will be created for each client request. Let as understand the per-call instance mode using example. Add service behavior attribute to the service class and set the InstanceContextMode property to PerCall as show below. Create the service contract called IMyService and implement the interface. Following diagram represent the process of handling the request from client using Per-Call instance mode.
WriteLine "Client making call to service. WriteLine "Service Instance mode: Each time while making call to the service. Service instance will created for each request and value of static variable will be set to one.
Client side. While return back. Output is shown below. PerCall ] public class MyService: In this implementation of MyMethod operation. When the client creates new proxy to particular service instance. Following diagram represent the process of handling the request from client using Per-Session instance mode. Add service behavior attribute to the service class and set the InstanceContextMode property to PerSession as show below.
Let as understand the Per-Session instance mode using example. It is independent of all other instance. So each time request is made to the service. Service instance will be created once the proxy is created at client side. So each call to MyMethod return incremented value. PerSession ] public class MyService: Following diagram represent the process of handling the request from client using Singleton instance mode.
This singleton instance will be created when service is hosted and. Let as understand the Singleton Instance mode using example. Add service behavior attribute to the service class and set the InstanceContextMode property to Single as show below.
WriteLine "Client 1 making call to service. Service instance is created when it is hosted. WriteLine "Client 2 making call to service. So this instance will remain till host is shutdown. Basically service instance is hosted in a context.
BeforeCall] public int Add int num1. Session actually correlated the client message not to the instance. When session starts. 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.
BeforeCall 3. None 2. AfterCall 4. BeforeAndAfterCall Below code show. Followings are the list Release mode available in the ReleaseInstanceMode 1. This is designed to optimize a method such a Cleanup ReleaseInstanceMode.
By default ReleaseInstanceMode property is set to 'None'. None This property means that it will not affect the instance lifetime.
AfterCall This property means that it will deactivate the instance after call is made to the method. BeforeCall This property means that it will create new instance before a call is made to the operation.
WCF deactivates the instance and calls Dispose before the call is done. If the instance is already exist. This is designed to optimize a method such as Create ReleaseInstanceMode.
It can use data store like SQL database for maintain instance state. BeforeCall and ReleaseInstanceMode. Net 3. AfterCall Explicit Deactivate You can also explicitly deactivate instance using InstanceContext object as shown below.
This has combined effect of using ReleaseInstanceMode. It means that durable services have the capability to restore their own state when they are recycled. This is means that it will create new instance of object before a call and deactivates the instance after call. It is new feature in.
Service will send the instanceID to the client. It takes 'CanCreateInstance' and 'CompletesInstance' property to mention on which operation instance state has to be saved and destroyed. Calling this operation results in creating the serialization and inserting it into the datastore. If the service is shut down or client closes the proxy.
Calling this operation results in deleting the persisted instance from the datastore. Even when client is shut down. So when ever client opening the proxy. This serialized instance xml and key will be saved in the database. But in case of Durable service it is still maintained. When Durable service is created with database as data store. You might think that we can also maintain session using WCF sessions.
When a client make a request to the service. Create interface and decorate with Service and Operation contract. Let us understand more about the durable service by creating Simple Calculator service which persist the instance state in SQL server database.
You need to add [Serializable] And [DurableService ] attribute to the service implementation. Select the 'WCF Service' as shown below. Before configuring the database information in the durable service. In this implementation. Microsoft provides inbuilt sqlPersistance provider. In order to support durable service. To set up the database environment. Create the console client application and name it as DurableServiceClient Step 7: Retrieve and set the context at the client side.
Create the Helper class called it as Helper. This helper class is used to Store. Copy and paste the below code to your helper file. SetContext ctx. Serialize fs.
Delete TokenContextFileName. When I call the Subtract and Multiply operation. SaveContext client. Add SetContext client. In the main method. Call to this method will add instance state to the database. Subtract 2. Multiply 5. Now I have closed the proxy and creating new proxy instance. I was creating the proxy for the service and calling the Add operation.
Output of the client application. Serialized XML instance state save in the database is shown below. Attribute maxConcurrentCalls Description Limits the total number of calls that can currently be in progress across all service instances. Performance of the WCF service can be improved by creating proper instance.
The default is Throttling WCF throttling provides some properties that you can use to limit how many instances or sessions are created at the application level. A positive integer that limits the number of sessions a ServiceHost object can accept. 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. 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. If service doesn't respond to the service within receiveTimeout, client will receive TimeOutException. 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. One-way operation can be enabled by setting IsOneWay property to true in Operation contract attribute.
Client will be blocked until operation completes. Suppose If you want to make use of One-way operation in Sessionful service. It will be good practice.
This operation should not return any value. In the below example you can find the decalration of the callback contract and it is configured in the ServiceContract attribute. In which. Defining and configuring a callback contract Callback service can be enabled by using CallbackContract property in the ServiceContract attribute. Callback Service Till now we have seen that the all clients will call the service to get the things done.
In the presence of transport session. Client will not be able to make new call using same proxy instance. So all these binding will be used for callback operation.
But WCF also provides the service to call the client. The client must use a proxy that will set up the bidirectional communication and pass the callback endpoint reference to the service. 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. So client has to expose a callback endpoint to the service to call.
Add System. ServiceModel reference to the project Step 3: Create the Callback and Service contract as shown below. Implementation of the Callback contract will be done on the client side. You need to mention CallbackContract property in theServiceContract attribute.
The following code shows the callback method invocation. Service can call the client side callback method using reference e to the client side callback instance. Using that instance we are calling the OnCallback method from client side.
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. Multiple ] public class MyService: If you are calling the Callback method inside the service method. This is because when a client made a call to the service. This application is used to self-host the WCF service.
Service will try to access the lock channel. So you can set ConcurrencyMode to Multiple or Reentent so it will release the lock silently. If you are not using ConcurrencyMode to Multiple or Reentent. Use Duplex binding to support Callback operation. Press key to stop the service.
This is the client application which contain Callback implementation.
Run the host application Step 9: Create the contractor which will accept InstanceContext as parameter. ServiceModel and CallbackService as reference to the project Step Create the proxy class as shown below. Use DuplexClientBase to create the proxy. An event may result from a direct client call. The service firing the event is called the publisher.
WriteLine "Callback method is called from client side. In the output. Create the implementation for Callback Contract class MyCallback: Run the client application. Publisher will be blocked. It will not affect the client.
Subscriber can be executed in any manner. Net delegates to manage the list of subscribers. These make publishers to put in wait state. Let us consider the scenario in which you what to publish large volume of event. It may lead Publisher event not to reach other subscriber. Since service has to communicate to the client. Here we are using one operation to subscribe the event and another for firing the event. PerCall ] public class MyPublisher: DoSomethingAndFireEvent operation will fire the event as shown.
I am using Operationcontext to get the reference to the client instance and Subscription method is added as event handler to the service event.
Implementation of the Service Contract is shown below. This application will be used to self-host the service. In the Subscription operation. ServiceModel and WcfEventService as reference to the project. WriteLine "Host is running.. This application will act a client which is used to subscribe the event from service. Run the host application as shown below. Create the console application using visual studio and name it as WcfEventServiceClient as shown below.
Implementation of IMyEvents at client side is shown below. This method will be called when service publish the event. This is true whether it is the client sending a message to the service or the service returning a message to the client. Transfer mode In our normal day today life. If data transfer is taking place through WCF service. WriteLine "Client call operation which will fire the event". Streamed transfers can improve the scalability of a service by eliminating the requirement for large memory buffers.
StreamRequest In this mode of configuration. Subscriber got notification. As a result. 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.
If you want to transfer large message. Run the client application and you see the when event is fired from the service. Stream transfer When client and Service exchange message using Streaming transfer mode. In this mode of configuration. NetworkStream are derived from it. Streaming Client and Service exchange message using Streaming transfer mode. Net stream class for Streaming the message. Stream and it's subclass can be used for streaming.
Stream the data. Stream in base class for streaming. Send and accept requests in streaming mode. TransferMode property should be set according to the desired streaming mode in the bindings. Stream and MemoryStream are serializable and it will support streaming 3. FileStream is non serializable. So you can increase the message size using maxReceivedMessageSize attribute in the binding element as shown below.
Send and accept requests in buffered mode. With all of these bindings streaming is disabled by default. Transaction Resources Transactional programming requires working with a resource that is capable of participating in a transaction. While doing singe operation. Below figure gives idea about transaction. Productivity penalty has to be payee for all effort required for handcrafting the recovery logic 4.
In addition. Solution Best way to maintain system consistence and handling error-recovery challenge is to use transactions. Recovery Challenge Let us discuss more on challenge we will phased and how to recover from it.
Such resources have been around in one form or another for decades. Transaction encounters an error and rollback to Consistence State A from intermediate state. These operations might success or fail. Transaction that execute successfully and transfer the system from consistence state A to B. Transactions fail to either in commit or abort. Consider a system maintained in consistent state. It provides way to logically group single piece of work and execute them as a single unit.
WCF allows client applications to create transactions and to propagate transactions across service boundaries. We are not considering about sub operation which are failed.
Some resources support auto-enlisting. We mainly consider about the success operation. Performance will be decreased because you need to execute huge amount of code. This act is called enlisting. Because we have to recover all these state to its previous consistence state. When transaction completes. Transaction Properties Transaction can be said as pure and successful only if meets four characteristics.
Durable transactions must survive failures. In which service starts and manage the transaction. Resources participating in the transaction should be locked and it should not be access by other third party. Any network failure or machine crash also increases the complexity for managing the transaction. 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. WCF come up with distributed transaction using two way committed protocol and dedicated transaction manager. Client itself will act as service or client. If service disallows at binding level.
This enables service to participate in a client transaction and it includes multiple services in same transaction. TransactionFlow can be enabled only at the operation level not at the service level. FaultException will be thrown when client disable at its binding. Transaction Mode This article explains about the how to configure the service and client transaction mode in WCF service.
Allowed in the operation contract 3. Transaction Protocols As a developer we no need to concern about transaction protocols and transaction manager used by WCF. Set TransactionFlowOption. Basically there are three different kinds of transaction protocols used by WCF.
WCF itself will take care of what kind of transaction protocols should be used for different situation. NotAllowed in the operation contract 3. This seeing ensures that the service always has a transaction.
This setting ensures service does not use transaction 1. Mandatory in the operation contract 3. Allowed ] bool AddEmployee int id. This attribute is used to enable the service transaction when the client transaction is not available. Text; using System. Open ; Console. Combine "Files", String. IfNoneMatch]; if! NotModified; return ctx. ToBase64String Encoding. GetBytes fInfo. Concat BitConverter. CreateTextResponse statusCode. CreateStreamResponse File. OpenRead fInfo.
FullName , MimeMapping. GetMimeMapping fInfo. Eser Eser Sign up or log in Sign up using Google. Sign up using Facebook. Sign up using Email and Password. Post as a guest Name. Email Required, but never shown. Featured on Meta. Announcing the arrival of Valued Associate Cesar Manara.
The Ask Question Wizard is Live! Data science time! April and salary with experience. Related