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.


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


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


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


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.


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


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


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.


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


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


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


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


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.


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.


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.


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.

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.


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


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.


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


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


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.


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


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


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.


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


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


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


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


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.


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


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.


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.


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


Please download the source code from this link


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#



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


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


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

Install-Package Spire.Doc


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.


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.


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.


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


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.


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.



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.

Protection Level in WCF

Protection Level in WCF


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


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.



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.


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


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 .


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



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.


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


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.



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