echecs16.info Theory WCF COOKBOOK PDF

WCF COOKBOOK PDF

Tuesday, June 11, 2019 admin Comments(0)

Communication Foundation (WCF). First released as part of echecs16.info Framework in , then updated in echecs16.info Framework , the most recent version. NET Expert Programming Cookbook (English) your book. Did you know that Packt offers eBook versions of every book published, with PDF and. ePub files. □Chapter 4: Installing and Creating WCF Services. The book not only provides deep insight into the new WCF ws//04/discovery/ws-discovery. pdf. an enterprise application without transactional support is a recipe for failure.


Author:RODOLFO SEABERT
Language:English, Spanish, Japanese
Country:Gabon
Genre:Academic & Education
Pages:655
Published (Last):02.12.2015
ISBN:713-3-80803-408-7
ePub File Size:17.79 MB
PDF File Size:8.10 MB
Distribution:Free* [*Register to download]
Downloads:45073
Uploaded by: PORFIRIO

WCF stands for Windows Communication Foundation. It is a framework This tutorial explains the fundamentals of WCF and is conveniently divided into various. munication Foundation (WCF) and its architecture enabling you to build simple concepts of WCF, I recommend that you give this chapter at least a cursory. Cookbook for Developing Getting the IP address of a client consumer of a WCF service. Binding a WPF element with data from a WCF service.

Relentlessly practical, the book delivers insight, not documentation, to teach developers what they need to know to build the next generation of SOAs. After explaining the advantages of service-orientation for application design and teaching the basics of how to develop SOAs using WCF, the book shows how you can take advantage of built-in features such as service hosting, instance management, asynchronous calls, synchronization, reliability, transaction management, disconnected queued calls and security to build best in class applications. Programming WCF Services focuses on the rationale behind particular design decisions, often shedding light on poorly-documented and little-understood aspects of SOA development. Developers and architects will learn not only the "how" of WCF programming, but also relevant design guidelines, best practices, and pitfalls. Original techniques and utilities provided by the author throughout the book go well beyond anything that can be found in conventional sources. Based on experience and insight gained while taking part in the strategic design of WCF and working with the team that implemented it, Programming WCF Services provides experienced working professionals with the definitive work on WCF.

The message might be lost in transit and never reach the service. If the send operation completes successfully at the client end, it does not guarantee that the remote endpoint has received the message. In those cases where the client only wants to send information to the server side, without taking care of the execution result, we can consider defining our WCF service operation as one-way style. Create the service interface or class type and add methods into it.

The following code snippet shows the complete one-way OperationContract definition: One-way operation cannot carry a return value but can only pass input parameters to the service.

After the client sends out the service request, the client will wait until it gets the response that the request message has reached the service side. However, the response here is not the return value, but the protocol level ACK, which indicates that the request has reached the service but gives no idea of whether or how the request has been processed.

We can get further understanding on one-way operation via the following question: What is the difference between a standard void no return value operation and a one-way operation? Suppose you have the following ServiceContract implemented: Understanding this can help us to make better decisions about whether to use one-way operation or not. There's more In addition to one-way operation, there are two other message exchange patterns that are widely used in WCF services.

They are the Request-response pattern and the Duplex pattern. The Request-response pattern is very similar to the standard function call that has an input parameter and return value. In a Request-response pattern-based WCF service operation call, a message is sent and a reply is received.

The pattern consists of request-response pairs, as shown in the next figure. This pattern is like a phone conversation, where each word being spoken is a message refer to the following screenshot. If we want to add new complex data types that will be transferred in service operations in a WCF service, we need to define it as a DataContract type so as to make it friendly to the DataContractSerializer engine.

NET serialization system supports backward-compatibility on custom data types naturally. However, sometimes we also need forward-compatibility for data types used in a WCF service. Suppose that you have a service that exchanges some custom data types between clients. If one side updates the custom data type adds some fields or properties or uses a newer version, it is important to make sure that the other side without using the updated version of data can still work correctly with the updated data type instances.

Make the custom data type we will use in our service communication implement the IExtensibleDataObject interface. You can have a look at the article ServiceBehaviorAttribute. IgnoreExtensionDataObject Property for more information and is available at: After the DataContract type implements the IExtensibleDataObject interface, an ExtensionDataObject property is added; this property plays an important role in forward-compatible serialization.

And if the deserialized instance with some unknown data stored in ExtensionDataObject is serialized into the message later, DataContractSerializer will write out ExtensionDataObject into the message stream again.

However, the ExtensionDataObject property is an opaque object to developers and we do not have means to manually read the data stored in it. See also ff Altering an operation message via MessageInspector in Chapter 9. As a unified distributed communication development platform, it is quite common to support such kind of DataContract generation in WCF development. How to do it The next screenshot shows a simple sample schema that contains a simple enum and a complex data type definition: Following is the sample command on how to use the Svcutil.

For the previous example, TestDataContractSchema. NET 3. If you're familiar with ASP. You can generate a WCF client proxy and export metadata from service code. Here we just use it to generate serialization code from the given XML Schema. The DataContract we generated here includes two typical class types—a composite type and a simple enum type. In most scenarios, people will define much more complicated data types in their services, and WCF DataContractSerializer does provide enough support for mapping between an XML Schema-based contract and.

NET code-based types. First, we should make our data type ready for XMLSerializer. This can be done by adding XML serialization attributes on our data types. Also, the auto-generated service metadata will output the data type schema based on the class's XML serialization attributes.

For the User class mentioned in the previous code example, service metadata will use the schema as shown in the next screenshot to represent its XML format: By capturing the underlying SOAP message, we can find that the XML content of the serialized User object conforms to the metadata schema defined earlier, which is controlled by those XML serialization attributes applied on the user class refer to the next screenshot: However, this only covers the data members variables and parameters used in operation serialized in the underlying SOAP message.

Sometimes we also need to control the structure and format of the entire SOAP message. WCF introduces a MessageContract concept, which helps service developers to model the structure and format of the entire message of a given service operation.

Define a custom data type that represents the entire SOAP message body content. The following code demonstrates a sample MessageContract pair—one is for operation request and the other for operation response. The serialization of such types still follows the rules for normal DataContract types. Also, it is important that operations which use MessageContract to control the SOAP envelope only have a single input parameter and return value. This is because only that input parameter will be serialized as the entire SOAP request body, and the return value will be serialized as the entire SOAP response body.

Each sub element under the optional Header is called a SoapHeader, which plays a similar role as the other headers, uses a certain network protocol's transmit package. For some user scenarios, we will also need to add a custom SoapHeader into the WCF service message so as to exchange additional information mostly for communication purposes.

We need to define a custom type, which represents the SoapHeader that will be serialized in the service message. Here is a sample DataContract type that represents a custom header used for custom authentication: Next, we can apply the custom Header type into our service operation's MessageContract.

Also, since the header is added in MessageContract at design-time, the WCF auto-generated metadata will include the SoapHeader information, as shown in the following screenshot: If you use Visual Studio or Svcutil. Thus, when invoking the service operation, we can simply pass SoapHeader data as the operation parameter. The following code demonstrates how the auto-generated service proxy invokes the operation with the custom SoapHeader assigned.

TestServiceClient ; TestProxy. WCF supports various means to add custom SoapHeader a into service messages. This recipe demonstrates using a custom type and MessageContract to add a custom SoapHeader statically. In addition to this, we can also use code to programmatically add SoapHeaders into service messages. For WCF service operations, exceptions are returned to the client through two steps: However, sometimes we want to encapsulate the raw exception information or return some user-friendly error to the client side.

FaultException is a new exception type that uses Generic to help WCF service encapsulate various kinds of custom error data objects in a unified way. FaultContract is used to formally specify the type of FaultException that will be returned from the target WCF service operation, so that the client consumers can properly handle and parse it. First, create the custom error type that will be returned to the service client as exception information.

The custom error type is defined as a standard DataContract type. Then, apply the custom error type to the service operation which will return this custom error type through a FaultContractAttribute. The following code shows a sample custom error type and the service operation that applies it: The FaultContractAttribute applied on the service operation will make the runtime generate corresponding metadata entries in the WSDL document as shown in the next screenshot.

Thus, the generated client proxy knows how to handle this custom error type. When invoking the operation, we can add code to handle the specific FaultException and get user-friendly error information from the Exception. Detail property. WriteLine "Error: Since the custom error type used by FaultContract supports any valid DataContract type, we can define various kinds of custom exception data content from simple primitive types to complex nested classes.

Service endpoints consist of ABC and a set of behaviors. What is ABC? Behaviors also play an important role in WCF. By using behaviors, we can gain further manipulation over the WCF service at service or endpoint level. Then, we will use two built-in bindings NetMsmqBinding and WSDualHttpBinding to demonstrate how to build a two-way communication and build a Publish-Subscribe pattern service through system bindings.

The fourth recipe shows how WCF allows a single service to expose multiple endpoints layered on heterogeneous transport and message settings. The last three recipes come from some common and tricky scenarios in service endpoint customization. These services often use very simple and typical endpoint and binding definitions. However, every time we need to set up such a service, we have to define the same endpoint and binding settings again and again, which really adds much duplicated work.

Fortunately, WCF 4. The steps for using a default endpoint are quite straightforward: Create a new Console Application project in Visual Studio targeting. NET Framework 4. Add the ServiceContract in the service project and implementation types we need in the service project. We can use any valid ServiceContract and its corresponding implementation class here. For example, the following IHelloService service containing a single SayHello operation is used in our sample service application here: Add service configuration entries for the service type defined in step 2 in the app.

We do not need to define any endpoint and binding configuration here. The following screenshot demonstrates the necessary service configuration elements: Start a ServiceHost and specify the service type we want to run see the following code: Open ; Console.

The magic behind scene is the Default Endpoints feature. When we start a WCF 4. The default endpoints will choose the proper binding based on its endpoint address the URL scheme by looking up a protocolMapping list predefined in the system configuration store within the.

NET 4 Machine. The following screenshot shows the protocolMapping list: For our previous example, since the endpoint address uses the HTTP scheme derives from the baseAddress , the runtime will choose the BasicHttpBinding according to the protocolMapping list.

By using the DumpEndpoint function, we can confirm that Default Endpoint with BasicHttpBinding has been correctly set up in the previous case refer to the next screenshot. Open ; DumpEndpoint host. Endpoints ; ……………. Address, sep. Name, sep. Contract ; Console. WriteLine be. For example, we define the following anonymous binding configuration, which does not have an explicit name. Any endpoint that uses BasicHttpBinding will adopt the setting in this anonymous binding configuration.

And the Microsoft. NET framework has also provided managed programming interfaces for developers to develop distributed applications based on MSMQ. However, it is still a bit complicated and time consuming for developers to build a complete distributed service through the raw or encapsulated MSMQ programming interface. As the new unified communication development platform on Windows, WCF provides more convenient means for developing a distributed service over the underlying MSMQ component.

NET Framework System. Messaging namespace that encapsulates the raw MSMQ programming interfaces visit http: To make the WCF client and service perform two-way communication over MSMQ, we need to set up two MSMQ-based endpoints—one for the service to receive client requests and the other for the client to get responses.

The following code snippet shows the sample ServiceContract one for the service and another for the client: Create the MSMQ queues on the client and server machines. There are two means for us to create the queues.

One way is to use the MMC snap-in. There are various ways to start up this snap-in, but the easiest is to open the Windows Computer Management utility in Administrative Tools, expand the Services and Applications section of the tree view on the left, and select the Message Queuing node.

This is also a great way to verify that MSMQ is installed on a particular machine. Another way is to create the queue programmatically, is as shown in the following code. In the sample service here, we will create the MSMQ queues in code: Exists qName MessageQueue.

After the message queues have been created, we can start configuring the service and client endpoints and map them to the underlying MSMQ queues. For the receiver side, the service endpoint should use NetMsmqBinding and set the address in net. The following screenshot shows a sample service endpoint configuration: The private in the endpoint address indicates that the MSMQ queue is a private queue and NotificationReceiver is the queue name.

The sender side will need to configure the client endpoint that uses the same configuration as the service endpoint at the receiver side, which is done as follows: How it works Messaging programming interfaces. However, in some cases, if you need to establish communication between raw MSMQ application and WCF-based application, there is another built-in binding called MsmqIntegrationBinding, which is suitable for such scenarios.

You can have a look at the article How to: In WCF service development, the Publish-Subscribe pattern will also help in those scenarios where the service application will expose data to certain groups of clients that are interested in the service and the data is provided to clients as a push model actively instead of polling by the client.

This recipe will demonstrate how to implement the Publish-Subscribe pattern in a WCF service through dual binding. Getting ready The Publish-Subscribe pattern is widely adopted in various application development scenarios and there are many different kinds of descriptions for this pattern. Refer to the following links for more information: The first thing to do is to design a ServiceContract that supports Publish- Subscribe pattern. The following IPublicBillboard interface represents a sample contract for publishing some announcements to client applications that are interested in the service.

Also, a session has been enabled here so that the service can conveniently identify client callback channels through their sessionId. When implementing the ServiceContract, Subscribe will cache the callback channel via the client sessionId so that it can notify the client later by invoking the callback channel. Single ] public class PublicBillboard: Add sessionId, OperationContext. If there is already a callback interface with the same sessionId cached, the code will remove the existing one first.

In the service endpoint configuration, it is important to select a duplex binding. At the client side, we need to provide a type that implements the callback interface and supply this type instance when initializing the service proxy, which is done as follows: Form, BillboardProxy. Subscribe ; btnSubmit. In the end, the service operation can selectively notify some or all of the clients proactively refer to the Announce operation shown as follows: GetAnnouncement string.

Single, so that all the clients will share the same service instance. Enabling the session makes the service be able to differentiate clients by their sessionId. The following screenshot shows the service console, which prints out all new announcements received from the client. At the client side, the callback function simply updates the Forum UI and prints the new announcement in the textbox control. Both the service callback operations are marked as one-way style.

If we need to expose it via another different transport layer, we will probably have to add additional code to implement the new endpoint. The WCF programming model separates the service implementation and underlying transport layer so that we can conveniently expose a single service implementation via multiple heterogeneous endpoints with different a transport layer and binding configuration. First, we make sure our ServiceContract is ready for various endpoint bindings we want to use to expose it.

The following sample contract is ready for most built-in bindings: The following code is the implementation of the CounterService: Single ] public class CounterService: Finally, we need to add the various endpoints and bindings in the service hosting code. None ; host. None, false ; host. None,false ; 41 www. Client applications can use any of the exposed endpoints to consume the service.

The sample client uses ChannelFactory to construct the client channel to consume the service: The following code shows a sample operation that is ready for exchanging POX-style messages. Message class as the only input parameter and return value. For the service endpoint, we will need to apply a custom binding on it.

The following screenshot shows the complete definition of our custom binding: After the service endpoint has been configured, we can start the service and consume it with POX-enabled clients. For the service side, we can directly get the XML content from the input Message parameter.

When returning the result, we also need to construct a Message instance and assign it the proper HTTP properties, if necessary. The following code demonstrates a simple message processing scenario: WriteLine reqMsg. CreateMessage MessageVersion. None, string.

SayHello reqMsg ; Console. WriteLine repMsg. Also, the System. Message type allows us to freely construct arbitrary XML-style messages for service requests and responses. However, some non-WCF service platforms may not expose this header. When working with this kind of service client or service, we will need to prevent the WCF message engine from generating the timestamp header.

Using WSHttpBinding as an example, we can create a customized binding that derives most of the setting of the built-in WSHttpBinding but suppresses the timestamp header generation. The following code snippet demonstrates how to create the CustomBinding and configure the certain binding element to disable timestamp header generation.

It then sets the IncludeTimestamp property to false. Finally, we can apply this CustomBinding to any endpoint that needs to suppress the timestamp header. Since the timestamp header is a security feature that performs a message-replaying check, the WCF programming model exposes this setting through the SecurityBindingElement type. However, only setting the SecurityBindingElement. By comparing the underlying SOAP messages, we can find the obvious difference in the SoapHeader section before and after we disable the timestamp header generation.

The next screenshot is a SOAP message captured before removing the timestamp header: The following screenshot is for a SOAP message captured after removing the timestamp header: SoapHeader has a mustUnderstand attribute that indicates to the target endpoint or intermediate message processor whether the SoapHeader must be processed. By default, a WCF endpoint will perform validation on all the SoapHeaders within incoming messages, and if there are any unknown SoapHeaders not predefined which have a mustUnderstand attribute as 1 or true , a validation exception will be raised by the runtime.

However, sometimes it is useful to suppress this validation so that the WCF service or client proxy can gracefully handle unknown SoapHeaders that are dynamically added.

Getting ready If you are not familiar with SoapHeaders and the mustUnderstand attribute, or how to set this attribute via the WCF programming model, you can take a look at the following references first: MustUnderstand Property http: The steps are as follows: First, we need to create a MustUnderstandBehavior type instance and set its ValidateMustUnderstand property to false which can be done in the type constructor. Endpoints collection to find the wanted endpoint.

For the client proxy, we can directly use [ClientProxy]. Endpoint to get the endpoint instance. The following code shows the complete steps for applying MustUnderstandBehavior in service hosting code: But, we can still use code to access them from OperationContext, as follows: Count ; foreach var header in OperationContext. Name, header. In this recipe, we demonstrated how to inject the MustUnderstandBehavior for a self-hosting scenario. In such cases, we can use a custom ServiceHostFactory class to add the behavior injecting code logic.

Another great feature is letting multiple endpoints listen over the same physical transport address. For example, you want to host a WCF service that has multiple endpoints exposed.

Programming WCF Services (eBook, PDF)

The first thing we need to do is configure the service endpoints. We will still specify different values for the address attribute of the two endpoints. However, we will use a special attribute named listenUri to supply the physical address identical for both endpoints.

The following screenshot shows the usage of both attributes: It is also important to configure the client endpoint so that the client proxy or ChannelFactory can correctly locate the service endpoint. You can use the ChannelFactory. Behaviors collection to inject the behavior in code, shown as follows: None ; SharedAddressService.

Generally, we will use the address attribute to specify the URL on which the endpoint will listen. The listenUri, on the contrary, represents the physical transport address the service endpoint listens on. Also, for the endpoints that share the same physical address, they will share the same service dispatcher and channel stack. Then, how does the WCF runtime differentiate these operation requests when there are multiple endpoints listening on a single physical address?

The answer is WCF runtime will try to resolve the request target by the combination of two parts: See also ff Creating a multiple-endpoint service 53 www. After developers complete the service development, we will need to deploy the service so as to make it available to all the client consumers. In the real world, there are various service deployment scenarios available, which will result in different deployment and configuration requirements on the service configuration or the hosting environment.

As an enhanced service development platform, WCF provides rich, built-in support on service hosting and configuration that can fulfill most of the existing deployment demands and requirements. For example, the most popular IIS hosting approach can provide high availability and stable service for local intranet or public internet-based deployment cases. The Windows service-hosting approach makes WCF service hosting easier to integrate with existing background scheduled tasks, and the self-hosting approach provides the most flexibility and customization points for service deployment in a production environment.

This is followed by two customized service-hosting cases—including a custom ServiceHostFactory and a dedicated singleton-instance hosting. Hosting a service in a console application When creating a simple demo program for.

NET framework, we will probably choose a console application. At the same, when talking about WCF service hosting, the console-hosting scenario is the most convenient one, which is especially handy and useful when we want to do some quick demo or testing on some WCF functionality.

Create a. Visual Studio provides various project templates for creating a. NET framework-based application. For our sample console-hosting service here, we will choose the Console Application project type from the Visual Studio New Project wizard. Add a new WCF service into the project.

Programming WCF Services (pdf)

Add code into the Main function to start up the WCF service. The following code shows the typical Main function that starts up a WCF service in a console application: WriteLine "press any key to stop service host The following code shows the sample ServiceContract and implementation class used in this recipe. In addition to the Contract and service type, the IDE will also insert a default configuration setting for the endpoint that can be exposed through the service.

The following screenshot shows the sample service configuration section that contains a single endpoint, which uses WSHttpBinding. With the code and configuration entries as defined previously, we can start our service host by supplying the service type in the constructor of the ServiceHost class.

Applications hosted via Windows Service can be running under a specific user account and can choose the startup mode manually or automatically. As a popular service-application-hosting scenario, it is also quite common to deploy a WCF service as a Windows Service. In this recipe, we will use a typical. Let's go through the detailed steps: Create a Windows Service project. When creating the project, we simply choose the Windows Service project type.

The following screenshot shows how we can select the Windows Service project type in the Visual Studio New Project wizard. Add a new WCF service item. The steps for creating a WCF service are the same as what we've discussed in the Hosting a service in console application recipe.

Add service hosting code into the service startup and shutdown event. As for the service-hosting code in the Windows Service, we need to put it in the correct place, since the. The following code shows how the WCF service startup and shutdown code is defined: Add an installer for the Windows Service. However, we still need to add another component—the installer class for deploying the Windows Service into the Windows Service collection on the target operating system. The following screenshot shows the context menu item for creating the installer class for the Windows Service.

We can specify many deployment parameters for the Windows Service in the Property panel of the two classes. The following screenshot shows the properties of the sample serviceProcessInstaller1 class. As with the screenshots displayed, Visual Studio will use standard Properties windows for displaying and configuring the individual properties of the Windows Service classes. Install the Windows Service through Installutil.

The last step is to install the Windows Service we have created after building the project into the operating system. This can be done by using the Installutil. NET framework. You can directly execute the Installutil. NET framework folder such as C: The following statements show the complete commands for installing and uninstalling a.

Install the Windows Service: Install Util. Therefore, they are the best places for us to put the WCF service-hosting code. Sometimes, we may need to access some remote or protected resource in our Windows Service host program. In such cases, it is important to specify a proper service account, either at development time or in the Windows Service Configuration Manager.

The following screenshot shows the service list, which contains the installed sample Windows Service in Windows Service Configuration Manager. NET provides a powerful platform for developing web applications over the.

An ASP. NET web pages in the same web application side by side without any particular effort. NET runtime features or state objects are not available to WCF service code even if they are within the same web application.

Those limited features include: Then, how can we make such features accessible to a WCF service again? NET Compatibility Mode, which can help resolve the problem. This feature is by default disabled; we will show you how to enable this feature so that the WCF service continues to enjoy the ASP. NET runtime in this recipe. The first thing we need to do is get an existing ASP. For our sample case, we will use an empty ASP. The following screenshot shows the web application structure in Visual Studio Solution Explorer.

The EchoService has a very simple ServiceContract, which contains a single Echo operation to return some data of type String refer to the following code snippet. Now we have the ASP. NET-specific runtime objects yet.

What we need to do is apply ASP. To enable ASP. The following screenshot shows the configuration fragment with ASP.

NET Compatibility Mode enabled. On the service implementation class of the WCF service, we need to apply the System. The following code snippet shows the implementation class of the sample EchoService, which has applied the proper AspNetCompatibilityRequirements setting: Allowed ] public class EchoService: Having all the services and applications configured appropriately, we can now start enjoying the ASP. The following code snippet shows the sample Echo operation code, which collects several runtime properties from the ASP.

NET request context and returns them to the service caller: RawUrl; return string. NET context properties returned, as shown in the following screenshot: NET Compatibility Mode. In the default mode, the ASP. BeginRequest one of the interception points of ASP. When ASP. NET-specific context data become available again. For more detailed information about ASP. NET Compatibility Mode http: After installing the activation components, we need to enable a certain type of binding in a particular IIS site and application virtual directory, in which our WCF service will deploy.

Therefore, we will add a net. Tcp binding into the IIS default site. The next screenshot shows how we can launch the Edit Bindings… configuration wizard against a particular IIS site in the manager tool.

Also, we need to enable the binding protocol at individual virtual directory level refer to the following screenshot. This will give developers and administrators more flexible granularity of control over multiple applications deployed in the same IIS site.

Create a WCF service in the web application. The following screenshot shows the detailed endpoint configuration. In the previous sample service, we add a MexTcpBinding-based endpoint in addition to the main service endpoint. This MexTcpBinding endpoint is used for a client application to acquire the metadata of the service.

If you use the Visual Studio Add ServiceReference command to generate the proxy, you can directly type the metadata address in the metadata browser's address bar. So, developers do not need to explicitly create and initiate the ServiceHost like we do in a self-hosting scenario. Sometimes, however, we still need to customize the service or endpoints through code. This recipe will use a custom metadata configuration case to demonstrate how to programmatically adjust service behaviors in an IIS-hosting scenario.

Create the WCF service in the hosting web application. The resulting WCF service is represented by a. Define a custom ServiceHostFactory class for customizing the metadata configuration. As what we want to do is customize the metadata configuration, we should override the CreateServiceHost method and inject our custom code logic there. The following code snippet shows a sample implementation of the custom ServiceHostFactory.

Apply the custom ServiceHostFactory to the target service. In order to apply our custom ServiceHostFactory, we can use the Factory attribute on the ServiceHost directive in the. This Activation module is added in the machine. So, this activation model provides the opportunity for developers to inject their own code logic into the ServiceHost by supplying a custom ServiceHostFactory type.

Also, if you do not explicitly specify the ServiceHostFactory, the runtime will use a default factory to create the ServiceHost. This makes hosting a WCF service quite simple and convenient; the service developers do not need to know when and how the runtime creates the service instance.

However, in some cases, it is useful and necessary to let the developer control when and how the service instance is created. This pattern can help design a class that will expose one and only one instance of the class over the entire lifecycle of the class or application context. This is very useful in cases where we want to restrict the number of instances of a given class or component.

In this recipe, we will use a sample Voting service to demonstrate how to supply a dedicated service instance for a WCF service hosting in singleton mode. The hosting environment can manipulate and communicate with the service instance directly throughout the hosting lifetime.

Define the ServiceContract and implement the service with special properties. The sample voting service contains a single operation Vote. This is used by the client to submit a vote request for a certain item. The following code shows the complete ServiceContract and implementation of the VotingService: Single ] public class VotingService: This function is not a WCF service operation and is used for the service hosting program to query the current voting status list.

Create the service instance and supply it to the ServiceHost. The next step, also the most important step, is to tell the WCF ServiceHost to use the service instance created by our code. For the sample VotingService, we simply create the service instance and assign it to the ServiceHost in the constructor as shown in the following code: WriteLine "name: Key, pair.

WCF allows developers to control how the service instance objects are created, and the relation between service instance and client channel through the ServiceContractAttribute.

InstanceContext property. The following table shows every possible InstanceContextMode along with its description. PerCall A new InstanceContext object is created prior to, and recycled subsequent to, each call.

If the channel does not create a session, this value behaves as if it were PerCall. Single Only one InstanceContext object is used for all incoming calls and is not recycled subsequent to the calls. If a service object does not exist, one is created. Note that for singleton lifetime behavior for example, if the host application calls the ServiceHost constructor and passes an object to use as the service , the service class must set InstanceContextMode to InstanceContextMode. Single, or an exception is thrown when the service host is opened.

For our sample service here, we use the Singleton mode so as to make our WCF service expose a single service instance object to process client requests. However, only applying the InstanceContextMode. Singleton is not enough, since we also need to control the creation of the service instance object. Therefore, we also add code to manually create the service instance object and supply it into the ServiceHost via the constructor.

By supplying a dedicated service instance object, we can conveniently communicate with the service instance in the hosting code. For example, in the above sample voting service, the console service host can query the voting count at any time by accessing the public methods for properties on the service instance type.

For more information about the Singleton design pattern, you can refer to the following page: With the WCF coming in. NET Framework 3. Creating the WCF service.

Free PDF eBook: Learn WCF and LINQ to Entities in Visual Studio | PACKT Books

The service configuration of the sample service is shown in the following screenshot. The following code shows a very simple VirtualPathProvider implementation that will do the job: That is a virtual path ending with ". EndsWith ". The following code shows this HttpModule used in our sample service: We will create a sub directory so as to make the structure look more clear.

The complete path of the directory in which we deploy our WCF service is C: There are two things that we need to add into the deploying directory—one is the. The assembly name is also referenced in the.

These preparations include: The following screenshot shows the sample web. This is necessary, since the WSS 3. And the most common means to consume a WCF service is using a.

NET Framework-based client proxy class. There are also different ways to create such kinds of client proxy types using Visual Studio IDE or the. Also, WCF proxy generation relies highly on the service metadata. Service metadata includes descriptions of the service endpoints, bindings, contracts, operations, and messages.

You can use service metadata for a variety of purposes, including automatically generating a client for consuming the service, implementing the service description, and dynamically updating the binding for a client. Metadata can be exposed to a client through many different ways, including using a HTTP-based static metadata endpoint, using dynamic metadata discovery, using custom metadata generation, and so on.

In this chapter, we will go through eight recipes focusing on WCF client proxy generation and metadata publishing and discovery. The first four recipes demonstrate the typical service proxy generation scenarios and how to apply some special configuration options on the generated service proxy components. The fifth, Building an ad-hoc auto-discoverable service, and sixth, Using managed ServiceDiscovery, recipes show the new auto-discovery feature of WCF 4. The last two recipes focus on the customization scenarios of WCF service metadata and client proxy generation.

Creating a typed service client WCF services can be consumed by a client through various means. If our client application is also built upon. This recipe will show you how to create a typed service proxy through WCF service metadata. We will go through the typed service proxy generation steps via a simple WCF service that is hosted at the address http: Following are the detailed steps: Get the WSDL metadata of the targeting service.

For our sample service, we can directly get the service metadata at the SVC endpoint file from the previous address. We can simply do it through the Add Service Reference command in the project context menu item, in the Solution Explorer pane. Create the proxy class and review the generated components. The main class in the proxy components is the ServiceClient type highlighted in the previous screenshot. If we look into the detailed code of this class, we will find that it is derived from the System.

The following code snippet shows the entire Service1Client class used in our sample project: DebuggerStepThroughAttribute ] [System.

GeneratedCodeAttribute "System. ServiceModel", "3. EndpointAddress remoteAddress: Binding binding, System. The following command shows the simplest syntax for creating a WCF typed service proxy from a given metadata location: NET object into raw XML or binary format at the server side and deserialize it into an object of the mapping type at the client side.

We will usually use an array or collection-like type as parameter or return value type in a service operation. When calling such operations, the client-side proxy will need to define the corresponding types that will match the parameters or return values. Here we will demonstrate how to specify the collection parameter type when generating the service proxy in Visual Studio.

The detailed steps are as follows: When using the Add Service Reference wizard, we can click on the Advanced button to launch the advanced configuration panel, which contains those additional settings that control service proxy generation. Choose the expected type from the given Collection type drop-down list.

Cookbook pdf wcf

We can choose the collection types from a combo box that contains all the available types. List, Generic. LinkedList, and so on. The following screenshot shows the Collection type selection drop-down list. After specifying a custom collection type, the Add Service Reference wizard will generate the proxy class that uses the selected type to represent any collection-based parameters or return values in service operations. For example, suppose the target service has the following ServiceContract: As mentioned in the Create a typed service client recipe, we can use Svcutil.

When using Svcutil. For example: When generating a WCF client proxy through the Visual Studio Add Service Reference context menu item, it will help to generate some skeleton types that have the same serialization format with the custom types used in the server-side service at the client- side instead of directly using the server-side types. However, sometimes we will need to reuse the existing types used at the server side instead of using the auto-generated skeleton types.

The first thing we need to do is gather all those custom types used in our WCF service operation in one or several class library assemblies. This can help separate them from other service definition-related code and make them more convenient to be reused. For our sample WCF service, we will use a single assembly with the custom type defined as follows: SearchResult type in the service operation as shown in the following code: To make the custom types available to the client application that needs to consume the WCF service, we need to reference the assembly first, which can be done via Add Reference in the Visual Studio Solution Explorer pane.

In the previous screenshot, the ClassLib assembly is the shared class library, contains the custom types that need to be shared between the WCF service and client projects. Specify the assembly for looking up reusable types when generating the WCF service proxy in Visual Studio.

As the previous screenshot shows, the advance options in Visual Studio's Add Service Reference UI has provided a Reuse types in referenced assemblies option that can let developers choose the assembly for probing reusable types between the server-side service and the client proxy.

Pdf wcf cookbook

After the service proxy is generated, we can open the main proxy class code to verify that the types defined in the centralized assembly have been used in the auto- generated service proxy as shown in the following code. The type probing is based on the WCF service operation's method signature such as parameter type and return value type or other types marked as knowable types.

Also, such kinds of assemblies being probed must be referenced by both client and service projects as shown in the previous figure. By using the type reusing functionality, developers can avoid generating redundant and duplicated skeleton types in client projects that will consume WCF service projects using custom types.

However, sometimes we will need to do some customization or adjustment on the generated proxy classes, such as add some custom methods, manipulate some of the method signature, or add additional member properties in the proxy class. In this recipe, we will cover the way to manually modify the auto-generated WCF service proxy class in a Visual Studio project.

In this recipe, we will look at the steps to customize an auto-generated WCF service proxy in Visual Studio by adding custom code. This is quite straightforward and we can just refer to the steps mentioned in the Creating a typed service client recipe.

After generating the service proxy and expanding the service reference node in Visual Studio, it will show you the view shown in the following screenshot: Also, this time we will need to inspect the main class of the service proxy in the Reference. The following code snippet shows the main class definition in our sample WCF service proxy: Get the main proxy class and create a partial class file to extend the main proxy class.

The next step is to add our customization code, which will extend the auto-generated service proxy class. To do this, we need to add a partial class file into the project and define a partial class with a name identical to the auto-generated main service proxy class shown previously.

The following code fragment shows the partial class definition in our sample client project: Parse xelm. Now that the default generated service proxy class has been extended via our partial class definition, we can use the custom member functions defined in the partial class on the proxy instance. As the following code snippet shows, the code for invoking the service operations through a service proxy instance remains the same as before: Service1Client ; Console.

WriteLine client. GetIntData 33 ; 95 www. Here we used a partial class file to extend the WCF auto-generated service proxy type. The partial class Service1Client is identical to the auto-generated service proxy type and has a custom method called GetIntData. The GetIntData method will call the auto-generated GetData service operation and do some post-processing on the return value before returning it to the caller.

We can also add other custom methods or properties into the partial class so as to further extend the auto-generated proxy class. When using the main proxy class to consume the WCF service, we can call any of our custom-defined members instead of the auto-generated operations so as to include our custom code logic seamlessly in the client-side code.

The advantage of this approach is that our custom code will be combined with the auto-generated proxy code and compiled together, which makes the proxy caller able to use our extended proxy members properties or functions seamlessly.

Another highlight is that by using a partial class file, the custom code to extend the proxy class will not be discarded when you update the WCF proxy via the Update Service Reference context menu item in Visual Studio. In such cases, it is quite important to let the service client be able to dynamically discover the service location.

Fortunately, WCF 4 provides a new feature called service discovery, which can properly address this issue. The discovery feature enables services to be discoverable at runtime in an interoperable way using the WS-Discovery protocol. WCF services can announce their availability to the network using a multicast message or to a discovery proxy server. Client applications can search the network or a discovery proxy server to find services that meet a set of criteria.

In this recipe, we will cover how to build a simple and powerful ad-hoc auto-discoverable service through the service discovery feature. The service discovery feature in WCF 4 is based on this specification. Our sample service will use the WCF 4 built-in discovery endpoint to demonstrate the steps for creating a WCF service with ad-hoc discoverable ability: Enable the auto-discovery feature on the WCF service.

The first thing to do is make the WCF service application auto-discovery ready. For ad-hoc auto-discoverable services, we can simply add an udpDiscoveryEndpoint into the service's endpoint collection. The following screenshot shows the complete service configuration with discovery endpoint and corresponding behaviors defined.

Add dynamic service-discovering code in the client application. However, instead of using a static endpoint address, we can use the DiscoveryClient class to locate the service endpoint address programmatically. The following code demonstrates how to dynamically find an auto-discoverable service and assign the dynamic EndpointAddress to client a proxy: Address; Console.

CalcServiceClient ; client. Also, like the service-side, the client application also needs to configure the udpDiscoveryEndpoint entry.

The ad-hoc auto-discovery feature in WCF 4. As used in the sample service, by applying udpDiscoveryEndpoint in the service, the runtime will start a UDP server for listening to any discovery requests from client applications.

Cyber Security. Full Stack. Game Dev. Git and Github. Technology news, analysis, and tutorials from Packt. Stay up to date with what's important in software engineering today. Become a contributor. Go to Subscription. You don't have anything in your cart right now. Want to learn both? You would normally have to dig through huge reference tomes - so wouldn't it be best to get exactly what you need in one simple place? Sign up to our emails for regular updates, bespoke offers, exclusive discounts and great free content.

Log in. My Account. Log in to your account. Not yet a member? Register for an account and access leading-edge content on emerging technologies. Register now. Packt Logo. My Collection. Deal of the Day Understand the fundamentals of C programming and get started with coding from ground up in an engaging and practical manner. Sign up here to get these deals straight to your inbox. Find Ebooks and Videos by Technology Android. Packt Hub Technology news, analysis, and tutorials from Packt.

Insights Tutorials.