Pradeep Loganathan

Distributed
posts - 17 , comments - 74 , trackbacks - 1

Friday, August 25, 2006

WS-Trust -- 7

A SOAP message using WS-Security is protected by security tokens. These security tokens can be obtained in a variety of ways such as username/password or x509 certificate, Kerberos e.t.c. Even though the SOAP message is now protected the recipient may not be able to use the token due to

1. Security token format incompatibility: The recipient may find the token format incompatible.

2. Security token trust: Even if the recipient can understand and process the token the recipient may be unable to map the trust hierarchy of the token to its own.

3. Namespace: The recipient may be unable to understand the claims within the token.

 

WS-trust aims to address these issues by defining a request/response protocol and by introducing a security token service. WS-Trust defines standard mechanisms for

Security token creation, management, exchange and also for establishing trust relationships.  WS-Trust thus builds upon WS-Security.

 

The Security Token Service (STS) is responsible for Token Issuance, Validation, Renewal & exchange. The requests are sent as RequestSecurityToken (RST) message specifying the operation type (Issue, Validate e.t.c) and the token type can also be specified optionally. WS-Trust defines further extensions to the RST message specifying delegation, forwarding and proxy requirements for the tokens. In addition lifetime and renewal requirements can also be specified.

The request structure is as follows

 

<RequestSecurityToken>                                 àRequest Header

        <TokenType>...</TokenType>                àDefines the security token type(X509…)

        <RequestType>...</RequestType>           àDefines the request type( Issue , cancel ..)

        <Base>...</Base>                                    àReference tokens

        <Supporting>...</Supporting>                  àsupporting tokens

 </RequestSecurityToken>

 


 

A sample RequestSecurityToken(RST) message is as follows

 

<wst:RequestSecurityToken>

<wst:TokenType>

http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1

</wst:TokenType>

<wst:RequestType>

http://schemas.xmlsoap.org/ws/2005/02/trust/Issue

</wst:RequestType>

</wst:RequestSecurityToken>

 

 

 

The response is returned as RequestSecurityTokenResponse(RSTR) containing the security token. The response structure is as follows

 

<RequestSecurityTokenResponse>                   àResponse Header.

        <TokenType>...</TokenType>                àThe token type returned.

        <KeyType>...</KeyType>                       àThe Key used in the token.

        <KeySize>...</KeySize>              àThe key size.

        <wsp:AppliesTo>...</wsp:AppliesTo>      àThe scope to which the token applies

        <RequestedSecurityToken>...                   àThe security token

           </RequestedSecurityToken>                  

        <RequestedProofToken>...                      àProof of possession token

            </RequestedProofToken>

</RequestSecurityTokenResponse>

 

A sample RSTR message is given below

<wst:RequestSecurityTokenResponse>

<wst:TokenType>

http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1

</wst:TokenType>

<wst:RequestedSecurityToken>

<saml:Assertion...>...</saml:Assertion>

</wst:RequestedSecurityToken>

<wst:RequestedProofToken>

<xenc:EncryptedKey>...</xenc:EncryptedKey>

</wst:RequestedProofToken>

</wst:RequestSecurityTokenResponse>

Posted On Friday, August 25, 2006 12:11 PM | Comments (0) | Filed Under [ WCF WS-Security ]

Monday, August 7, 2006

XML Encryption - 4

XML encryption is used to ensure confidentiality of XML documents. With XML encryption you can either encrypt the whole XML document or just portions of the document. The .net implementation of XML encryption is totally w3c compliant.

XML encryption scores over transport level security in two areas by ensuring that only certain portions of the document can be encrypted and  also ensuring that the document is secure through its lifetime.

Posted On Monday, August 7, 2006 8:02 AM | Comments (0) | Filed Under [ WS-Security ]

XML Encryption - Sample - 5

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Xml;

using System.Security;

using System.Security.Cryptography;

using System.Security.Cryptography.Xml;

 

namespace XMLDIGSIG

{

    class Class1

    {

 

        static void Main(string[] args)

        {

 

            TripleDES tdes = new TripleDESCryptoServiceProvider();

            EncryptXML(tdes);

            DecryptXML(tdes);

            Console.ReadKey();

        }

 

 

        public static void EncryptXML(TripleDES tdes)

        {

            try

            {

                XmlDocument doc = new XmlDocument();

                doc.Load("xmlfile1.xml");

                EncryptedXml encxml = new EncryptedXml(doc);

 

 

 

                byte[] encpayment = encxml.EncryptData((XmlElement)doc.SelectSingleNode("/order/payment"), tdes, false);

 

 

                EncryptedData ed = new EncryptedData();

                ed.EncryptionMethod = new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl);

                ed.Type = EncryptedXml.XmlEncElementUrl;

                ed.CipherData = new CipherData();

                ed.CipherData.CipherValue = encpayment;

                EncryptedXml.ReplaceElement((XmlElement)doc.SelectSingleNode("/order/payment"), ed, false);

                doc.Save("encxml.xml");

            }

            catch (CryptographicException ce)

            {

                Console.WriteLine(ce.ToString());

            }

        }

 

        public static void DecryptXML(TripleDES tdes)

        {

            try

            {

                XmlDocument doc = new XmlDocument();

                doc.Load("encxml.xml");

 

                XmlElement encelement = (XmlElement)(doc.GetElementsByTagName("EncryptedData")[0]);

 

                EncryptedData ed = new EncryptedData();

                ed.LoadXml(encelement);

 

                EncryptedXml exml = new EncryptedXml();

                byte[] decpay = exml.DecryptData(ed, tdes);

                exml.ReplaceData(encelement, decpay);

                doc.Save("decxml.xml");

            }

            catch(CryptographicException ce)

            {

                Console.WriteLine(ce.ToString());

            }

 

 

           

        }

    }

}

Posted On Monday, August 7, 2006 8:03 AM | Comments (0) | Filed Under [ WS-Security ]

Tuesday, August 8, 2006

SAML: Portable Identity, Authorization & Authentication - 6

As web services are increasingly crossing organizational and domain boundaries the problems of representing identity and its associated attributes across these boundaries is becoming more essential.  A system is secure if it knows all its users and all information is secure if the information is intact, non-tampered and can be proven to be confidential.

A payroll processing service may need to further interact with the service implemented by the HR systems and maybe with an external Banking service too. If all these services maintain and manage their own identification, authentication & authorization schemes the concept of secure interoperability would become complex and restrictive. A common way to represent & communicate identity & authorization across systems needed to be established.

SAML is the standard for web services for solving all the above problems.       

 

SAML is used to represent Identity using XML and this can then be attached to SOAP messages thereby making the identity portable SAML builds on this using other concepts called assertions. These assertions are made by identity providers and are consumed by service providers.

 

SAML Assertions:

Assertions contain claims or statements about an identity or subject. There are three types of statements

 

  1. Authentication statements: An authentication statement states that a particular authentication authority has authenticated the subject at a particular instant of time based on a particular authentication process
  2. Authorization decision statements: An authorization statement states that a particular authorization authority has granted or denied permission to the subject to act on a particular resource within a specific period of time.
  3. Attribute statements: An attribute statement provides additional information about an authentication/authorization assertion.

 

These assertions can be passed around between identity providers and service providers thus ensuring that the user need not provide his credentials to each and every service. The assertions are passed around based on a request response pair and a schema definition.

 

 

Authentication Assertion:

An authentication authority authenticates a subject based on a set of credentials and produces an authentication assertion specifying that s subject S was authenticated using an authentication mechanism M during time T.

An authentication assertion contains a element. This element contains the element specififying the authentication method used and the element specifying the instant the subject was authenticated.

 

An example of an authentication statement is below.

 

 

    AuthenticationMethod="urn:oasis:names:tc:SAML: 1.0:am:password"

    AuthenticationInstant="2006-07-03T12:06:00Z">

   

     

        Format="urn:oasis:names:tc:SAML:1.0:

assertion#emailAddress">pradeep@test.net

     

       

       

     

   

 

 

 

AuthorizationAssertion:

An authorization authority asserts that a subject S can be granted access of type A to a resource R based on the evidence E.

 

 xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion"

 MajorVersion="1" MinorVersion="1"

 Issuer="https://idp.org/saml/" ...>

 

 

   Decision="Permit"

   Resource="htts://company.com/resource ">

   read

   ...

 

 

Attribute Assertions:

An attribute assertion associates a subject S with additional attributes. Examples of additional attributes in a HR system maybe department name, Manager Name e.t.c

 

 

 

Since SAML is concerned with the making and enforcing decisions based on a set of policies the SAML architecture defines two types of roles namely Policy decision point (PDP) and a Policy enforcement point (PEP). A PDP makes authorization decisions based on the attributes and authentication statements and also based on the policy followed. The PEP is used when an enforcement decision is required. The PEP communicates with the PEP to retrieve the decisions.

Posted On Tuesday, August 8, 2006 7:18 AM | Comments (0) | Filed Under [ WS-Security ]

Wednesday, August 2, 2006

WS-Security Basics - 1

Web services can be secured using either Transport level security or Message level security. The main goal of transport level security is to establish a secure pipe between two endpoints and all messages that go into and out of the pipe are secured from point to point. The advantages of transport level security are

 

  1. The technologies for Transport level security are mature and well established.
  2. The technologies used are simpler and easier to administer.

 

The disadvantages are

  1. It only secures a message from point to point i.e. once a message leaves the secure pipe it is not secured.
  2. It does not provide and any control over the level of security on the message. i.e. The whole message is encrypted and we cannot set options about which part of the message should be encrypted and what should be in the clear.

 

Transport level security is mainly implemented by using SSL over HTTP. Message level security is much more complex and uses other technologies such as XML Signatures, XML Encryption, SAML e.t.c.

 

Message level security is more suited to implement Web services security. A SOAP message may pass through multiple SOAP nodes which may not be completely under your control. If we are using transport level security then we can only secure Messages between a few SOAP nodes under our control and then the message is in the clear. Another requirement may be that certain parts of the SOAP message must be visible to some of the SOAP nodes but should be opaque to the others. This level of control is not possible using transport level security. There are also other needs such as ensuring the integrity and confidentiality of the message which are all met by using Message level security. SOAP messages may also be logged and you would need to ensure the security of the message much beyond its transmission lifetime. All these require the usage of the technologies mentioned above namely XML signature, XML encryption e.t.c

 

Next : Foundations of Message Level Security

Posted On Wednesday, August 2, 2006 6:00 AM | Comments (0) |

Foundations of Message Level Security - 2

Foundations of Message Level Security

 

The main aim of securing Web services is to secure the messages sent and consumed by the services. This depends on using standards such as XML signature and XML encryption.

To understand XML signature and XML encryption we need to understand the principles of shared Key cryptography and public Key cryptography.

 

Shared Key Cryptography

 

Shared Key cryptography is used to ensure confidentiality of messages. Shared key technologies depend on the sender and the recipient of the message knowing a secret key. This secret key is then used to encrypt all messages between the sender and the receiver.

Shared key technology is faster but has problems with scalable key distribution.

Public Key cryptography

 

Public Key cryptography aims to solve the problem of Key distribution inherent in Shared key cryptography. Public key cryptography is used to ensure integrity, non-repudiation and authentication for messages. In public key cryptography the sending and the receiving parties do not need to know or share a secret key which can be intercepted in-between, rather public key cryptography relies on a pair of public and private keys which are mathematically related. One key is used for encryption and the other key is used to decrypt. The disadvantage of public keys cryptography is that it is very slow.

 

Posted On Wednesday, August 2, 2006 6:23 AM | Comments (0) |

XML signature - 3

XML signature and XML encryption are used to ensure the integrity & confidentiality of SOAP messages and are the basic pillars of WS-security.

 

A XML signature is a method of associating a Key to data using XML to represent the signature. XML signatures can be applied to any digital content. Once a XML document is signed any attempts to modify the contents of the XML document will result in failure of the verification.

A simple XML signature contains the following

  1. A reference to what is being signed
  2. The signature
  3. The Key used to verify the signature
  4. An optional object to represent miscellaneous items.

 

The structure of an XML signature is as below

 

   

        (CanonicalizationMethod)

        (SignatureMethod)

        (

            (Transforms)?

            (DigestMethod)

            (DigestValue)

        )+

   

    (SignatureValue)

    (KeyInfo)?

    (Object)*

 

There are three types of XML signatures based on the reference that is being signed namely

  1. Enveloping Signature
  2. Enveloped Signature
  3. Detached signature

 

An enveloping signature wraps the item that is being signed within it. An enveloped signature references to the parent element and a detached signature references an element outside signature elements hierarchy.

 

The process of generating a XML signature is as follows

  1. Reference Generation
    1. Calculate the digest value of the signed object.
    2. Create the reference element, the URI, the digest method used and the digest value.
  2. Signature generation
    1. Create the signedinfo element with the signature method, canonicalization method and the references.
    2. Canonicalize and calculate the signature value over signedinfo
    3. Construct the signature element including signedinfo and signature value

Posted On Wednesday, August 2, 2006 6:24 AM | Comments (0) |

Thursday, August 3, 2006

XML Signature Sample

using System.IO;

using System.Xml;

using System.Security;

using System.Security.Cryptography;

using System.Security.Cryptography.Xml;

namespace XMLDIGSIG

{

class Program

{

static void Main(string[] args)

{

SignXML();

ValidateXML();

Console.ReadKey();

}

private static void SignXML()

{

XmlDocument doc = new XmlDocument();

doc.Load("xmlfile1.xml");

SignedXml sx = new SignedXml(doc);

RSA Key = new RSACryptoServiceProvider();

sx.KeyInfo = new KeyInfo();

sx.KeyInfo.AddClause(new RSAKeyValue(Key));

sx.SigningKey = Key;

Reference refer = new Reference("");

refer.AddTransform(new XmlDsigEnvelopedSignatureTransform());

sx.AddReference(refer);

sx.ComputeSignature();

doc.DocumentElement.AppendChild(sx.GetXml());

doc.Save("Signedxml.xml");

}

private static void ValidateXML()

{

XmlDocument doc = new XmlDocument();

doc.Load("Signedxml.xml");

SignedXml verify = new SignedXml(doc);

verify.LoadXml((XmlElement)(doc.GetElementsByTagName("Signature")[0]));

if( verify.CheckSignature())

Console.WriteLine("Signature verified --- Match");

else

Console.WriteLine("Signature verified --- No Match");

}

}

}

Posted On Thursday, August 3, 2006 5:23 AM | Comments (0) |

Monday, March 27, 2006

SOA

The current trend with SOA required developers to reorient thier thinking in terms of messages and contracts and schemas rather than in terms of pure objects. This is a major change for a lot of dev's especially for people like me. so i am back to looking at schemas , contracts, undertanding wsdl & soap. While quite a few out there may argue that developers need not have to look at angular brackets and other stuff and  that it should be the infrastructure that should translate the object structure into the corresponsing building elements i still believe that there is nothing better than knowing whats happening behind the scenes. so looks like i will need to revisit all the stuff about XMLSchemas, WSDL, SOAP structures e.t.c

Posted On Monday, March 27, 2006 4:51 AM | Comments (0) |

Thursday, February 9, 2006

Two Phase Commit

To understand how a two phase commit works we need to understand all the actors involved in a two phase commit

 

  1. Resource Manager: A resource manager manages either a durable resource such as a database, (e.g. SQL Server), a queuing system (e.g.  MSMQ) or a volatile resource (e.g. in-memory transacted hash table) and provides facilities for the transaction manager for resource enlistment, delistment e.tc. A
  2. Transaction Manager: The transaction manager provides facilities for an application to initiate transactions and coordinates with all the resource managers involved in the transaction.

 

The transaction manager is the root of the transaction and coordinated between all the resource managers involved in the transactions. Now let’s see the phases and the steps involved in a two phase commit in a happy path transaction (i.e. everything commits).

 

  1. Commit-request phase:
    1. The TM asks all the resource managers to prepare for the transaction.
    2. All the RM’s prepare the transaction, maybe hold locks on the changes and record the entries in the respective redo and undo logs.
    3. All the RM’s respond back to the TM with a prepared message.
  2. Commit phase
    1. If all the RM’s responded with a prepared message then the TM writes a commit record to the commit log.
    2. The TM sends a commit message to all the RM’s.
    3. Each RM then commits the changes and releases all locks held.
    4. Each RM then sends a committed message to the TM.
    5. The TM writes a committed record to its log.
    6. The TM completes the transaction when all the RM’s have responded with a committed message.

 

Now let’s see the second scenario when a RM fails to make the changes durable as a result of which the transaction needs to be rolled back.

 

a.       A RM responds with an abort message.

b.      The TM sends a Rollback message to all the RM’s.

c.       Each RM then rollsback the transaction using the undo logs created in thye commit-request phase and releases any locks held.

d.      The TM completes the transaction when all the RM’s have responded with a rollback

 

Posted On Thursday, February 9, 2006 9:04 AM | Comments (0) |

Two Phase Commit

To understand how a two phase commit works we need to understand all the actors involved in a two phase commit

 

  1. Resource Manager: A resource manager manages either a durable resource such as a database, (e.g. SQL Server), a queuing system (e.g.  MSMQ) or a volatile resource (e.g. in-memory transacted hash table) and provides facilities for the transaction manager for resource enlistment, delistment e.tc. A
  2. Transaction Manager: The transaction manager provides facilities for an application to initiate transactions and coordinates with all the resource managers involved in the transaction.

 

The transaction manager is the root of the transaction and coordinated between all the resource managers involved in the transactions. Now let’s see the phases and the steps involved in a two phase commit in a happy path transaction (i.e. everything commits).

 

  1. Commit-request phase:
    1. The TM asks all the resource managers to prepare for the transaction.
    2. All the RM’s prepare the transaction, maybe hold locks on the changes and record the entries in the respective redo and undo logs.
    3. All the RM’s respond back to the TM with a prepared message.
  2. Commit phase
    1. If all the RM’s responded with a prepared message then the TM writes a commit record to the commit log.
    2. The TM sends a commit message to all the RM’s.
    3. Each RM then commits the changes and releases all locks held.
    4. Each RM then sends a committed message to the TM.
    5. The TM writes a committed record to its log.
    6. The TM completes the transaction when all the RM’s have responded with a committed message.

 

Now let’s see the second scenario when a RM fails to make the changes durable as a result of which the transaction needs to be rolled back.

 

a.       A RM responds with an abort message.

b.      The TM sends a Rollback message to all the RM’s.

c.       Each RM then rollsback the transaction using the undo logs created in thye commit-request phase and releases any locks held.

d.      The TM completes the transaction when all the RM’s have responded with a rollback

 

Posted On Thursday, February 9, 2006 8:53 AM | Comments (1) |

Friday, February 3, 2006

ServiceConfig

In .Net 1.1 it is possible to use the some of the services provided by System.EnterpriseServices without having to inherit from serviced component. For example of you want to use the transaction support functionality you could do this.

public void DoWork()

{

System.EnterpriseServices.ServiceConfig sc;

try

{

sc = new ServiceConfig();

sc.Transaction = TransactionOption.Required;

ServiceDomain.Enter(sc);

Work();

ContextUtil.SetComplete();

}

catch(Exception e)

{

Console.WriteLine(e.ToString());

ContextUtil.SetAbort();

}

finally

{

ServiceDomain.Leave();

}

}

 

private void Work()

{

//update databases

Console.WriteLine(ContextUtil.IsInTransaction.ToString());

Console.WriteLine(ContextUtil.TransactionId.ToString());

}

 

The ServiceConfig class specifies& configures the services that you would need. Here I am setting the transaction options of the serviceconfig class to ensure that I am in a transaction once I enter the domain.

Posted On Friday, February 3, 2006 3:44 AM | Comments (0) |

Tuesday, January 17, 2006

Transactions with MSDTC

Was playing around with MSDTC today and had a a big gotcha. If you get any issues with the distrubuted transaction check this. Go to Component services MMC and right click on My Computer --> Properties and then click on the MSDTC tab and then on Security configuration . Make sure that “Network DTC access ” is checked and so is “No authentication required”.

I have also posted some sample code for directly working on the MSDTC transactions.

#include <windows.h>

#include <stdio.h>

#include <oledb.h>

#include <oledberr.h>

#include <txdtc.h>

#include <xolehlp.h>

#include <sql.h>

#include <sqlext.h>

#include <Odbcss.h>

void main()

{

ITransactionDispenser *pTransactionDispenser;

ITransaction *pTransaction;

HRESULT hr = S_OK;

SQLHENV henv;

SQLHDBC hdbc1, hdbc2;

SQLHSTMT hstmt1, hstmt2;

SQLRETURN retcode;

SQLCHAR sqlstmt1[]="insert into TEST1 values('hello')";

SQLCHAR sqlstmt2[]="insert into TEST2 values('hello')";

SQLCHAR* theDiagState = new SQLCHAR[50];

SQLINTEGER theNativeState;

SQLCHAR* theMessageText = new SQLCHAR[255];

SQLSMALLINT iOutputNo;

hr = DtcGetTransactionManager(0, 0, IID_ITransactionDispenser, 0, 0, 0, (void**)&pTransactionDispenser);

if(FAILED(hr))

{

printf("Failed to get the transaction manager" );

}

 

SQLAllocEnv(&henv);

SQLAllocConnect(henv,&hdbc1);

SQLAllocConnect(henv,&hdbc2);

retcode = SQLConnect(hdbc1, (SQLCHAR*) "blrdevlabsvr12DSN", SQL_NTS,

(SQLCHAR*) "sa", SQL_NTS,

(SQLCHAR*) "", SQL_NTS);

if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)

printf("Connected to 1........");

retcode = SQLConnect(hdbc2, (SQLCHAR*) "seconddsn", SQL_NTS,

(SQLCHAR*) "sa", SQL_NTS,

(SQLCHAR*) "", SQL_NTS);

if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)

printf("Connected to 2........");

hr = pTransactionDispenser->BeginTransaction (NULL,ISOLATIONLEVEL_READCOMMITTED,ISOFLAG_RETAIN_DONTCARE, NULL, &pTransaction );

if (FAILED (hr))

{

printf("BeginTransaction failed: Error # %#x\n", hr);

exit(1); // Replace with specific error handling.

}

hr = SQLSetConnectAttr (hdbc1, SQL_COPT_SS_ENLIST_IN_DTC,(SQLPOINTER)pTransaction,SQL_IS_INTEGER);

if (hr != SQL_SUCCESS)

{

SQLGetDiagRec(SQL_HANDLE_DBC,hdbc1,1,(SQLCHAR*)theDiagState,&theNativeState,(SQLCHAR*)theMessageText,100,&iOutputNo);

printf( "Error :%s\n%d", theMessageText,iOutputNo);

}

hr = SQLSetConnectAttr (hdbc2, SQL_COPT_SS_ENLIST_IN_DTC,(SQLPOINTER)pTransaction,SQL_IS_INTEGER);

if (hr != SQL_SUCCESS)

{

SQLGetDiagRec(SQL_HANDLE_DBC,hdbc1,1,(SQLCHAR*)theDiagState,&theNativeState,(SQLCHAR*)theMessageText,100,&iOutputNo);

printf( "Error :%s\n", theMessageText);

}

 

retcode = SQLAllocStmt(hdbc1, &hstmt1);

retcode = SQLAllocStmt(hdbc2, &hstmt2);

retcode = SQLExecDirect(hstmt1,sqlstmt1, SQL_NTS);

if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)

printf("Executed 1........");

retcode = SQLExecDirect(hstmt2,sqlstmt2, SQL_NTS);

if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO)

printf("Executed 2........");

 

SQLFreeStmt(hstmt1,SQL_DROP);

SQLFreeStmt(hstmt2,SQL_DROP);

hr = pTransaction->Commit(FALSE,XACTTC_SYNC_PHASEONE,0);

SQLDisconnect(hdbc1);

SQLFreeConnect(hdbc1);

SQLDisconnect(hdbc2);

SQLFreeConnect(hdbc2);

SQLFreeEnv(henv);

}

I will be explaining this in my next post. It is pretty late out here :-(

 

 

Posted On Tuesday, January 17, 2006 12:27 PM | Comments (0) |

Friday, January 13, 2006

Problems with declarative model

The declarative model has the following problems

 

  1. Forces you to inherit from Serviced component limiting any class modeling that you may want to implement.
  2. Always makes use of MSDTC even if the transaction is local and restricted to only one resource. MSDTC is mainly used for transactions that span multiple resources and is a huge overhead on transactions involving only one resource.
  3. Forces you to use the COM+ model such as stateless objects et al.

Posted On Friday, January 13, 2006 7:19 AM | Comments (0) |

Problems with declarative model

The declarative model has the following problems

 

  1. Forces you to inherit from Serviced component limiting any class modeling that you may want to implement.
  2. Always makes use of MSDTC even if the transaction is local and restricted to only one resource. MSDTC is mainly used for transactions that span multiple resources and is a huge overhead on transactions involving only one resource.
  3. Forces you to use the COM+ model such as stateless objects et al.

Posted On Friday, January 13, 2006 6:25 AM | Comments (0) |

Declarative/Implicit Transactions in .Net 1.0/1.1:

 When transactions span across multiple resources each additional resource increases the chances of failure. For transactions spanning across multiple resources windows uses the MSDTC service. MSDTC coordinates between all the resource managers involved in the transaction using OLE TX .

 

namespace TestTrans1

{

    [Transaction]

    class Worker : ServicedComponent

    {

        public void DoWork()

        {

            string ConnectionString = "connection string";

            System.Data.IDbConnection Conn = new System.Data.SqlClient.SqlConnection(ConnectionString);

            System.Data.IDbCommand Cmd = new System.Data.SqlClient.SqlCommand();

            System.Data.IDbTransaction transaction = null;

           

            try

            {

                Conn.Open();

                Cmd.Connection = Conn;

                Cmd.CommandText = "your_insert_statement";

                Cmd.ExecuteNonQuery();

 

                Cmd.CommandText = "your_other_insert_statement";

                Cmd.ExecuteNonQuery();

 

                ContextUtil.SetComplete();

 

            }

            catch (System.Data.SqlClient.SqlException exception)

            {

                System.Console.WriteLine(exception.ToString());

                ContextUtil.SetAbort();

            }

            finally

            {

                Conn.Close();

            }

        }

    }

Posted On Friday, January 13, 2006 6:11 AM | Comments (0) |

Thursday, January 12, 2006

Explicit Transactions

Explicit Transactions: Explicit transactions are basically ADO.net based transactions where you need to explicitly enlist & manage a transaction. If you are transaction spans a single resource you should be using this . The sample below lists a Explicit transaction.

 

using System;

using System.Data.SqlClient;

 

namespace TransTest1

{

      class Class1

      {

           

            [STAThread]

            static void Main(string[] args)

            {

                  string ConnectionString = "";

 

                  System.Data.IDbConnection Conn = new System.Data.SqlClient.SqlConnection(ConnectionString);

                  System.Data.IDbCommand Cmd = new System.Data.SqlClient.SqlCommand();

                  System.Data.IDbTransaction transaction = null;

                 

                  try

                  {

                        Conn.Open();

                        transaction = Conn.BeginTransaction();

                 

                        Cmd.Connection = Conn;             

                        Cmd.Transaction = transaction;

 

                        Cmd.CommandText = "your_insert_statement";

                        Cmd.ExecuteNonQuery();

                        transaction.Commit();

 

 

                  }

                  catch(System.Data.SqlClient.SqlException exception)

                  {

                        System.Console.WriteLine(exception.ToString());

                        transaction.Rollback();

                       

                  }

                  finally

                  {

                        Conn.Close();

                  }

 

 

            }

      }

}

 

In this case BeginTransaction method of the connection object represents the underlying database transaction and allows the developer to either commit or rollback the transaction. Since this sort of a transaction involves a single resource it does not include a lot of overhead.

Posted On Thursday, January 12, 2006 8:43 AM | Comments (1) |

Powered by: