Extensibility – Inspecting WCF Messages

      blocks -Rameshkartik

 

  • Introduction on Extensibility
  • Service Stack
  • Interfaces
  • Configuring Message Inspectors
  • Output
  • Summary

 

Introduction on Extensibility

Extensibility = Extend the functionality.

Guys, before we jump into WCF Extensibility, I would like to give you, a brief on Extensibility which is nothing but a software design principle to extend the software functionality, with a minimal impact or no impact into the existing functionalities. In simpler words, Feature X would not affect by the extended Feature Y.

WCF pipeline is easily extendable allowing the developer to extend in various locations in the Client and the Service to implement the custom logic if needed. You can extend your own binding, channel and behavior. Let us discuss this in detail.

WCF Service Stack

I would suggest you to read my old article WCF Runtime Architecture and SOA implementation to understand the WCF pipeline architecture completely before you jump into Extensibility. In the snapshot given below, you can understand the processes involved in sending the data from the client to the Server and vice versa.

wcf-runtime-architecture

The data travels from the client application to the stream by converting calls to WCF message and it converts the messages into calls and objects on the Server side. There are five Extensible Endpoints on the Server side.

  1. Message Inspection
  2. Operation Selector
  3. Message Formatting (De-Serialization)
  4. Parameter Inspection and
  5. Operation Invoker

WCF has multiple extensible points which allow you to modify runtime behaviour.You can ask me a question like, What is the usage of extensible points? Why should I modify the runtime behaviour using the extensible points? The following snapshot answers these questions

extensibility

Figure 2.0 WCF Extensible Points

From the Message Inspector, you can find that

  • How much data exchanged between the Client and the Server?
  • What is the Size of the Message?
  • How long will it take to reach the Message from the Client to the Server?
  • How much time the Service Method will take to process it?

From the Parameter Inspector, you can find that

  • Which clients are making calls to the Service?
  • Is the User an Authenticated one?

In this article, we are going to see Message Inspector in detail

Message Inspector

Message Inspector is the most extensively used extensible point,which allows the developer to log,modify and replace the complete message. The following two interfaces help us to log and modify the messages in WCF pipeline

  • IDispatchMessageInspector
  • IClientMessageInspector

msginspector

Figure 3.0 Message Inspectors

The implementation of IDispatchMessageInspector- AfterRecieveRequest method helps us to inspect the incoming message, which received on the wire and before it dispatched to the Service method. The implementation of IDispatchMessageInspector-BeforeSendReply method helps us to receive the outgoing message from the Service method and before it sent on the wire.

The implementation of IClientMessageInspector-BeforeSendRequest method helps us to receive and inspect the message, which created from the client application and before it sent to the wire. IClientMessageInspector-AfterRecieveReply method helps us to receive the message (response message) from the Server and before it reaches the client application. Let us talk about it in detail.

Configuring Message Inspectors

Step 1

 

Create a separate class library and refer the following assemblies and namespaces

  • System.ServiceModel
  • System.Runtime.Serialization

namespaces

Next, Implement IDispatchMessageInspector methods AfterRecieveRequest and BeforeSendReply.  AfterRecieveRequest helps us to identify, log, modify or Replace the incoming message, which received from the client and before it, send to the Service method.

afterrecrequest

In the snapshot given above, you can see the parameters Message (reference param), Channel and InstanceContext. Channel parameter helps us to identify through which channel (basicHttp, netTcp) the message received. With the help of InstanceContext parameter, you can find out any InstanceContext(PerCall,PerSession) associated with this Service. The message object passed by the reference. The beauty of the Message object is that once you consumed (read, write, copied) the object, it cannot be used again. The message object is a read once the stream, once consumed it cannot used again. The responsibility of the Message inspector’s responsibility is to recreate the message. The source above shows that how the message is consumed and recreated. In our case, I have not changed the original data rather I have recreated the original data. The following methods would cause the message to consume.

  • CreateBufferedCopy
  • GetBody
  • GetReaderAtBodyContents
  • WriteBody
  • WriteBodyContents
  • WriteMessage

Accessing the message headers and properties does not have any issues, Accessing the message object once will be treated as consumed , and it cannot be consumed again

Step 2

In order to add MessageInspector we have to create custom behaviour extension class which is dervied from  IServiceBehaviour or IEndpointBehaviour, In our case, i will implement IEndpointBehaviour

msgendptbehaviour

In the snapshot above, you can find that IEndpointBehaviour is implemented ApplyDispatchBehaviour and other methods. You need to create the Message Inspector object and add into Endpoint Dispatcher. Finally, you need to create the Behavior extension class which derived from BehaviourExtensionElement and override the CreateBehaviour method and BehaviourType property to return the MessageEndPtBehaviour objects (custom behavior objects).

Step 3

As the last step, we have to update behavior settings in the App.config file as well

behaviorextensionendpointbehavior

In the snapshot given above, Please mention the name of the Extension, type and Assembly name. Assign the extension name “InspectorExtension” into the endpointBehaviour as well.

Output

Please refer the ServiceInspector Library in the Host application and Host the Server.If you clearly notice the output once the Client launched the application you can find that before the log I placed in the Service method triggers, log I placed in the ServiceInspector gets triggered.output

In the snapshot above, “PNR Query processing” and “PNR Query processed” are the logs placed inside the Service Method gets triggered only after the execution of AfterReceiveRequest method in the ServiceInspector.

Please refer the attached sourcecode for more details

Summary

To inspect the messages in the WCF pipe line IDispatchMessageInspector and IClientMessageInspector interfaces implement methods AfterRecieveRequest and BeforeSendReply in the serviceside to recieve and inspect the incoming messages and outgoing messages. WCF run time behaviour can be easily extended with the help of Extensibility.

Server Load Balancing in WCF

gop_balancing_act23

  • Introduction
  • Need for Load Balancing
  • Load Balancing Set up
  • Load Balancing Configuration
  • Output
  • Summary

Introduction

Load Balancing – Distribution of work load

Load balancing is an interesting feature in WCF to distribute the workload to the dedicated Server or a group of Servers, which provides a good response time for the client calls. With the help of routing, we can distribute the load and get the response immediately rather than waiting for the response from one Server always. Let us discuss this in detail

Need for Load Balancing

Load Balancing aims to have the following

  • Maximizing throughput
  • Minimize response time
  • Dedicated Server for the critical operations
  • Avoiding overload
  • Optimizing resource

Definitely, you can experience any of the problems, mentioned above in train ticket booking Websites during the festival season when you try to book the tickets. Since a large number of users have raised the ticket booking requests, the one Server would not able to process all the requests, which makes the users wait for a long time to get their tickets booked. On the other hand, it might not have a dedicated Server for the ticket booking calls (other calls like PNR Status and food ordering also utilize the same Server and make the network traffic). When there is an increase in the Server load, the response time to the client will also increase. In this article, we will see how we can balance the Server load in WCF by assigning a dedicated Server for the critical client operations like ticket booking. We can also load balance the Servers in a round-robin method.

Load Balancing Set up

loadbalancersetup

In the snapshot given above, you can find that the client will make various operations. If the critical operation like ticket booking request comes to the Load Balancer Service, it will redirect to the dedicated Server assigned for the critical operations to maximize the response time. This Server will take care of only the ticket bookings; it will not receive any requests like PNR status or food order etc. These normal operations will be handled by the other Service. Let us see how the same setup will be implemented, using WCF.

Services Configuration

As a first step, you need to define two services, where one is to handle the critical operations and the other one to handle the normal operations. Operation Contract or Operations will be same across the 2 Servers. Both the Servers are capable of handling all the operations. In the snapshot given below, you can find the operations like PNR,TicketBook will be hosted in a Service 1 and Service 2.

Load balancer is one which sits between the client and the Services will load balance; the BookTicket requests to the dedicated Server. Since the BookTicket operation will be getting many requests by a large number of clients during the festive/tatkal season, we have hosted a dedicated Server to maximize the response time. Once you implement the contracts, create the Service, endpoint and base address to host the Service. Please take the snapshot, given below as a reference and do the hosting for the Services 1 and 2.

servicelib

Please refer to my old articles for more details on hosting the services.

Load Balancer Configuration

Now, let us configure the load-balancing Server to move the ticket booking operations on a dedicated Server and the PNR operations to the normal Server. In our case, Service 2 will receive and process the critical operation requests (TicketBook) and Service 1 will receive and process the normal operation requests (PNR). Technically, Load balance Server is none other than the routing Server, which redirects the request based on the operation (TicketBook/PNR). Please refer to my old articles for more details on routing Service configuration. As I mentioned in my routing articles, please remember the sentence “Service the FilterTable and FilterEnd”, which will take you to configure routing Server easily.

Service = Configure the Routing Service, as mentioned in the snapshot is given below, The name of the routing Service should always be “System.ServiceModel.Routing.RoutingService”and select the address, binding and contract depending upon the requirement.

routingservice

Next step, Filter Table = Define the Filter table which requires Filter name and the associated endpoint name, which means if the filter gets matched, redirect the message to the URL mentioned in the associated end point.

filtrtable

The final one is FilterEnd, which means we need to define the filter and the end point. When we are defining the filter, we must supply the filtertype and filterData. In our case, when the data(iSeatBook/BookTicket) comes to the Service, it should pass the URL mentioned in the associated end point.
filterend

In the snapshot given above, you can find that if the incoming message comes for the BookTicket operation (look at the FilterData element) in Filter, it finds the associated endpoint in the filtertable. In our case, the associated end point of Filtername “TktBookFilter” is “ept_TktBookLoadBalanceServer”. Afterwards, it fetches the address from the endpoint element and redirects the message accordingly. In our case, the address to redirect the data (iSeatBook/BookTicket) is http://localhost:8650/RailServices2. This logic will redirect all the ticket booking operations to the address http://localhost:8650/RailServices2 and redirect all the PNR operations to the address http://localhost:8650/RailServices1. Please download the attached source code and have a look on it.

Output

Let’s analyze the output screens to get a better understanding

output

If you notice the first line in the top 2 Windows, it clearly mentions the address, where the Service is hosted. Left side Window in the top side tells that the Server is hosted at http://localhost:8650/RailServices1 and it processes only the PNR operations, whereas the right Window in the top side tells that the Server is hosted at http://localhost:8650/RailServices2 and it processes only the TicketBooking operations. The bottom Window is a client Window, where it sends the requests to the Service side. Please download the attached source code for more details on it.

Summary

Load balancing feature in WCF can be attained with the help of routing. It load balances (routes) the incoming requests to the appropriate Server, which is based on the operation.

Working with MS word using Spire.Doc

                                                                                                                                     – Rameshkartik.RS

  1. Introduction
  2. Document Creation
  3. Header Updation
  4. Footer Updation
  5. Image set up in Header and Footer
  6. Summary

Introduction

In this article, am going to explain you the ways how you need to work with Microsoft word using Spire.Doc. Yes, Spire.Doc is a wonderful library for the developers to perform document operations like Document Creation,Page Setup,Page Background,Setting Header and Footer,Changing Font etc. Here am not going bake you everything  I listed above but you will have a clear session on Document Creation, Document update,Header and Footer creation,Header image upload. Let’s discuss this in detail

Document Creation

You can’t find any software without reports, Yes, Reports are the major source to understand what exactly the current trend is? Where were we lacking this month? How are we going to improve the trend? Reports will give one a better idea to align ourselves towards the organizational goal. Creating the reports in word/pdf should also be easy, in that case, e-iceblue provides us with a wonderful library Spire.Doc, using which one can operate the Microsoft word easily and effectively. Okay, Let me explain you the steps to create the document

As a first step, download the Spire.Doc from this link, After that refer the Spire.Doc DLLs into your project

spirereference

To create the document using Spire.Doc ,We should remember the five important steps mentioned below

  1. Use Spire.Doc namespaces in code
  2. Creating Document instance
  3. Creating Section instance from the Document
  4. Creating Paragraph instance and Append the text
  5. Save the Document

First, use the Spire.Doc namespaces into the code as mentioned in the below snapshot.If we didn’t mention the namespace,we would not be able to use the Spire.Doc classes and methods.

using

Next,create the document as mentioned in the below snapshot, using the doc reference we are going to add the paragraphs,sections into the file and save it

doccreate

Then create the sections from the document instance and assign into a Section instance

section

As we need to write some text into the document ,create the paragraph instance from the section instance and append the text into the paragraph using Append Text Method.

parag

So far,we have created the Document,adding sections ,paragraph instances and AppendText into the paragraph.Finally, we need to save the document as mentioned in the below snapshot

save

Header Update

In this section, you will see how to insert the header into the document. When you are creating the document it’s very important to define the header and footer.The Header will be used to display the name of the article or document with the image. Readers whoever reading the document gets the information from header/footer when he is moving from one page to other. Let’s see how we can insert the header using Spire.doc library. Here we need to remember five important steps to define the header into the document

  1. Creating Section
  2. Creating Header
  3. Creating Paragraph
  4. Appending Header text in Paragraph

As a first step,we need to create the section in the document

section1o

With the section instance, you need to create Header or Footer instance based on your requirement,In our case, we need to create the Header object from the section object called section. Refer the below-mentioned snapshot for details

header

Once you define the header , we need to update the Header text, for which we need to create the Paragraph object from the header object

headerpara

After that , Append the header text into the paragraph object and assign into TextRange Object. Refer the below snapshot for the details. Text Range instance holds the HeaderText information.

textrange

As like we do formatting for the document text we can also do the formatting for the header text as well. You can change the Font name,Font size and Text colour of the Header Text.Refer the snapshot below you can find that Font name “Cambria” has been set for the header text and Font size as 11,Text colour as Orange. Likewise you can change the header texts according to your requirements

headerfont

Friend,Do you want to change the border style,colour of the border? of course,you can also do that by assigning your required border style to the header paragraph. Please look at the below snapshot,the source code itself explain you everything.

borderstyle

In our case, I have updated my border style as ThickThinMediumGap and space as 0.05f.

Footer Update

We are done with the header update, In this section,we shall see Footer update. Footer configuration/update is almost same like header update. Only a few parameters will be different compared to the header configuration. As usual, you need to define the Footer from the section instance from which ,create the paragraph from the footer instance . Then you need to use the AppendText Method from the paragraph object and assign into TextRange instance.

footerobj

Please find the above snapshot,paragraph instance has been created and appended the footer text

Image set up in Header and Footer

In the Header, most of the documents contain their company logo’s.  Updating the image file in the header/footer is effective using Spring.Doc. You just need to select the AppendPicture method from the paragraph(header) instance. AppendPicture method will take only the image parameter,where you just need to supply the path of the image.Look at the below snapshot for more details

imageset

Please download the source code from this link

Summary

Spire.Doc is a .net library created for document operations like PageSet up,Header & Footer ,Page Background,Font. Using that developer can easily update the Microsoft word document and release the products effectively and efficiently.

Convert Doc to PDF using Spire.Doc in C#

spiredoc

                                                                                                                                    -Rameshkartik.RS

  1. Introduction
  2. Library installation and Reference
  3. Document to PDF conversion
  4. Document to XPS conversion
  5. Summary

Introduction

In this article, I will explain about certain third- party libraries, which helps to create, convert and manipulate word and excel files. All we need to do is get the library reference from NuGet Packet Manager and make use of it. You can also install it from NuGet package Console if you are interested. Once you add the reference into your project, it is just a matter of few method calls to the library to get the features like converting the document to PDF or converting the document into Image format. Let us discuss this in detail

Library installation and Reference

Spire.Doc is the library designed for programmers to manipulate word processing tasks.  With this Library one can easily convert,create,read and  write word document file. As a first step, I request you to Open the Visual studio and Click File->New->Project->Windows Application

projectadd

After that open, the Tools->Library Package Manager Console->NuGet Package Manager Console and provide the following command

Install-Package Spire.Doc

packagemanager

Another way you can also download the same from websites. Once you successfully downloaded the package you can check the reference in the project. You need to  manually add the reference in case you download the library from the website.

spiredocref

Document to PDF conversion

Here, am going to explain to you how you can convert your word document into a PDF document by consuming the library. As a first step, just use the library reference into your windows application.

using

After that, you just need to create the XML document object and load the word document which you want to convert into a PDF document. Then you have to choose the Method SaveToFile method in the XML document, this will automatically convert the word document into PDF document. Following is the snapshot, which details the conversion.

doctopdf

In the snapshot above, you can find that XmlDocument object named doc has been created, After that I have loaded Caramel_Chocolate.docx document into the doc XmlDocument. After that select SaveToFile method in the XmlDocument and provide the FileFormat you want to convert and name of the file once it get converted., in our case I have selected as FileFormat.PDF and Caramel_Chocolate_PdfVersion.PDF.

This will convert the word document into a PDF document.

Document to Txt conversion

Here, you can see the steps to convert the word document into a text document.

All the steps remain the same, as we did for Word to PDF conversion except the FileFormat value need to be changed into FileFormat.Txt. Please look at the below snapshot to get the complete details of conversion

doctotxt

In the snapshot above, you can find that Caramel_Chocolate.docx a word document file will be converted into Caramel_Chocolate_TxtVersion a Text document

Document to XPS conversion

There are situations you need to convert the word document into an XPS Image file , and the main Advantage of having, as an XPS file is one cannot able to edit the content.

The below snapshot will explain you the steps we need to consider for converting word document into a XPS image file.

doctoxps

In the snapshot above, you can find that word document will be loaded into an XML document and then We need to choose the file format version into XPS. With that, one can easily convert the word  Document into XPS image.

SourceCode

Summary

Spire.Doc is a .Net Library designed to convert, create, read and write word document file. With that Developers can easily convert the word document into PDF,XPS,Txt format.

Protocol Bridging In WCF

Tags

Introduction

Bridging => the action of putting a bridge over RIVER

In the sentence, given above, you can find that bridge has been constructed over the river with the intention that traffic flow shouldn’t be interrupted for any reason. Yes, people travelling by road transport find it difficult to continue their journey because the river gets in their way. Bridge solves the interruption and provides a smooth flow of traffic to reach the other end. The data communication shouldn’t be interrupted across the Services as each Service owns a different set of protocol standards like one might use TCP communication, others might use HTTP communication. Here, we see protocol bridging feature from WCF to route the communication across a different set of protocol Services. Let’s discuss this in detail.

Protocol Bridging

Protocol bridging is one of the important features in WCF to route the data from the client to the Services when both use a different set of protocols. (E.g. Client=>basicHTTBinding, WCF Service => NETTCPBinding).

In the snapshot, given above, you can find that client sends the messages in HTTP format to the router Service, but the internal Services, which are connected to the main router, do not accept the messages in an HTTP format. It rather accepts it only in a TCP format. Thus, the router switches to a different binding, according to the internal Service and sends the message. The client will get the response messages in HTTP format. It’s a complete responsibility of Router to read the data in a source protocol and switch to the destination protocol, based on the need. It can also be useful when you don’t want some complex Services. The actual URL shouldn’t be exposed to the client. In this case, you can provide only the main router Service URL to the client, the main router Service then redirects the messages to the actual Service, based on the message filtering.

Routing Configuration

As mentioned in the previous snapshot, we shall configure two Services, which are Router or Front end Service and internal Service. Internal Service will accept the messages in a TCP format, Router Service will accept the messages in HTTP format.

Step 1

As a first step, we shall configure the internal Service named FoodInventory Service, which accepts the messages in a TCP format. As mentioned in the snapshot, given below, you can configure the Service Library.

code

You can find the Service Library created with the address“net.tcp://localhost:8523/FoodInventoryLib/Service” and the binding is NETTCPBinding . Once the Service Library is created, it can be hosted. In this case, we will do the Self-Hosting. If you need any assistance for Self-Hosting, please refer to my article “Hosting in WCF”.

Step 2

Once the internal Service is configured, we need to configure the Router Service or Front-end Service. As mentioned in the snapshot, given below, you can configure the Routing Service, which routes the messages, based on the message content, Filters. If you need any assistance on configuring Routing Service, refer the article “Configuring WCF Routing”.

code
code

We have to remember the four important configurations in creating Router Service configuration. I will suggest that you remember the simple sentence to recollect the routing Server configuration, which is “Address the Filter Table and Filter End”. Yes, Address = > you shouldn’t forget to update the Server address. In our case, it is http://localhost:8543/MainRouteServer/Router, a client will use this address to send all the messages. Next is Filter Table. Once you define the address, don’t forget to declare the FilterTableName in Service Behaviour Tag, and then create the same Filtertable in Routing Tag. In our case, it is “RoutingInformationTable”. Next is Filter. Create and add the Filter in the filtertable. In our case, it is “MatchAllFilter”, Final one is End. You need to create the endpoint and associate the same in the filtertable. The configuration, given above says that if the message filter is applied successfully,  you can redirect the message to the endpoint listed. In our case, if any incoming message contains the endpoint address as http://localhost:8543/MainRouteServer/Router, the message will be redirected to the service net.tcp://localhost:8523/FoodInventoryLib/Service. Wherever the Service needs to be routed, just simply update the name of the binding with the Service URL. In our case, you can find that endpoint has been created under the client tag with the address and binding details. WCF internally switches (bridges) the protocol into TCP format and sends the messages to the internal Service. Once the internal Service is responded to the Main router Service, it again switches (bridges) the protocol into HTTP format before sending to the client.

Hope you have enjoyed learning. Please update the comments/likes as a token of appreciation.

SourceCode

Please use this link to download the source-code

Summary

Protocol bridging is an important feature in WCF routing. It will be useful when you need the data to travel among the various sets of protocol Services.

Configuring WCF Routing

Tags

Introduction

Routing Service is an intermediary between the client and the back-end services. It has the ability to receive messages from clients and route them to the appropriate service, based on the message content. The client needs not to have the multiple endpoints, whereas the routing service has the aggregation of various service endpoints, and the messages will be routed based on the message content. If you are not familiar with the Routing basics, you can refer to my last article “Basics of WCF Routing”. This topic will help you understand the Routing Service configuration. Moreover, it also tells how filters are applied to route the back-end service, based on the message content.

Architecture

To configure the Routing, one has to configure the following components –

  • Routing Service
  • Contracts
  • Service Behaviour
  • Filters
  • Endpoint

Before you know how to configure these components, let’s first understand what exactly the purpose is of configuring each component.

Routing Service

Routing service is implemented as a WCF service in the System.ServiceModel.Routing assembly. It’s already available in the WCF to route messages over any protocol, using a different message exchanging patterns like one way, two way, Request-Response and duplex messaging. We only need to define the name, address, binding, and contract according to our requirements.

Contracts

Service contract of Routing service supports different Message Exchange Patterns (MEPs), like request-reply, duplex session, and simplex session channels. These Interfaces are required to process the messages from channels.

Contract Description
IDuplexSessionRouter Defines the interface required to process messages from duplex session channels
IRequestReplyRouter Defines the interface required to process messages from request-reply channels.
ISimplexDatagramRouter Defines the interface required for processing messages from simplex datagram.
ISimplexSessionRouter Defines the interface required to process messages from simplex session channels

Filter

The Job of the Message Filter is to inspect specific sections of a message, such as – address, endpoint. To send the message to the desired endpoint, the incoming message should match the filters applied.

FilterTable

Once the filters are matched with filter data in the earlier step, here we are associating the filter with the endpoint name.

Endpoint

Endpoints are used for associating the address and binding with the endpoint name. The Routing service refers the address with the associated endpoint and routes the messages accordingly.

Routing Configuration

So far, we have seen what are all the components required and why these are required to configure Routing . Now, I am going to explain to you in detail, the steps involved in configuring the simple routing.

Routing Configuration

In the above diagram, you can find that Client always connects to the Front-end service. Then, front-end service will inspect the message content and route the messages to the Food Inventory service or Materials inventory service, based on the message content it receives from the client. To accomplish this configuration, let me explain to you in detail-

Step 1 – Let’s start with configuring back-end services first. I would recommend you guys to configure and host the back-end services in IIS. As soon as the IIS gets started, these services will also get started automatically, unlike the self-hosting where we have to start it manually. First, create the Food Inventory Service Library and do the IIS hosting. If you need assistance in creating IIS hosting, please refer my old article (http://www.c-sharpcorner.com/article/iis-hosting-in-wcf/). We don’t have any complex configuration in backend service.  In the below snapshot, you can see the snapshot of my Food Inventory configuration for your reference

Routing Configuration

Hope you have done the IIS hosting for Food Inventory. Once you are done with it, we will go for creating a Materials Inventory Service.

Step 2 – In step 2, you have to repeat the same steps (what you have done for Food Inventory) to the Material Inventory. Create the Material Inventory Service and host it in the IIS. In the below snapshot, you can see the Materials Inventory Service configuration, for your reference. So far, you are not able to find a single configuration in Routing. All the routing configuration will happen only on the next step i.e on Front-end service or Main Service.

Routing Configuration

Step 3 – Step 3 is the most important configuration in the Routing. As I mentioned in the architecture section here, we need to configure the following in the Front-end service

  • Contract
  • Service Contract
  • Filters
  • Endpoint
  • Routing Service

As a first step, create WCF Service Library project (New Project ->WCF->WCF Service Library) and open the App.config file. As mentioned in the below snapshot, update the service name as “System.ServiceModel.Routing.RoutingService” and update the ServiceBehaviourConfiguration. In our example, I have named the service behavior as “Routing Service Behaviour”.

Routing Configuration

Then, as usual, give the address for your service. In our case, since this service is a front-end service for the client, though we have a couple of back-end services (Food-Inventory & Materials Inventory), the URL to access the services remains same for the client. And, that URL is none other than Front End Service URL (http://localhost:8555/MainRoutingService/Router). After that, did you find the contract name in the endpoint element? As I already mentioned, Routing Service is already available in WCF and the name of the contract we decided for our case is “System.ServiceModel.Routing.IRequestReplyRouter”. As all my services, MEP (Message Exchange Pattern) is Request Reply Pattern. I thought of selecting this option as a contract with my front-end service.

Step 4 – This step is all about defining the Filters and Filter Tables. The first thing you need to do here declares the name of a routing filter table in the Service Behavior.

Routing Configuration
In the above snapshot, you can find that name of a filter table is a ServiceRouterInfoTable. After that, you have to write the routing logic in the form of Filters and Filter Table. A Filter has 3 elements- name, filter type, and filter data. You have to define these 3 as mentioned in the below snapshot

Routing Configuration

The FilterData will be used to inspect the specific section of an incoming message. Once the message is matched, the associated endpoint entry name will be taken to forward the message. In the above snapshot, filterData, “GetFoodInventory” gets matched with the incoming message. So, the associated endpoint name “ept_FoodInventory” will be taken as mentioned in the the below snapshot

Routing Configuration
As the last step, you need to define the endpoint names ept_FoodInventory and ept_MaterialsInventory in the endpoint element. Once the filter is matched with the filter data and the incoming message, endpoint name will be referred to the filter name. Then, the address and binding information against the endpoint name will be taken to route the messages accordingly. The following snapshot shows how to define the endpoint in the Front- end service

Routing Configuration

Finally, we need to host the Routing service or Front-end Service. Place the below code and start the project. The Routing Service will be launched to receive the requests from the client. Route it to back-end services based on the message content.
Routing Configuration

Guys, we are done on the service side. So far, we have configured back-end services and hosted them in IIS. Now, that we created a front end service and created Service name, Contract and Service behaviour. Then  we do Filters, FilterTable, endpoint definition and hosting the Router Service

Step 5 – As a Final step, let me tell you what you need to do on the client side. The simpler option would be adding the service reference by right clicking the project -> Add Service Reference. Provide the Routing Service URL and click Go (Refer the below snapshot). Before that, make sure, your back-end service is up and running in IIS. The same is applicable to Materials Inventory Service as well. A couple of times, you have to create Service reference for both the services.

Routing Configuration

As soon as you add the service reference, App.config in the client project will be populated automatically with the endpoint, binding and contracts. As the client needs to connect only Routing service, just update the Routing URL http://localhost:8555/MainRoutingService/Router over both the endpoints in the client. Now, run the project and make a service call, it will automatically route to the desired service.

Please refer to the attached source code for the details. The attachment includes back-end services FoodInventory and MaterialInventory, front-end services RoutingService and the client application. Hope you enjoyed learning! If anything strikes you, please feel free to update your comments over this article.

Source-Code

Please use this link to download the source-code

Summary

Routing Service in the System.ServiceModel.Routing Namespace. Front end service will get all the messages from the client and route it to the appropriate service based on the message content.

WCF Service Failover

Tags

Introduction

Failover – The standby server takes over, when the main server fails.

In this article, I will explain the Failover functionality to be achieved, using WCF concepts. The general idea behind going into Failover is 24/7 availability of the service to the critical client applications. The client application should always be in a position to consume the Backup Service through the Main Service, which is not available due to some reason. Let us discuss this in detail.

Failover

Failover is a method of protecting the Applications/communication from failure, where there is a backup Service. IT automatically takes over when the Main Server fails. In a real world scenario, you can see that ticket booking websites take more time to book the tickets (to get the Server response) during peak hours. The Server takes more time due to Server’s unavailability, or if the number of requests in the queue is higher, or for any other reason/s. Whatever the reason is, the client application should not be impacted, another Server should take it up when the main Server is not available.

Figure1.0 Work Flow Diagram

In the snapshot, given above, you can find that the client communicates with the main router. It is not aware of the Primary Service or Backup Service. When the router receives the request from the client, it usually tries to process it with the primary Server. If the primary Server is not reachable for any reasons, the main router then automatically tries to connect with the Backup Service 1. If the Backup Service 1 is available, the request would be processed and send the response to the client. If the Backup Service 1 is also not available, it would send the request to Backup Service 2 to get it processed.

The client does not need to worry about the availability of the Servers. The main router will re-route the request to the backup services and get it processed if the Primary Servers are not available.

Need for Backup

Let us discuss, in detail, about the need of a backup service.

Critical Applications Availability

Critical applications are the ones, where a large number of users always want to perform many transactions at a time. For example, bank transfers, where a large number of people need to do fund transfers and other transactions as part of their day-to-day activities. If this kind of Application Server gets affected, the impact will be huge. To overcome these issues, Backup Server is always recommended to take care of the client’s transactions, if the Primary Server is not available.

Load Balancing

There are situations when the Service gets more requests/transactions only during the peak time on any single day. Let us take the ticket booking websites. A large number of users will try to book the tickets once the tatkal period gets started. If the Server is not capable enough to process all the requests, the clients will not be able to book the tatkal tickets. To overcome this, the Main Server should load balance the requests to the backup services accordingly. Let’s say, if the Primary Server is already processing 1000 messages, the Main Server would reroute the other 1000 messages to the Backup Services. This would increase the processing time and the client’s request will not affect.

Routing Configuration

Let us take the Figure 1.0 as a reference for configuring primary and backup services accordingly. As a first step, create the Primary Service library and the host application. As usual, in the Primary Service library, you can define the contracts and service implementation. Afterwards, create the host application and refer to the Primary Service library, define the Service, endpoint, and host it. In our example, I have done it in self-hosting. If you need an assistance in configuring and hosting the Services, please look at my previous articles Configuring WCF Routing, Hosting in WCF.

Primary Service


Figure 1.2 Primary Service

From Figure 1.2, you can find that Primary Service is hosted on net.tcp://localhost:8523/PrimaryServiceLib/Service. Afterwards, you need to repeat the same configuration for the Backup Services 1 and 2. In our case, the address of Backup Service 1 and 2 are given below.

“net.tcp://localhost:8524/BackupService1/Service/”,net.tcp://localhost:8525/BackupService2/Service/.

Now, you have successfully hosted the Services Primary, Backup Service 1, and Backup Service 2. Now, it is time to define the Routing Service, which will pass the messages to the appropriate Service, based on availability. As I have already mentioned in my previous articles, we shouldn’t forget this simple sentence “Address the filter and filter end” . It is just a sentence I have framed myself to remember the RoutingServer configuration steps, which are Address, Filter table, Filters and endpoint, As I shown in the Figure 1.3 snapshot configure the Routing Service accordingly


Figure 1.3 Routing Service

In the filter table named “RoutingInformationTable”, you can find that the MatchAllFilter has been applied and routed to the end point named “PrimaryService_TCPEndPoint”. MatchAllFilter is used to route all the messages from the client to the PrimaryService_TCPEndpoint. You can find other attribute named “backuplists” in the filter element. If the RoutingService find the PrimaryService_TCPEndpoint is not available for some reasons, it can route the messages to the endpoints listed in the BackupServices. If the backup Service 1 is also not available, then it re-routes to back up Service 2 endpoint. So the client will not aware of the Service from which Service his request served.

SourceCode
Please use this link to download the source-code

Summary

Failover functionality is an important feature in Client-Server communication. It is quite natural that Services may stop/not be reachable for any reason. Routing Service will take the client to the different Service (backup) if any of the primary Services are not available. Backup Service will process the request and send it back to the client.

Basics Of WCF Routing

Tags

Introduction

Routing => Take the other way

Hello, everyone!

I will start this article in a different manner today. Let me start with a small scenario – I hope you remember the old style cinema theatres where one person would check our tickets and direct us to take a left side or right side of the seating, based on the type of the ticket we bought.
Another example like this is –  You are actually entering your office premises by car. According to the block/area/company you work in, you are told to park your vehicles in a particular location. Please note that your seating area will differ according to the class/number of a ticket you purchase. Also, your parking area will differ according to your company. So, the point here is that based on the content you own, whether ticket or company, you are routed to a particular location. Let’s discuss routing in the computer world.

Routing

Routing service will act as a Central Router or Message Router which receives the messages from the client and routes the messages to the appropriate service, based on the message content client provides. Routing Service will act as a front-end service to the client, receive the message, apply the filter,  and route the messages to the back-end services.
Routing
In the above figure, you can see that the Routing Service is an intermediary between the client and the services. The primary job of Routing Service is to route the client messages to the back-end services. Routing service is implemented as a WCF service in the System.ServiceModel.Routing assembly.

Need of Routing

You may wonder why we need to pass the messages via Routing Service,  or,  why can’t we simply pass the messages directly to the back-end services?

To answer this, Routing Service aggregates (collective) multiple destination endpoints to reduce the number of endpoints exposed to the client applications. So, the client will be having only one destination endpoint and send messages to the Routing service. Then, the Routing Service will redirect the messages, based on their content, to the respective services. Another benefit of this is that some sorts of operations have to be processed only by the particular service. For example, all tax calculations have to be processed only by the service A.

Service Aggregation

Clients do not need to remember all the Service URL’s to get it served. Only Routing Service URL needs to be remembered and it will have the complete collection of back-end services

Service Versioning

Imagine you have to migrate the existing service to the new service. So, you are in the situation to maintain the different versions over a period of time. Of course, the customer should be able to utilize the existing features in the old version of the service and the new features in the new version of the service. For that, Routing Service plays a very important role in redirecting messages according to the version information in the messages from the client.

Priority Routing

There are some scenarios like, specific clients requests (e.g. – Admin Requests) have to be processed in a separate service among other clients requests(Eg: Normal user Requests), to segregate a particular client request and process it in a separate service, routing would be an ideal option, by using a filter in routing service that looks for client specific information contained in the message and redirects the request to the appropriate service to get it processed.

Error Handling

This would be used in a situation like, though our main service gets affected/crashed/not reachable, the backup service will take care of managing the errors/exceptions.

Protocol and Security Bridging

Imagine you have a legacy service which could use only HTTP protocol, but in your recent service version, it supports multiple protocols. To integrate the old legacy service into the new version which enables users to get the support of all the protocols., Routing service (Legacy Service) will communicate with the back end services with a different protocol and reply to the client in a different protocol.
Routing
Dynamic Configuration

There are a few applications which should run 24X7 time frame without any interruptions. It’s not fair to stop these applications and modify the configuration as it will be a huge impact to the customer. For these sets of scenarios, Routing service provides an IExtension<T> implementation called Routing Extension which allows dynamic update of Routing Service configuration at run time.

In my next article, we shall see how to configure routing in WCF with detailed steps and source code.

Summary

Routing Service works in the System.ServiceModel.Routing Namespace. Routing service aggregates one or more service endpoints and routes the messages based on the message content which comes from the client.

Message Logging In WCF

Tags

Introduction

WCF is all about handling the messages from different systems. From a developer’s  perspective, Message Logging may need to find out the exact message, transmitted over a period of time. For example, you may want to know the messages that are logged at the transport layer (For debugging purposes).

Of course, it’s highly recommended not to enable the ‘Message Logging’ options in the production environment. In this article, we are going to discuss what various available options there are to log the messages and how we control the Message Logging.

Let’s discuss in detail.

Message Logging

What comes to your mind when you think about message logging? Obviously, you wonder where do we need the log and what messages are logged there. Yes, “where” comes before “what”. So, here is the answer.  The listener will take care of “Where we need to log the data”, and Message Logging will take care of “What we need to log”. These two elements are essential to log your messages, <System.Diagnostics> enables you to interact with event logs and Performance counters,

Following are the details you need to mention in <System.Diagnostics>

  • Source
  • Switch value or Trace Level
  • Type
  • Initialize Data (Path of the log file)

Switch Value – Tracing settings can be done in the Switch value, Following are the Trace Levels,

  1. Off – Tracing Disabled, ignores the tracing
  2. Critical – Critical issues like Application crashed or shut immediately, Tracing will be generated for critical issues in service
  3. Error – Logs all the exceptions
  4. Warning – Tracing will be generated for warnings which indicate the possibility of problems
  5. Information – Tracing will be generated for the successful execution of application
  6. Verbose – Mostly used for debugging purpose. it allows low-level tracing
  7. Activity Tracing – Tracing will be generated for the communication across components of an application.

    code

In the above snapshot, you can find the source as Message Logging. That means diagnostics has to interact with the System.ServiceModel.MessageLogging to record the event data. IntializeData gets file path where we need to log the data. XmlWriteTraceListener will create the traces in the XML Format.

Once we are done with the diagnostics part, we need to take the Message Logging part to complete the Configuration as I have mentioned in the below snapshot.

code

  • LogEntireMessage – Do you need to log the entire message including header and body? Default value is False.
  • maxMessagesToLog – What is the maximum number of messages to be logged? Ex- 1000 messages, Messages will not be logged if it goes beyond this level 1000. This will save you from performance overhead of your service.
  • maxSizeOfMessageToLog – What is the maximum size of a message to log? Ex- 2000 bytes. It helps you to decide the size of a message the log.
  • logMessagesAtServiceLevel – Do you want to log the messages that are about to enter the service(On receiving)? Do you want to log the messages that are about to leave the service (On Sending).
  • logMessagesAtTransportLevel – Do you want the messages which are ready to be encoded (On Sending) and transportation over the wire? Do you want the messages which are ready to be decoded (On Receiving) after transportation over the wire?
  • logMalFormedMessages – What’s the meaning of Malformed Messages? It’s all about the WCF messages that are rejected by the WCF runtime during processing. Use this element to log the messages that are rejected by the WCF Stack

Please find the below snapshot of app.config file, and refer the attached source code for the complete reference.

code

Source-Code

Please use this link to download the source-code
Summary

To log and analyse the happenings in the server side, Message Logging will be a perfect option in WCF. There are two things we need to define in the message logging, Listener ( to write the data in a particular location) and Message logging (to log the messages at the service level, transport level).

Protection Level in WCF

Protection Level in WCF

padlock-597495_1280

Rameshkartik. RS

  1. Introduction
  2. Available Parameters to Protect Data
  3. Protection Level
  4. Configuring Protection Level
    1. Declaration
    2. ProtectionLevel.None
    3. ProtectionLevel.Sign
    4. ProtectionLevel.EncryptedAndSign
  5. Summary

Introduction

In the modern world, we are about to communicate with different persons, firms in our day to day life to get our business done, in which we are always concerned about the confidentiality and integrity of the information we send. Often we send information which is highly secure for the business,In few cases ,we send information which is not to be a secured one or it might be irrelevant to the business. Ok, Let’s talk about it in detail with the WCF technology.

Available Parameters for Protecting Data

Sign – It confirms the message has not been tampered or changed by anyone. It signs all the messages on the wire to provide the message integrity

Encrypt and Sign – It confirms the message we send is confidential and it has not been tampered anywhere by anyone.

Protection Level

Protection Level  = Throttle (Control) Message Protection

By default , WCF protects all the message on the wire to provide the data confidentiality and message integrity. If the developer wants to control the flow of message protection, Protection Level will  be an ideal option. Yes,  In Few scenarios, messages are not required to be secured one since it doesn’t have any sensitive information, In few scenarios messages should transmit only in a secure mode. For these set of things, WCF provides the flexible approach called ‘Protection Level’ . The developer can set their messages which require  message integrity or message confidentiality or Both

If the data is not sensitive over the wire,  then I will recommend you to set the ProtectionLevel as None because it produces a greater performance. Of course,  Encryption or Sign will definitely take an additional time in every request and response. Message contracts also support a way to override the protection level for the operation.

Configuring Protection Level

The supported message protection level in the WCF are

  • None
  • Sign
  • EncryptAndSign

The Protection levels can be done at all the levels

  • Service Contract
    • Operation Contract
      • Message Contract
        • Message Header
          • Message Body

If we are defining our protection level  at the top level, it is applicable till the root level unless otherwise if we are overriding it in the root level . You can define it like ProtectionLevel is EncryptAndSign in the top level (Service Contract) and override it in the bottom level (Operation Contract) like ProtectionLevel is None.  The developer has a flexible approach for controlling the message protection across all the levels.

Declaration

Prot

In the above snapshot you can find out the protection level has to be declared over the service method .For the method GetStringData i have made it as a Sign,because I don’t care about the confidentiality here , but I care for the message integrity, That’s why I have chosen Protection Level.Sign.

For the GetDetailedData method I have set the Protection Level as  ProtectionLevel.None , though my service contract Protection Level configured as ProtectionLevel.EncryptAndSign because i don’t want to protect this method’s message on the wire.

For the GetIntData method, I didn’t say anything about the Protection Level, Then What will be the Message Protection Level? Of course, it will take the Protection level,  we said in the Service contract level.

ProtectionLevel.None

The following is the snapshot of the message flow if we set the ProtectionLevel.None.

imgpr

You can find that the values are transmitted over the wire as a plain text. There is no encryption or Sign. Because we have mentioned the Protection Level is None, Kindly refer App.config of the Service Library which is enclosed ,  you can determine the ways to generate the logs. Once it is generated have a look on the messages.svclog .

ProtectionLevel.Sign

The following is the snapshot of the message flow if we set the ProtectionLevel.Sign.

imgpr1

imgpr2

You can find that Data Integrity is maintained,  but the confidentiality is not maintained. Signature information in the above snapshot  will take care of the Data Integrity related things, In the body of the message in the above snapshot you can determine the messages were plain and not encrypted.

ProtectionLevel.EncryptedAndSign

The following is the snapshot of the message flow if we set the ProtectionLevel.EncryptedAndSign.

imgpr3

If you find the body of the message, you can find that messages  were encrypted and signed. By setting the different ProtectionLevel in different levels , we can make our service more efficient and responsive.

SourceCode

Summary

If the messages sending over the wire is not an important one, Then you can set the protection level  as  None for all your service messages,  it increases the performance. Protection levels can be set at the Service Level,  Operation Level, Message Level,  Header Level and Body Level