Archive for August, 2008

In my last post I had discussed about the basics of transactions,transaction manager & resource manager.In this post we will discuss about the Lightweight Transaction Manager(LTM) a transaction manager introduced with .NET 2.0.
Prior to LTM the only transaction manager available in the Microsoft world was the Micrsoft Distributed Transaction Coordinator(MSDTC).This transaction manager is able to handle transaction flowing across process/machine/network boundaries.But MSDTC has it’s own overheads and which is not required for simple transactional scenarios.That’s why the LTM was introduced.
LTM can manage transactions with
a) Any number of volatile resource managers
b) Single durable resource manager
c) No flows across process/machine
When anyone of the above mentioned conditions is violated the transaction gets promoted/escalated to the MSDTC or Kernel Transaction Manager(introduced with Windows Vista)
One of the great features of LTM is management of volatile or in-memory resource managers.Using the classes/interfaces present in System.Transaction namespace we can make Plain old .NET Objects transaction aware.

The first important class to take note of is the Transaction.It contains methods used for implementing resource managers for enlistment. It also provides functionalities for cloning a transaction and controlling the current transaction context. We can get current transaction, if one is set, using the static Current property.
      tx = Transaction.Current;
            if (tx != null)
            {
               ….
            }
As we have seen in the earlier post transaction manager communicates with the resource managers.Each resource manager needs to enlist with the transaction manager for a particular transaction.For this the Transaction class provides two methods EnlistVolatile-for volatile resource managers and EnlistDurable for durable resource managers.
For custom resource managers to enlist in the transaction they have to implement the IEnlistmentNotification interface.This interface defines the contract that a resource manager should implement to provide two phase commit notification callbacks for the transaction manager upon enlisting for participation.
This interface specifies the following methods:
      
 This callback is invoked during the second phase of a transaction if the transaction is commited.
        public void Commit(Enlistment enlistment)
        {
            ….
        }
 This callback is invoked during the second phase of a transaction if the transaction is in doubt.
        public void InDoubt(Enlistment enlistment)
        {
            …
.
        }
 This notification method is invoked in the first phase when the transaction manager asks participants whether they can commit the transaction.

        public void Prepare(PreparingEnlistment preparingEnlistment)
        {
            …
        }
 This callback is invoked during the second phase of a transaction if the transaction is aborted.
        public void Rollback(Enlistment enlistment)
        {
           …
        }

    }
Another important class in TransactionScope.This class is used for marking a code block transactional.On instanting the TransactionScope the transaction manager which transaction to participate.This is guided by the TransactionScopeOption parameter.The ambient transaction is the transaction in whichcode executes.A reference to the ambient transaction can be obtained by Current property of the Transaction class.
If no exception occurs within the transaction scope (that is, between the initialization of the TransactionScope object and the calling of its Dispose method), then the transaction in which the scope participates is allowed to proceed. If an exception does occur within the transaction scope, the transaction in which it participates will be rolled back.When code completes all tasks the Complete method has to be called to inform that transaction manager that it is acceptable to commit the transaction. If this method is not called then transaction is aborted.

The following classes shows the sample and simple implementation of a transaction aware Hashtable:

   class TransactionHashtable
    {
        private Hashtable ht = null;
        private Transaction tx;
        private bool enListed = false;
        public TransactionHashtable()
        {
            ht = new Hashtable();
        }
        public void Add(object key, object value)
        {
            tx = Transaction.Current;
            if (tx != null)
            {
                if (!enListed)
                {
                    tx.EnlistVolatile(new HashtableEnlistor(ref ht), EnlistmentOptions.None);
                    enListed = true;
                }
            }
          
            ht.Add(key, value);
        }
        public IDictionaryEnumerator GetEnumerator()
        {
            return ht.GetEnumerator();
        }
    }

    class HashtableEnlistor : IEnlistmentNotification
    {
        Hashtable ht = null;
        Hashtable htOld = null;
        public HashtableEnlistor(ref Hashtable ht)
        {
            this.ht = ht;
            MemoryStream ms = new MemoryStream();
           
            IFormatter f = new BinaryFormatter();
            f.Serialize(ms, ht);
            ms.Position = 0;
            htOld = (Hashtable)f.Deserialize(ms);
        }
        #region IEnlistmentNotification Members

        public void Commit(Enlistment enlistment)
        {
            enlistment.Done();
        }

        public void InDoubt(Enlistment enlistment)
        {
            throw new NotImplementedException();
        }

        public void Prepare(PreparingEnlistment preparingEnlistment)
        {
            preparingEnlistment.Prepared();
        }

        public void Rollback(Enlistment enlistment)
        {
            ht.Clear();
            IDictionaryEnumerator en = htOld.GetEnumerator();
            while (en.MoveNext())
            {
                ht.Add(en.Key,en.Value);
            }
            enlistment.Done();
        }

        #endregion
    }

Transactions

Posted: August 4, 2008 in Transactions
Tags: ,

Transaction

By transaction we mean a group of tasks which are executed together.If anything goes wrong in any one of them then outcome of the entire set is rolled back.After rollback the system returns to it’s original state i.e. the state before execution of transaction started.Changes are only committed if all the tasks are completed without any problem or failure.

ACID Properties

  1. Atomic – This describes the all or nothing feature of transaction.For example a transaction in document upload may contain two steps saving the file in server disk and inserting a record for the document in database.Here the transaction will be successful if both file and database record is successfully saved,if there is a problem in any one operation none will be saved.
  2. Consistent- Transaction should always leave the system in consistent state.Think of the above example if the database record is saved and file is not then the system would have become inconsistent having metadata for document whose actual file is missing.
  3. Isolated-Transactions has to operate in isolation until they are complete.For example when the file is not saved yet,database record for document is saved and it is visible to other users in document list screen.Other user might click that link to find that no file is attached and it will appear like a phantom record.
  4. Durable-No information should be lost even if the machine goes down when a transaction is executing.

Distributed Transactions

A transaction when involves multiple persistent resources(e.g. databases) or spans across process/machine boundary is referred to as a distributed transaction.

Transaction Management

Transaction Management is neccessary to maintain the ACID properties of the distributed transaction.The two key components  of transaction management are:

  1. Transaction Manager – A transaction manager manages commit/abort and monitors status of each task by coordinating with the corresponding resource managers.
  2. Resource Manager – A resource manages state of a particular resource based on the instructions from the transaction manager.
    • Durable Resource Manager – Manages persistent resource
    • Volatile Resource Manager – Manages in-memory resource

Two Phase Commit(2PC) Protocol

Phase 1

  • Coordinator asks each of the resource managers to commit
  • Each resource manager responds whether they are about to commit or abort.
  • Coordinator collects the responses and decides whether to commit/rollback the transaction as a whole.

Phase2

  • Coordinator informs the resource manager it’s decision to commit/rollback
  • Resource managers acknolwdges the message to commit/rollback
  • Coordinator waits for acknowledgement of the resource managers

In a distributed transaction spanning across multiple server each server has  a local transaction manager and all resource managers in that server enlists with that local transaction manager.The local transaction managers in turn communicate with each other.There is superior/subordinate relationship  between each local transaction manager and the corresponding resource managers in that box.The local transaction manager of the server where the transaction is initiated is called root transaction manager or the global commit coordinator.So this is the root of the commit tree and the enlisted resource managers and other local transaction managers are it’s children.Each resource manager depends on it’s local transaction manager for commit/abort decision and each local transaction manager depends upon it’s superior transaction manager (if any) for the commit/abort decision.

The transaction manager maintains a log on disk. The log is a sequential file with transaction events. The transaction manager records transaction starts, enlistments, and commit decisions in the log. During normal processing, the transaction manager only writes to the log. However, if the transaction manager fails, it reads the log when it restarts to reconstruct the most recent state, using the log to make its state durable.

IIS Hosted WCF Services-Part I

Posted: August 3, 2008 in WCF
Tags: , ,

In all the host programs of WCF services we need to write the something like:

 using(ServiceHost host = new ServiceHost(typeof(<ServiceType>)))
            {
               
                host.Open();
                Console.WriteLine(“Service Started…”);
                Console.Read();
            }

The class System.ServiceModel.ServiceHost provides the functionality to host Windows
Communication Foundation (WCF) services.This is a derived class
of ServiceHostBase  and is used to load a service, configure endpoints, apply security
settings, and start listeners to handle incoming requests.The ServiceHost class creates a
ServiceDescription from the service type and configuration information and then uses
that description to create ChannelDispatcher objects for each endpoint in the description.

But while developing the IIS hosted services we need not write code for the host at all.
So how does the hosting functionalities mentioned above is taken care
when we are hosting the service in IIS?

For a WCF Service hosted in IIS we have the following flow:

1.The messages are directed to System.ServiceModel.Activation.HttpHandler
by the aspnet_isapi.dll
2.The HttpHandler depends upon the System.ServiceModel.Activation.WebServiceHostFactory
to create an instance of service host.The CreateServiceHost method of WebServiceHostFactory
creates an instance of WebserviceHost.

System.ServiceModel.Web.WebServiceHost class is derived from ServiceHost class.This class provides
extended ServiceHost functionality for IIS Hosted Services.If there are no endpoints configured then
it automatically creates a default endpoint at the service’s base address for HTTP and HTTPS base
addresses. It does not create an endpoint automatically if the user has configured an endpoint
explicitly at the base address. WebServiceHost automatically configures the endpoint’s binding to
work with the associated Internet Information Services (IIS) security settings when used in a
secure virtual directory.WebServiceHost class also adds the WebHttpBehavior to all endpoints
that does not have the behavior.