Durable Services in Windows Communication Foundation (WCF)

Introduction

In this article we will learn about durable services and how it can be implemented in Windows Communication Foundation (WCF). I will also demonstrate steps to create a durable service in WCF along with the source code. WCF durable service concept was only introduced in .NET Framework 3.5 version. After reading through this article you should be having a good idea on WCF durable services, how it works and how to build it.

What is a Durable Service in Windows Communication Foundation (WCF)?

Generally web applications, web services and WCF services are stateless. In other words one can say HTTP is a stateless protocol. The word stateless here denotes that a state of the object in WCF service will not be persisted between multiple requests to the service. WCF durable service paves way for building long running applications with a persisted state. WCF durable service helps in persisting the state of the service instance between multiple requests or even if the service/client application is restarted.

This state persistence is done by XML serializing the instance of the server object and storing them in the database with a GUID as a unique key for the record. This GUID will be sent to the service by the client so that the service would retrieve the corresponding instance from the database for that request. Hence the state is persisted. WCF durable service also provides an option to remove the instance from the database.

How it is Different From Sessions in WCF?

As a reader you will be definitely dubious about the fact that what makes the durable service state persistence different from the session state persistence in WCF using the InstanceContextMode.PerSession option. The answer is simple, session state persistence in WCF will only be effective till the client or WCF service is restarted. Once the service or client is restarted the persisted state will be lost as the storage of session is in-memory. On the other hand with WCF durable service state persistence is not based on the user context rather it is based on the GUID passed by the client. Here the state will be persisted even if the client or WCF service is restarted since the instance is stored in the database.

Implementing WCF Durable Services: Prerequisites

In this section we will look at the things need to be done or to be noted while developing a WCF durable service. Check out the below points.

  1. Need to have SQLServer express installed on the machine and create a database to store the serialized instance in it.
  2. Go to C:\WINDOWS\Microsoft.NET\Framework\v3.5\SQL\EN path on your file system; fetch the SQL scripts from the files SqlPersistenceProviderLogic.sql and SqlPersistenceProviderSchema.sql. Here is a brief description for the file contents.
    1. SqlPersistenceProviderSchema.sql: This file contains the script for creating the tables and required schema for storing the object instance.
    2. SqlPersistenceProviderLogic.sql: This file contains the stored procedure script for creating the serialized instance in the database, retrieving the instance and deleting the instance.

Sample Application

In this section we will create a sample WCF durable service. I will also be providing the description along with the source code.

  1. As a first step create a solution named WCFDurableServices solution
  2. Add a WCF Service Application to the solution and name it as WCFDurableService.
  3. Add a Console Application to the solution and name it as ClientApplication.

WCF Service

Let us now implement the durable WCF service. Add a ServiceContract named IAccountingService. Below is the source code:

  namespace WcfDurableService
  {
      [ServiceContract]
      public interface IAccountingService
      {
          [OperationContract]
          void PersistInstance();
  
          [OperationContract]
          void AddAmount(long amount);
  
          [OperationContract]
          long GetTotalAmount();
  
          [OperationContract]
          void ClearInstance();
      }
  }

There is nothing different with the service contract for developing durable service as you can witness in the above code. Let us now create a .svc file named AccountingService.svc. Inherit the AccountingService class in AccountingService.svc.cs file and implement the same. Below is the code:

  namespace WcfDurableService
  {
      [Serializable]
      //Attribute require to mark this implementation as a durable service
      [DurableService]
      public class AccountingService : IAccountingService
      {
          private long _totalAmount;
  
          #region IAccountingService Members
          //Attribute to decorate the service methods
          [DurableOperation(CanCreateInstance=true)]
          public void PersistInstance()
          {
          }
  
          [DurableOperation]
          public void AddAmount(long amount)
          {
              _totalAmount += amount;
          }
  
          [DurableOperation]
          public long GetTotalAmount()
          {
              return _totalAmount;
          }
  
          [DurableOperation(CompletesInstance=true)]
          public void ClearInstance()
          {
          }
  
          #endregion
      }
  }

In the above code you will notice the Serializable attribute. It is required since the instance of this implementation class will be XML serialized and stored in the database. Also you could see there are two new attributes decorating the implementation class and the service method.

  1. DurableService: To decorate the implementation class of the durable service.
  2. DurableOperation: To decorate the service method of the durable services. This attribute allows specifying two Boolean properties.

    1. CanCreateInstance: If this property is set to true then the respective method will create and store the instance in the database when called by the client.
    2. CompletesInstance: If this property is set to true then the respective method will delete the instance in the database when called by the client.

DurableService and DurableOperation attribute will be available only after adding the reference to System.WorkflowServices is added to the WCF service application.



Durable Services in Windows Communication Foundation (WCF)

Next is the configuration step in the durable service development. Below is the config section that needs to be placed in the Web.Config file of the WCF application.

  <connectionStrings>
  		<add name="DurableServiceDbConnectionString" connectionString="ConnectionStringGoesInHere"/>
  	</connectionStrings>
  	<system.serviceModel>
  		<services>
  			<service behaviorConfiguration="WcfDurableService.Service1Behavior" name="WcfDurableService.AccountingService">
  				<endpoint address="" binding="wsHttpContextBinding" contract="WcfDurableService.IAccountingService">
  				</endpoint>
  			</service>
  		</services>
  		<behaviors>
  			<serviceBehaviors>
  				<behavior name="WcfDurableService.Service1Behavior"  >
  					<serviceMetadata httpGetEnabled="true" />
  					<serviceDebug includeExceptionDetailInFaults="true" />
  					<serviceCredentials>
  						<windowsAuthentication allowAnonymousLogons="true" includeWindowsGroups="true" />
  					</serviceCredentials>
  					<persistenceProvider
  						     type="System.ServiceModel.Persistence.SqlPersistenceProviderFactory, System.WorkflowServices, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
  							 persistenceOperationTimeout="00:00:20"
  					         connectionStringName="DurableServiceDbConnectionString"
  							 lockTimeout="00:01:00"
  							 serializeAsText="true"
  					/>
  				</behavior>
  			</serviceBehaviors>
  		</behaviors>
  </system.serviceModel>

The connection string for the SQL Server Express database has to be provided and under the behavior section persistenceProvider has to be mentioned as shown in the above configuration section. The connection string name to connect to the SQL Express database is also mentioned in the persistenceProvider section.

The binding to be used on the client and WCF service should be wsHttpContextBinding. This binding allows WCF durable service to exchange the instance GUID between the client and server.

Client Application

As a first step in the client application add the service reference and name the proxy as AccountingService. Below is the Main method code. I have implemented in such a way that it will operate on the same instance until and unless you opt to clear it.

  class Program
  {
          static AccountingServiceClient _client;
          static void Main(string[] args)
          {
              _client = new AccountingServiceClient();
              _client.PersistInstance();
              Console.WriteLine("Instance XML persisted to the database!");
  
              while (true)
              {
                  Console.WriteLine("Do you want to clear the instanse? (Y/N)");
                  string clearInstance = Console.ReadLine();
                  if (clearInstance.ToUpper().Equals("Y"))
                  {
                      _client.ClearInstance();
                      Console.WriteLine("Instance XML deleted from the database!");
                      break;
                  }
                  else
                  {
                      Console.WriteLine("Please enter the amount to deposit: ");
                      _client.AddAmount(Convert.ToInt64(Console.ReadLine()));
                      Console.WriteLine("Total fund available: {0}", _client.GetTotalAmount());
                  }
              }
  
              Console.ReadLine();
          }
  }

When the instance is created by calling _client.PersitInstance() method go to your SQL server management studio and query the InstanceData table.

Fig 1.0 shows the record created in the DurableServiceDb.

[record1.jpg]
Fig 1.0

Run the application and Fig 1.1 shows the output window.

[wcf1.jpg]
Fig 1.1

Try restarting the WCF service and you will be surprised to see the persistence of the data happening on the service side. If you need to make the client to be durable as well then you have to set the InstanceId explicitly to the IContextManager on the client.

Conclusion

Hope this article clearly describes about WCF durable services, the way it works and steps involved in developing it. I have also attached the sample application's source code which you can download for your reference. If you have any doubts or concerns regarding the article then please make use of the comments sections.

Happy Reading!

Related Articles





About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

  • On-demand Event Event Date: October 23, 2014 Despite the current "virtualize everything" mentality, there are advantages to utilizing physical hardware for certain tasks. This is especially true for backups. In many cases, it is clearly in an organization's best interest to make use of physical, purpose-built backup appliances rather than relying on virtual backup software (VBA - Virtual Backup Appliances). Join us for this webcast to learn why physical appliances are preferable to virtual backup appliances, …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds