Commit() public method

public Commit ( ) : void
return void
        public void ProcessData(int employeeId)
        {
            // There is not much processing logic here...
            // We are assuming that the organization has 50 employees with sequential Employee Ids
            // If the employeeId  > 50, we are sending an Http Status code of 500 (Internal Server Error) back to the client
            // else, we assume that the processing is successful and send an Http Status code of 200 (Successfull)
            ReceiveContext receiveContext;
            if (!ReceiveContext.TryGet(OperationContext.Current.IncomingMessageProperties, out receiveContext))
            {
                Console.WriteLine("ReceiveContext property was not found in the message...");
                return;
            }

            if (employeeId > 50)
            {
                // Abandon
                receiveContext.Abandon(TimeSpan.MaxValue);
            }
            else
            {
                // Complete in Transaction block.
                CommittableTransaction committableTransaction = new CommittableTransaction();
                Transaction.Current = committableTransaction;
                try
                {
                    receiveContext.Complete(TimeSpan.MaxValue);
                    committableTransaction.Commit();
                }
                catch
                {
                    committableTransaction.Rollback();
                    // If the transaction was not completed we call Abandon explicitly which sends an Http 500 to the client
                    receiveContext.Abandon(TimeSpan.MaxValue);
                }
            }
        }
		public void ExplicitTransaction6 ()
		{
		    ExceptionAssert.Throws<InvalidOperationException>(
		        delegate
		            {
		                CommittableTransaction ct = new CommittableTransaction();

		                IntResourceManager irm = new IntResourceManager(1);
		                irm.Value = 2;
		                ct.Commit();

		                ct.Commit();
		            });
		}
		public void EnlistmentCounts_CommittableTransaction()
		{
			var newGuid = Guid.NewGuid();
			for (int i = 0; i < 5; i++)
			{
				using (var tx = new CommittableTransaction(new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted }))
				using (new TxScope(tx, NullLogger.Instance)) // set ambient also!
				{
					System.Transactions.Transaction.Current.EnlistDurable(newGuid, new EnlistmentTracking(), EnlistmentOptions.None);
					System.Transactions.Transaction.Current.EnlistDurable(newGuid, new EnlistmentTracking(), EnlistmentOptions.None);

					tx.Commit();
				}

				Assert.That(EnlistmentTracking.EnlistmentCounts, Is.EqualTo(0).Or.EqualTo(1).Or.EqualTo(2));
			}
		}
Esempio n. 4
0
		public void Vol2_Dur1_Fail5 ()
		{
			CommittableTransaction ct = new CommittableTransaction ();
			IntResourceManager [] irm = new IntResourceManager [2];
			irm [0] = new IntResourceManager ( 1 );
			irm [1] = new IntResourceManager ( 3 );

			Transaction.Current = ct;
			irm [0].Type = ResourceManagerType.Durable;
			irm [0].FailSPC = true;
			irm [0].FailWithException = true;

			for ( int i = 0; i < 2; i++ )
				irm [i].UseSingle = true;

			/* Durable RM irm[2] does on SPC, so
			 * all volatile RMs get Rollback */
			
			using ( TransactionScope scope = new TransactionScope () ) {
				irm [0].Value = 2;
				irm [1].Value = 6;

				scope.Complete ();
			}

			try {
				ct.Commit ();
			}
			catch ( TransactionAbortedException e ) {
				Assert.IsNotNull ( e.InnerException, "Expected e.InnerException == NotSupportedException, but got None" );
				Assert.AreEqual ( typeof ( NotSupportedException ), e.InnerException.GetType (), "Expected e.InnerException == NotSupportedException, but got " + e.GetType () );

				irm [0].Check ( 1, 0, 0, 0, 0, 0, 0, "irm [0]" );
				irm [1].Check ( 0, 1, 0, 1, 0, 0, 0, "irm [1]" );
				try {
					ct.Commit ();
				}
				catch (InvalidOperationException x ) {
					Assert.IsNull ( x.InnerException);
					Transaction.Current = null;
					return;
				}
				Assert.Fail ( "Should not be reached" );
			}

			Assert.Fail ( "Expected TransactionAbortedException" );
		}
		public void RetryOnFailure()
		{
			using (var t = new CommittableTransaction())
			using (new TxScope(t, NullLogger.Instance))
			{
				t.EnlistVolatile(new ThrowingResource(true), EnlistmentOptions.EnlistDuringPrepareRequired);

				using (var c = GetConnection())
				using (var cmd = c.CreateCommand())
				{
					cmd.CommandText = "SELECT TOP 1 Val FROM Thing";
					var scalar = (double)cmd.ExecuteScalar();
					Console.WriteLine("got val {0}", scalar);
				}

				try
				{
					t.Commit();
					Assert.Fail("first commit should fail");
				}
				catch (ApplicationException)
				{
					Assert.That(t.TransactionInformation.Status, Is.EqualTo(TransactionStatus.Committed));
				}
			}
		}
Esempio n. 6
0
        private void button84_Click(object sender, EventArgs e)
        {
            CommittableTransaction tx = null;
            try
            {

                using (tx = new CommittableTransaction())
                {
                    using (SqlConnection conn1 = new SqlConnection(Properties.Settings.Default.NorthwindConnectionString))
                    {

                        using (SqlCommand myCommand = new SqlCommand())
                        {

                            myCommand.Connection = conn1;

                            conn1.Open();
                            conn1.EnlistTransaction(tx);


                            //Restore database to near it's original condition so sample will work correctly.
                            myCommand.CommandText = "DELETE FROM Region WHERE (RegionID = 100) OR (RegionID = 101)";
                            myCommand.ExecuteNonQuery();

                            //Insert the first record.
                            myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'MidWestern')";
                            myCommand.ExecuteNonQuery();


                            //測試交易失敗用
                            //Insert the first record.
                            myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'MidWestern')";
                            myCommand.ExecuteNonQuery();


                            //Insert the second record.
                            myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (101, 'MidEastern')";
                            myCommand.ExecuteNonQuery();


                            tx.Commit();

                            MessageBox.Show("trans. Successfully");
                        }
                    }
                }

            }


            catch (TransactionException ex)
            {
                MessageBox.Show(ex.Message);
                tx.Rollback();
            }
            catch (Exception ex)
            {

                MessageBox.Show("trans. roll back " + ex.Message);
            }
        }
Esempio n. 7
0
		public override int Delete(DataTable dt, string fname, DataColumnCollection colinfo)
		{
			int rlt = 0;
			string sqlmain = "delete from {0} ";
			string sqlwhere = " where {0} in ({1}) ";
			string sql, where, ids = "";
			LastException = null;
			foreach (DataRow row in dt.Rows)
			{
				if (dt.Columns.Contains(fname))
				{
					ids += "," + SqlHelper.MakeSafeFieldSql(row[fname].ToString(), colinfo[fname].ToString(), true);
				}
			}
			ids = ids.Substring(1);
			where = string.Format(sqlwhere, SqlHelper.MakeSafeFieldNameSql(fname), ids);
			sql = string.Format(sqlmain, SqlHelper.MakeSafeFieldNameSql(dt.TableName)) + where;
			Logger.Log(sql);
			CommittableTransaction ts = new CommittableTransaction();
			DbConnection conn = db.GetConnection();
			conn.Open();
			conn.EnlistTransaction(ts);
			ExecuteResult er = db.Execute(sql, conn, ts);
			rlt = er.IntRlt;
			if (er.Exception != null)
			{
				LastException = er.Exception;
				rlt = 0;
			}
			else
			{
				ts.Commit();
			}
			if (conn.State != ConnectionState.Closed)
			{
				conn.Close();
			}
			ts.Dispose();
			return rlt;
		}
		public void ExplicitTransaction2 ()
		{
			Assert.IsNull (Transaction.Current, "Ambient transaction exists (before)");
			CommittableTransaction ct = new CommittableTransaction ();
			Transaction oldTransaction = Transaction.Current;

			Transaction.Current = ct;

			IntResourceManager irm = new IntResourceManager (1);

			irm.Value = 2;
			using (TransactionScope scope = new TransactionScope ()) {
				Assert.AreEqual (ct, Transaction.Current, "#44");

				/* Not calling scope.Complete
				scope.Complete ();*/
			}

			Assert.AreEqual (TransactionStatus.Aborted, ct.TransactionInformation.Status, "#45");
			Assert.AreEqual (ct, Transaction.Current, "#46");
			Assert.AreEqual (1, irm.Actual, "#47");
			Assert.AreEqual (1, irm.NumRollback, "#48");
			irm.Check ( 0, 0, 1, 0, "irm" );
			Transaction.Current = oldTransaction;

			try {
				ct.Commit ();
			} catch (TransactionAbortedException) {
				return;
			}
			Assert.Fail ("Commit on an aborted transaction should fail");
		}
		public void ExplicitTransaction3 ()
		{
			Assert.IsNull (Transaction.Current, "Ambient transaction exists (before)");
			CommittableTransaction ct = new CommittableTransaction ();
			Transaction oldTransaction = Transaction.Current;

			Transaction.Current = ct;

			IntResourceManager irm = new IntResourceManager (1);

			using (TransactionScope scope = new TransactionScope (TransactionScopeOption.RequiresNew)) {
				Assert.IsTrue (ct != Transaction.Current, "Scope with RequiresNew should have a new ambient transaction");

				irm.Value = 3;
				scope.Complete ();
			}

			irm.Value = 2;

			Assert.AreEqual (3, irm.Actual, "#50");

			Assert.AreEqual (ct, Transaction.Current, "#51");
			ct.Commit ();
			Assert.AreEqual (2, irm.Actual, "#52");
			Transaction.Current = oldTransaction;
		}
		public void ExplicitTransactionCommit ()
		{
			Assert.IsNull (Transaction.Current, "Ambient transaction exists (before)");

			CommittableTransaction ct = new CommittableTransaction ();
			Transaction oldTransaction = Transaction.Current;
			Transaction.Current = ct;

			IntResourceManager irm = new IntResourceManager (1);
			irm.Value = 2;
			ct.Commit ();

			Assert.AreEqual (2, irm.Value, "#33");
			Assert.AreEqual (TransactionStatus.Committed, ct.TransactionInformation.Status, "#34");
			Transaction.Current = oldTransaction;
		}
		public void ExplicitTransaction1 ()
		{
			Assert.IsNull (Transaction.Current, "Ambient transaction exists (before)");
			CommittableTransaction ct = new CommittableTransaction ();
			Transaction oldTransaction = Transaction.Current;

			Transaction.Current = ct;

			IntResourceManager irm = new IntResourceManager (1);

			irm.Value = 2;

			using (TransactionScope scope = new TransactionScope ()) {
				Assert.AreEqual (ct, Transaction.Current, "#38");
				irm.Value = 4;
				scope.Complete ();
			}

			Assert.AreEqual (ct, Transaction.Current, "#39");
			Assert.AreEqual (TransactionStatus.Active, Transaction.Current.TransactionInformation.Status, "#40");
			Assert.AreEqual (1, irm.Actual, "#41"); /* Actual value */

			ct.Commit ();
			Assert.AreEqual (4, irm.Actual, "#42"); /* New committed actual value */
			Assert.AreEqual (TransactionStatus.Committed, Transaction.Current.TransactionInformation.Status, "#43");
			Transaction.Current = oldTransaction;
		}
		public void ExplicitTransaction16 ()
		{
			CommittableTransaction ct = new CommittableTransaction ();
			IntResourceManager irm0 = new IntResourceManager ( 3 );
			IntResourceManager irm = new IntResourceManager ( 1 );

			Assert.IsNull ( Transaction.Current );

			Transaction.Current = ct;

			irm.FailPrepare = true;
			irm.FailWithException = true;
			irm.Value = 2;
			irm0.Value = 6;

			try {
				ct.Commit ();
			} catch (TransactionAbortedException e) {
				Assert.IsNotNull ( e.InnerException, "Expected an InnerException of type NotSupportedException" );
				Assert.AreEqual ( typeof (NotSupportedException), e.InnerException.GetType (), "Inner exception should be NotSupportedException" );
				irm.Check ( 1, 0, 0, 0, "irm" );
				irm0.Check ( 0, 0, 1, 0, "irm0" );
				Transaction.Current = null;
				return;
			}
			 
			Assert.Fail ( "Should not be reached" );
		}
        public void Learn(Stream words)
        {
            var wordStream = new WordStream(words);
            LinkedList<string> wordHistory = new LinkedList<string>();
            for (int i = 0; i < 4; i++)
            {
                wordHistory.AddLast(String.Empty);
            }
            foreach (var word in wordStream)
            {
                using (var transaction = new CommittableTransaction())
                {
                    wordHistory.RemoveFirst();
                    wordHistory.AddLast(word);

                    HandleWord(word);
                    HandleTwoGram(wordHistory.AsEnumerable().Skip(2).Take(2).ToList());
                    var gram = HandleThreeGram(wordHistory.AsEnumerable().Skip(1).Take(3).ToList());
                    HandleFourGram(wordHistory.AsEnumerable().ToList(), gram);

                    context.SaveChanges();
                    transaction.Commit();
                }
            }
        }
		public void ExplicitTransaction6a ()
		{
		    ExceptionAssert.Throws<InvalidOperationException>(
		        delegate
		            {
		                CommittableTransaction ct = new CommittableTransaction();

		                IntResourceManager irm = new IntResourceManager(1);
		                irm.Value = 2;
		                ct.Commit();

		                /* Using a already committed transaction in a new 
                         * TransactionScope
                         */
		                TransactionScope scope = new TransactionScope(ct);
		            });
		}
		public void ExplicitTransaction13 ()
		{
			CommittableTransaction ct = new CommittableTransaction ();
			IntResourceManager irm = new IntResourceManager ( 1 );

			Assert.IsNull ( Transaction.Current );
			Transaction.Current = ct;
			irm.Value = 2;
			irm.FailPrepare = true;

			try {
				ct.Commit ();
			} catch ( TransactionAbortedException ) {
				Assert.AreEqual ( TransactionStatus.Aborted, ct.TransactionInformation.Status );
				try {
					ct.BeginCommit ( null, null );
				} catch (Exception) {
					Transaction.Current = null;
					return;
				}
				Assert.Fail ( "Should not be reached(2)" );
			}
			Assert.Fail ("Should not be reached");
		}
		public void ExplicitTransaction4 ()
		{
			Assert.IsNull (Transaction.Current, "Ambient transaction exists (before)");
			CommittableTransaction ct = new CommittableTransaction ();
			Transaction oldTransaction = Transaction.Current;

			/* Not setting ambient transaction 
			 Transaction.Current = ct; 
			 */

			IntResourceManager irm = new IntResourceManager (1);

			using (TransactionScope scope = new TransactionScope (ct)) {
				Assert.AreEqual (ct, Transaction.Current, "#53");

				irm.Value = 2;
				scope.Complete ();
			}

			Assert.AreEqual (oldTransaction, Transaction.Current, "#54");
			Assert.AreEqual (TransactionStatus.Active, ct.TransactionInformation.Status, "#55");
			Assert.AreEqual (1, irm.Actual, "#56"); /* Actual value */

			ct.Commit ();
			Assert.AreEqual (2, irm.Actual, "#57"); /* New committed actual value */
			Assert.AreEqual (TransactionStatus.Committed, ct.TransactionInformation.Status, "#58");

			irm.Check ( 1, 1, 0, 0, "irm");
		}
 private static byte[] CreateFixedPropagationToken()
 {
     if (fixedPropagationToken == null)
     {
         CommittableTransaction transaction = new CommittableTransaction();
         byte[] transmitterPropagationToken = TransactionInterop.GetTransmitterPropagationToken(transaction);
         try
         {
             transaction.Commit();
         }
         catch (TransactionException exception)
         {
             DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Information);
         }
         Interlocked.CompareExchange<byte[]>(ref fixedPropagationToken, transmitterPropagationToken, null);
     }
     byte[] destinationArray = new byte[fixedPropagationToken.Length];
     Array.Copy(fixedPropagationToken, destinationArray, fixedPropagationToken.Length);
     return destinationArray;
 }
		public void ExplicitTransaction6 ()
		{
			CommittableTransaction ct = new CommittableTransaction ();

			IntResourceManager irm = new IntResourceManager (1);
			irm.Value = 2;
			ct.Commit ();

			ct.Commit ();
		}
Esempio n. 19
0
		public override int Update(DataTable dt, string fname, DataColumnCollection colinfo, params string[] ignoreFields)
		{
			/*
				UPDATE Managers
				SET ManagerName = CASE id
					WHEN 6 THEN 'value'
					WHEN 7 THEN 'value'
					WHEN 8 THEN 'value'
				END
				WHERE id IN (6,7,8)"
			 */
			int rlt = 0;
			int vNextSubmitValue = vSubmitCount;
			string sqlmain = "update {0} set {1} ";
			string sqlset = " , {0} = case {1} {2} end ";
			string sqlwhen = " when {0} then {1} ";
			string sqlwhere = " where {0} in ({1}) ";
			string sets = "", ids = "", sql, where, whens;
			string tname = SqlHelper.MakeSafeFieldNameSql(dt.TableName);
			int i = 0, n = 0;
			LastException = null;

			CommittableTransaction ts = new CommittableTransaction();
			DbConnection conn = db.GetConnection();
			conn.Open();
			conn.EnlistTransaction(ts);

			while (i < dt.Rows.Count)
			{
				foreach (DataColumn col in dt.Columns)
				{
					whens = "";
					//foreach (DataRow row in dt.Rows)
					for (i = vNextSubmitValue - vSubmitCount; i < vNextSubmitValue; i++)
					{
						DataRow row = dt.Rows[i];
						if (!col.ColumnName.Equals(fname))
						{
							whens += string.Format(sqlwhen
								, SqlHelper.MakeSafeFieldSql(row[fname].ToString(), colinfo, dt.Columns[fname])
								, SqlHelper.MakeSafeFieldSql(row[col].ToString(), colinfo, col));
						}
						else
						{
							ids += ","
								+ SqlHelper.MakeSafeFieldSql(row[col].ToString(), colinfo, col);
						}
						if (i + 1 >= vNextSubmitValue)
						{
							break;
						}
						else if (i + 1 >= dt.Rows.Count)
						{
							break;
						}
					}
					if (!col.ColumnName.Equals(fname))
					{
						if (ignoreFields.Contains<string>(col.ColumnName))
						{
							continue;
						}
						sets += string.Format(sqlset, SqlHelper.MakeSafeFieldNameSql(col.ColumnName), SqlHelper.MakeSafeFieldNameSql(fname), whens);
					}
				}
				sets = sets.Substring(2);
				ids = ids.Substring(1);
				where = string.Format(sqlwhere, fname, ids);
				sql = string.Format(sqlmain, tname, sets) + where;
				Logger.Log(sql);
				ExecuteResult er = db.Execute(sql, conn, ts);
				rlt += er.IntRlt;
				if (er.Exception != null)
				{
					rlt = 0;
					LastException = er.Exception;
					break;
				}
				//rlt += Execute(sql, conn, ts);
				//if (LastException != null)
				//{
				//    rlt = 0;
				//    break;
				//}
				sets = "";
				where = "";
				ids = "";
				vNextSubmitValue += vSubmitCount;
				if (i + 1 >= dt.Rows.Count)
				{
					break;
				}
			}
			if (rlt != 0 && LastException == null)
			{
				ts.Commit();
			}
			if (conn.State != ConnectionState.Closed)
			{
				conn.Close();
			}
			ts.Dispose();
			return rlt;
		}
		public void ExplicitTransaction6a ()
		{
			CommittableTransaction ct = new CommittableTransaction ();

			IntResourceManager irm = new IntResourceManager ( 1 );
			irm.Value = 2;
			ct.Commit ();

			/* Using a already committed transaction in a new 
			 * TransactionScope
			 */
			TransactionScope scope = new TransactionScope ( ct );
		}
Esempio n. 21
0
		public override int Insert(DataTable dt, DataColumnCollection colinfo, params string[] ignoreFields)
		{
			/*
				insert into Managers(ManagerName)
				select 'a' union all
				select 'b' union all
				select 'c'
			 */
			int rlt = 0;
			int vNextSubmitValue = vSubmitCount;
			string sqlmain = "insert into {0} ({1}) {2}";
			string sqlsel = " union all select {0} ";
			string cols = "", sels = "", sql;
			string tname = SqlHelper.MakeSafeFieldNameSql(dt.TableName);
			int i = 0;
			LastException = null;

			foreach (DataColumn col in dt.Columns)
			{
				if (!ignoreFields.Contains<string>(col.ColumnName))
				{
					cols += "," + SqlHelper.MakeSafeFieldNameSql(col.ColumnName);
				}
			}
			cols = cols.Substring(1);
			CommittableTransaction ts = new CommittableTransaction();
			DbConnection conn = db.GetConnection();
			conn.Open();
			conn.EnlistTransaction(ts);

			while (i < dt.Rows.Count)
			{
				for (; i < dt.Rows.Count; i++)
				{
					DataRow row = dt.Rows[i];
					string vals = "";
					foreach (DataColumn col in dt.Columns)
					{
						if (!ignoreFields.Contains<string>(col.ColumnName))
						{
							string val = row[col].ToString();
							vals += "," + SqlHelper.MakeSafeFieldSql(val, colinfo, col) + " ";
						}
					}
					sels += string.Format(sqlsel, vals.Substring(1));
					if (i + 1 >= vNextSubmitValue)
					{
						vNextSubmitValue += vSubmitCount;
						break;
					}
				}

				sels = sels.Substring(11);
				sql = string.Format(sqlmain, tname, cols, sels);
				Logger.Log(sql);
				ExecuteResult er = db.Execute(sql, conn, ts);
				rlt += er.IntRlt;
				if (er.Exception != null)
				{
					rlt = 0;
					LastException = er.Exception;
					break;
				}
				sels = "";
				i++;
			}
			if (rlt != 0 && LastException == null)
			{
				ts.Commit();
			}
			if (conn.State != ConnectionState.Closed)
			{
				conn.Close();
			}
			ts.Dispose();
			return rlt;
		}
		public void ExplicitTransaction6b ()
		{
			CommittableTransaction ct = new CommittableTransaction ();

			IntResourceManager irm = new IntResourceManager ( 1 );
			
			Transaction.Current = ct; 

			TransactionScope scope1 = new TransactionScope ();
			/* Enlist */
			irm.Value = 2;

			scope1.Complete ();

			try {
				ct.Commit ();
			} catch (TransactionAbortedException) {
				irm.Check ( 0, 0, 1, 0, "irm" );
				
				scope1.Dispose ();
				Transaction.Current = null;
				return;
			}
			Assert.Fail ( "Commit should've failed" );
		}
		public void ExplicitTransactionWithDependentTransaction()
		{
			using (var t = new CommittableTransaction())
			using (new TxScope(t, NullLogger.Instance))
			{
				Console.WriteLine("T1 STATUS: {0}", t.TransactionInformation.Status);

				using (var c = GetConnection())
				using (var cmd = c.CreateCommand())
				{
					cmd.CommandText = "SELECT TOP 1 Val FROM Thing";
					var scalar = (double)cmd.ExecuteScalar();
					Console.WriteLine("T1 STATUS: {0}", t.TransactionInformation.Status);
					Console.WriteLine("got val {0}, disposing command and connection", scalar);
				}

				using (var t2 = t.DependentClone(DependentCloneOption.RollbackIfNotComplete))
				using (new TxScope(t2, NullLogger.Instance))
				using (var c = GetConnection())
				using (var cmd = c.CreateCommand())
				{
					t2.TransactionCompleted +=
						(s, ea) =>
						Console.WriteLine("::: T2 TransactionCompleted: {0}", ea.Transaction.TransactionInformation.LocalIdentifier);
					cmd.CommandText = "DELETE FROM Thing";
					Console.WriteLine("T2: EXECUTING NON QUERY");
					cmd.ExecuteNonQuery();

					Console.WriteLine("T2: Enlisting volatile");
					t2.EnlistVolatile(new VolatileResource(false), EnlistmentOptions.None);

					Console.WriteLine("T2: COMPLETE-CALL");
					t2.Complete();
					Console.WriteLine("T2 STATUS: {0}", t2.TransactionInformation.Status);
				}

				Console.WriteLine("T1: COMMITTING, status: {0}", t.TransactionInformation.Status);
				try
				{
					t.Commit();
				}
				catch (TransactionAbortedException e)
				{
					Console.WriteLine("TransactionAbortedException, {0}", e);
					t.Rollback(e);
				}
				Console.WriteLine("T1 STATUS: {0}", t.TransactionInformation.Status);
				Console.WriteLine("T1: DISPOSING");
			}
		}
		public void ExplicitTransaction7 ()
		{
			CommittableTransaction ct = new CommittableTransaction ();

			IntResourceManager irm = new IntResourceManager (1);
			irm.Value = 2;
			ct.Commit ();
			/* Cannot accept any new work now, so TransactionException */
			ct.Rollback ();
		}
		public void ExplicitTransaction()
		{
			using (var t = new CommittableTransaction())
			using (new TxScope(t, NullLogger.Instance))
			{
				using (var c = GetConnection())
				using (var cmd = c.CreateCommand())
				{
					cmd.CommandText = "SELECT TOP 1 Val FROM Thing";
					var scalar = (double)cmd.ExecuteScalar();
					Console.WriteLine("got val {0}", scalar);
				}
				Console.WriteLine("COMMITTING");
				t.Commit();
				Console.WriteLine("DISPOSING");
			}
		}
		public void ExplicitTransaction8a ()
		{
			CommittableTransaction ct = new CommittableTransaction ();

			IntResourceManager irm = new IntResourceManager ( 1 );
			using ( TransactionScope scope = new TransactionScope ( ct ) ) {
				irm.Value = 2;
				scope.Complete ();
				/* FIXME: Why TransactionAbortedException ?? */
				try {
					ct.Commit ();
				}
				catch ( TransactionAbortedException) {
					irm.Check ( 0, 0, 1, 0, "irm" );
					return;
				}
				Assert.Fail ( "Should not be reached" );
			}
		}
Esempio n. 27
0
		public void TransactionDispose3 ()
		{
			CommittableTransaction ct = new CommittableTransaction ();
			IntResourceManager irm = new IntResourceManager (1);

			try {
				Transaction.Current = ct;
				irm.Value = 5;
				ct.Commit ();
				ct.Dispose ();
			} finally {
				Transaction.Current = null;
			}

			irm.Check (1, 1, 0, 0, "Dispose transaction");
			Assert.AreEqual (5, irm.Value);
		}
		public void ExplicitTransaction10a ()
		{
			CommittableTransaction ct = new CommittableTransaction ();

			IntResourceManager irm = new IntResourceManager ( 1 );
			Transaction.Current = ct;
			irm.Value = 2;
			Transaction.Current = null;

			TransactionScope scope = new TransactionScope ( ct );
			Assert.AreEqual ( ct, Transaction.Current, "ambient transaction" );
			Transaction.Current = null;
			//scope2.Complete ();
			//scope2.Dispose ();
			try {
				ct.Commit ();
			}
			catch ( TransactionAbortedException) {
				irm.Check ( 0, 0, 1, 0, "irm" );
				Transaction.Current = null;
				return;
			}

			Transaction.Current = null;
			Assert.Fail ();
		}
		public void IfOneWorks_AndOneFails_FirstShouldRollback()
		{
			var newGuid = Guid.NewGuid();
			for (int i = 0; i < 5; i++)
			{
				using (var tx = new CommittableTransaction(new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted }))
				using (new TxScope(tx, NullLogger.Instance)) // set ambient also!
				{
					var first = new AnotherEnlistment(false);
					System.Transactions.Transaction.Current.EnlistDurable(newGuid, first, EnlistmentOptions.None);
					var second = new AnotherEnlistment(true);
					System.Transactions.Transaction.Current.EnlistDurable(newGuid, second, EnlistmentOptions.None);

					try
					{
						tx.Commit();
						Assert.Fail("we have a failing resource");
					}
					catch (TransactionAbortedException)
					{
						Assert.That(second.RolledBack, Is.False);

						first.HasRolledBack.WaitOne();
						Assert.That(first.RolledBack, Is.True);
					}
				}
			}
			
		}
        private void ExecutePolling()
        {
            string dataAvailableStatement = Connection.ConnectionFactory.Adapter.DataAvailableStatement;
            string getDataStatement = Connection.ConnectionFactory.Adapter.GetDataStatement;
            string endOperationStatement = Connection.ConnectionFactory.Adapter.EndOperationStatement;

            bool dataAvailable = true;

            if (!string.IsNullOrWhiteSpace(dataAvailableStatement))
            {
                using (var connection = Connection.CreateDbConnection())
                {
                    connection.Open();

                    var dataAvailableCommand = connection.CreateCommand();
                    dataAvailableCommand.CommandText = dataAvailableStatement;

                    int? count = dataAvailableCommand.ExecuteScalar() as int?;
                    dataAvailable = count.HasValue && (count > 0);
                }
            }

            if (dataAvailable)
            {
                bool goOn = Connection.ConnectionFactory.Adapter.PollWhileDataFound;

                do
                {
                    if (queue.IsAddingCompleted)
                        return;

                    var connection = Connection.CreateDbConnection();
                    connection.Open();

                    var transaction = new CommittableTransaction(new TransactionOptions { IsolationLevel = Connection.ConnectionFactory.Adapter.IsolationLevel });
                    connection.EnlistTransaction(transaction);

                    var getDataCommand = connection.CreateCommand();
                    getDataCommand.CommandText = getDataStatement;

                    using (var reader = getDataCommand.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            queue.Add(new MessageItem
                            {
                                Message = DbHelpers.CreateMessage(reader, Connection.ConnectionFactory.Adapter.UseAmbientTransaction ? transaction : null, action),
                                Connection = connection,
                                Transaction = transaction,
                                EndOperationStatement = endOperationStatement
                            });
                        }
                        else
                        {
                            transaction.Commit();
                            connection.Close();

                            goOn = false;
                        }
                    }
                } while (goOn);
            }
        }