using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Transactions;

namespace PromoteTx
{
  class Program
  {
    static void Main(string[] args)
    {
      Promotable();
      DoesDistributed();
    }
    static void Promotable()
    {
      using (TransactionScope ts = new TransactionScope())
      {
        SqlConnection conn1 = new SqlConnection(
          "server=.;integrated security=sspi;database=pubs");
        // start local tx if SQL 2005, distributed tx if not
        conn1.Open();
        SqlCommand cmd1 = new SqlCommand(
           "INSERT jobs VALUES('job1', 10, 10", conn1);
        cmd1.ExecuteNonQuery();

        SqlConnection conn2 = new SqlConnection(
          "server=other;integrated security=sspi;database=pubs");
        // promote to distributed tx if SQL 2005
        conn2.Open();
        SqlCommand cmd2 = new SqlCommand(
           "INSERT jobs VALUES('job2', 10, 10", conn2);
        cmd2.ExecuteNonQuery();

        ts.Complete(); 
        // dispose SqlCommands and SqlConnections here
      } // commits transaction when TransactionStream.Dispose is called here

    }

    static void DoesDistributed()
    {
      using (TransactionScope ts = new TransactionScope())
      {
        SqlConnection conn1 = new SqlConnection(
          "server=.;integrated security=sspi;database=pubs");
        // start local tx if SQL 2005, distributed tx if not
        conn1.Open();
        SqlCommand cmd1 = new SqlCommand(
           "INSERT jobs VALUES('job1', 10, 10", conn1);
        cmd1.ExecuteNonQuery();
        // EXACT same connection string as the first one
        // second connection always causes promotion to distributed tx
        SqlConnection conn2 = new SqlConnection(
          "server=.;integrated security=sspi;database=pubs ");
        conn2.Open();
        SqlCommand cmd2 = new SqlCommand(
           "INSERT jobs VALUES('job2', 10, 10", conn2);
        cmd2.ExecuteNonQuery();

        ts.Complete(); // commit transaction 
        // dispose SqlCommands and SqlConnections here
      }

    }
  }
}
