Archive for the ‘Uncategorized’ Category

Building The Repository

In my last post I had discussed about the various O/R mapping patterns and Repository is one of them.In this post we will develop a repository library for our sample application.This application is a very list of personal bookmarks with an url and description.

Step1: Create the database table

The database contains a single table called Bookmarks as shown below:

CREATE TABLE [dbo].[Bookmarks](
    [BookmarkId] [int] IDENTITY(1,1) NOT NULL,
    [Url] [varchar](100) COLLATE Latin1_General_CI_AI NOT NULL,
    [Description] [text] COLLATE Latin1_General_CI_AI NOT NULL,
CONSTRAINT [PK_Bookmarks] PRIMARY KEY CLUSTERED
(
    [BookmarkId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

(more…)

Advertisements

In my earlier post I explained the different types of behaviors available in the WCF framework.In this post we will discuss about how to develop a custom operation invoker.Now the obvious question is what is an operation invoker.Operation invoker is the class responsible invoking the service method with a set of parameters and generate the output parameters and return value.The class responsible for this needs to implement the System.ServiceModel.Dispatcher.IOperationInvoker interface.This interface defines the following methods

  1. AllocateInputs – Returns an array of parameters required for the method call.
  2. Invoke – This method accepts the instance of the service object,array of parameter values ,array of output values as a parameters and returns the value returned by the service method.
  3. InvokeBegin – This is the asynchronous version of the Invoke method and initiates the call.
  4. InvokeEnd – This is the asynchronous version of the Invoke method and it completes the call.

Operation invoker is attached to the System.ServiceModel.DispatchOperation via the Invoker property.The default invoker provided by WCF framework for synchronous method call is System.ServiceModel.Dispatcher.SyncMethodInvoker.The custom invoker we are going to develop will be added to the DispatchOperation via Invoker property.

This custom invoker will provide a caching functionality.It will check that for a given set of parameters if output and return value exists in cache then it will use the cached values otherwise invoke the method and add results to cache.As a first step we will develop a class implementing IOperationBehavior and it will also wrap the instance of the default operation as shown below:

    public class CacheOperationInvoker:IOperationInvoker
    {
        /// <summary>
        /// This variable keeps a reference to the IOperationInvoker instance of DispatchOperation.
        /// </summary>
        private IOperationInvoker invoker;
        public CacheOperationInvoker(IOperationInvoker invoker)
        {
            this.invoker = invoker;
        }

    …………………
    }

We will now implement the logic to check from cache in the Invoke method as shown below:

public object Invoke(object instance, object[] inputs, out object[] outputs)
{

    //Generate Key method generates the key for cache store by concatenating the input params.
     string key = GenerateKey(inputs);

    //CacheOutput is a custom C# class that encapsulates the output parameter array and return value
     CacheOutput  item = null;
     object retval = null;
     outputs = null;
     if (!string.IsNullOrEmpty(key))
     {

        //Get from Cache
         item = CacheManager.GetItemFromCache(key) as CacheOutput ;
         if (item != null)
         {

            //return from Cache
             retval = item.ReturnValue;
             outputs = item.Outputs;
         }
         else
         {

            //Invoke the method using default invoker instance and set values in cache.
             retval = invoker.Invoke(instance, inputs, out outputs);
             item = new CacheOutput();
             item.Outputs = outputs;
             item.ReturnValue = retval;
             CacheManager.SetItemInCache(key, item);
         }
     }
     return retval;
}

Now we add a operation behavior and add our invoker to DispatchOperation as shown below:

public class CacheOperationBehavior:Attribute,IOperationBehavior
  {

      public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
      {
          //Get the instance of the default invoker
          IOperationInvoker invoker = dispatchOperation.Invoker;
          //Override with cache based invoker
          dispatchOperation.Invoker = new CacheOperationInvoker(invoker);
      }

  }

Finally the behavior can be added to the service as shown below:

[ServiceContract]
    public interface ICalculator
    {
        [OperationContract]
        [CacheOperationBehavior]
        int Add(int i, int j);
    }

The entire sample code can be found at:

http://code.msdn.microsoft.com/Project/Download/FileDownload.aspx?ProjectName=wcfsamples&DownloadId=4496

WCF Behavior

Posted: January 4, 2009 in Uncategorized, WCF
Tags: ,

I ended my last post on WCF Dispatcher extension points with the note that we need WCF behavior to attach the components extending WCF functionality to the runtime.In this post I will describe the various WCF behaviors and how they can be plugged into the WCF runtime.

There are 4 types of behaviors in WCF : Service ,Endpoint,Operation and Contract ,each with a different scope of effect.To create each of this behavior we need to implement a separate interface having the same methods with similar intentions but with different parameters.The purpose of these methods is described below:

  1. AddBindingParameters – This method is used to pass custom information to the binding.
  2. Validate – This method is used to validate the service description.
  3. ApplyDispatchBehavior/ApplyClientBehavior – This method is used to add the extension components to DispatchRuntime/ClientRuntime e.g. MessageInspector,ParameterInspectors etc.

The WCF behaviors can be added to the runtime using the following ways:

  • Programmatically – This I will discuss in details with the individual types of behavior
  • Attributes – In this case the behavior class needs to implement the corresponding behavior interface and extend the attribute class.Then that attribute needs to be applied to the service class implementing the ServiceContract as shown below:

         public class ServicePoolBehavior : Attribute,IServiceBehavior
         {
             …..
         }

          [ServiceContract]

          public interface ITest
          {
             …..
          }
         [ServicePoolBehavior(MaxPoolSize=10,MinPoolSize=2,IncrementSize=2)]

         public class Test:ITest
         {
            ……
         }

  • Configuration – Here we need to implement a custom behavior extension element by extending the System.ServiceModel.BehaviorExtensionElement class and then add the new behavior in the config as shown below:

         public class ServicePoolBehaviorExtensionElement:BehaviorExtensionElement
        {
          ………..

          …………..

          public override Type BehaviorType
           {
              get { return  typeof(ServicePoolBehavior); }
           }

           protected override object CreateBehavior()
           {
              ServicePoolBehavior behavior = new ServicePoolBehavior();
              behavior.MaxPoolSize = Convert.ToInt32( this.ElementInformation.Properties[“maxPoolSize”].Value);
              behavior.MinPoolSize = Convert.ToInt32( this.ElementInformation.Properties[“minPoolSize”].Value);
              behavior.IncrementSize =Convert.ToInt32( this.ElementInformation.Properties[“incrementSize”].Value);
              return behavior;
          }
      }

      <extensions>
            <behaviorExtensions>
                <add name=”poolBehavior” type=”SB.ServiceModel.Pool.ServicePoolBehaviorExtensionElement, SB.ServiceModel.Pool, Version=1.0.0.0,  Culture=neutral, PublicKeyToken=null” />
            </behaviorExtensions>
        </extensions>
        <behaviors>
            <serviceBehaviors>
                <behavior name=”testBehavior”>
                    <serviceDebug includeExceptionDetailInFaults=”true” />
                    <serviceMetadata httpGetEnabled=”true” httpGetUrl=”
http://localhost:9001/Meta” />
                    <poolBehavior minPoolSize=”2″ maxPoolSize=”10″ incrementSize=”2″/>
                </behavior>
            </serviceBehaviors>
        </behaviors>

Now we will discuss about the individual types of behaviors:

  • ServiceBehavior
    • Need to implement the System.ServiceModel.Description.IServiceBehavior interface.
    • This behavior applies for the entire service runtime including the ServiceHostBase.
    • This behavior can be added by attribute,configuration or code.The following snippet shows how we can add a service behavior programmatically:

                    using (ServiceHost host = new ServiceHost(typeof(SampleService.Test)))
                    {

                       SB.ServiceModel.Pool.ServicePoolBehavior behavior = new SB.ServiceModel.Pool.ServicePoolBehavior();
                       behavior.IncrementSize = 2;
                       behavior.MaxPoolSize = 10;
                       behavior.MinPoolSize = 2;
                       host.Description.Behaviors.Add(behavior);

                       …….

                  }

  • EndpointBehavior
    • Need to implement the System.ServiceModel.Description.IEndpointBehavior interface.
    • This behavior customizes the runtime of a particular endpoint and associated EndpointDispatcher object.
    • This behavior can be added by configuration or code.The following snippet shows how we can add a endpoint behavior programmatically:

                    foreach (ServiceEndpoint se in host.Description.Endpoints) se.Behaviors.Add(new CustomBehavior());

  • ContractBehavior
    • Need to implement the System.ServiceModel.Description.IContractBehavior interface.
    • This behavior customizes the runtime of a particular contract and associated DispatchRuntime/ClientRuntime object.
    • This behavior can be added by attribute or code.The following snippet shows how we can add a contract behavior programmatically:

                   foreach (ServiceEndpoint se in host.Description.Endpoints)
                   {
                        se.Contract.Behaviors.Add(new CustomBehavior);
                    }

  • OperationBehavior
    • Need to implement the System.ServiceModel.Description.IOperationBehavior interface.
    • This behavior customizes the runtime of a particular operation and associated DispatchOperation/ClientOperation object.
    • This behavior can be added by attribute or code.The following snippet shows how we can add a operation behavior programmatically:

                    foreach (ServiceEndpoint se in host.Description.Endpoints)
                    {
                          foreach (OperationDescription od in se.Contract.Operations)
                          {
                                  od.Behaviors.Add(new CustomBehavior);
                          }
                   }

With this much understanding what all different behaviors are available and how to hook them to the runtime we are ready to explore the individual extension points in details from next post onwards.

WS-Reliable Messaging

Posted: August 30, 2008 in Uncategorized, WCF
Tags:

In the next few posts I will be discussing about WCF Reliable Messaging.But prior to that, a discussion on the WS-Reliable Messaging(WS-RM) protocol is required to gain a better understanding.

Today’s Web Services are expected to work inspite of network failures and some sort of mechanism is required to ensure that messages are delivered properly inspite of such failures.Apart from that messages may be lost,duplicated or delivered in an incorrect order.WS-Reliable Messaging ensures guranteed message delivery between two endpoints.This is also referred to as the delivery assurance.There are four basic delivery assurances provided by the WS-RM

  • At Most Once – Message will be delivered at most once without duplication or error will be thrown in at least one endpoint.
  • At Least Once – Message will be delivered at least one point.
  • Exactly Once – Message will be delivered without duplication in at least one endpoint. 
  • Ordered – Messages will be delivered in the order in which they were sent.

The diagram below provides a simple view of the Reliable Messaging model.

 

  1. Application source is the endpoint that sends the message.
  2. The RM source transmits the message over the wire.
  3. The RM destination is the endpoint that receives the message and also sends an acknowledgement of the receipt.
  4. RM Destination also delivers the message to the Application destination or the end point that is supposed to receive the message.

WS-RM defines the spec to achieve this flow by introducing additional elements in the SOAP message header.The major elements are

  • Sequence – The sequence header block is key element used to track & assure message delivery.The main components of this are
    1. Identifier – This is an uniqueidentifier for the reliable session,which is used in all the subsequently exchanged messages.This is a must have element.
    2. MessageNumber – This is the ordinal position of the message within sequence.This is also a must have element.
    3. LastMessage – This indicates that a particular message is a last message in the sequence.

<wsrm:Sequence …>
<wsrm:Identifier …> xs:anyURI </wsrm:Identifier>
<wsrm:MessageNumber> xs:unsignedLong </wsrm:MessageNumber>
<wsrm:LastMessage/>
</wsrm:Sequence>

  • SequenceAcknowledgement – On sucessful receipt of a message RM Destination sends a SequenceAcknowledgement.This can passed as an indepdent message or can be piggybacked with a operation response.The key elements of this are
    • Identifier – This is the unique sequence identifier.This isa  must element.
    • AcknowledgementRange – Range of message numbers successfully received
    • Nack – Unreceived message in the sequence.

<wsrm:SequenceAcknowledgement …>
<wsrm:Identifier …> xs:anyURI </wsrm:Identifier>
[ <wsrm:AcknowledgementRange … Upper=”xs:unsignedLong” Lower=”xs:unsignedLong”/> + |
<wsrm:Nack> xs:unsignedLong </wsrm:Nack> + ] …
</wsrm:SequenceAcknowledgement>

  • CreateSequence – The RM Source creates the sequence by passing this message to the senders.
  • CreateSequenceResponse – The RM destination responds to a CreateSequence request using this header block.This includes the Identifier element.
  • SequenceTermination – After the RM Source receives acknowledgement of all the messages this message is sent out to inform the RM Destination that sequence will be terminated.based on this the RM Destination can release the resources.

The sequence of actions is somewhat like this:

The detailed specs can be found at:

specs.xmlsoap.org/ws/2005/02/rm/wsreliablemessaging.pdf

In the next post I will discuss about how WCF implements this Reliable Messaging….

Yesterday I have come across very interesting question:Should one use raw XML as string or Objects as parameters of methods for passing data between tiers.I mostly use objects for doing so.Initially I had a bias towards that approach.But after pondering over the subject I found that both the approaches has it’s own pros and cons and one should choose based mostly on the non functional requirements(performance/maintainability/developer expertise) for the system under discussion.

Object Approach

Pros

  1. All the advantages of object oriented programming and design can be very well used.Code will be simpler and very easy to understand.
  2. When used in WebMethods the schema will be extracted via wsdl as XSD and it will be easier for the client code to interpret the meaning and purpose of the object.

Cons

  1. When the object is to be passed beyond process/machine boundary it will be serialized.
    • For Web Services .NET Framework will be using the XML Serializer.
    • For Remoting it can be the Binary as well as the SOAP formatter
    • .NET XML Serialization internally generates an assembly at runtime for serialization.There will be one assembly per type passed to the constructor of the XMLSerializer constructor.Naturally there is a performance hit because of this.However this assemblies can be generated before hand using the tool SGen.exe.The detailed tips for improvement of XML Serialization can found in the patterns & practices guide.
  2. For any change in the object structure the proxies needs to updated.

 XML Approach

Pros

  1. No additional serialization overhead.
  2. For any change in the object structure the proxies needs not be updated.However this can sighted as a disadvantage as well as the client contract will hazy.Client has to know before the xml structure.There is should be some XSD validation in the service as well.

Cons

  1. Program will be complex as one has to use XMLDOM and Xpath to parse and read/write the values from/into the XML.

That’s all I can think of at this point.

But I would still prefer objects with XMLSerializer unless my performance requirements vs server infrastructure is not at all able to take the load.