public void ExternalTransactionViaADO() { MessageQueue queueA = new MessageQueue(); string ConnectionString = @"data source=AJGUSHC2DB08PD.ajgcodev.int\dev2;initial catalog=Learn;integrated security=True;"; SqlConnection conn = new SqlConnection(ConnectionString); try { queueA.Path = @"formatName:DIRECT=OS:corpvmdev67.ajgcodev.int\private$\TransactionalQ1"; queueA.Send("OrderA for Message", "Order A", MessageQueueTransactionType.Automatic); Random r = new Random(); int inserted = 0; string QryString = "insert into TestOrder values(" + r.Next(1, 10) + ",'" + DateTime.Now.ToString() + "','Order_" + r.Next(11, 100) + "')"; SqlCommand CmdObj = new SqlCommand(QryString, conn); conn.Open(); inserted = CmdObj.ExecuteNonQuery(); ContextUtil.SetComplete(); } catch (Exception ex) { using (EventLog eventLog = new EventLog("Application")) { eventLog.Source = "ExternalTransaction"; eventLog.WriteEntry("Error Getting " + ex.Message, EventLogEntryType.Error, 101, 1); } ContextUtil.SetAbort(); } finally { conn.Close(); queueA.Close(); } }
public void Log(int ID) { try { SqlConnection sqlConn = new SqlConnection("Integrated Security=SSPI;Initial Catalog=CarLot;Data Source=localhost;"); sqlConn.Open(); // Build a SQL statement based on incoming params. string myInsertQuery = string.Format(@"INSERT INTO CarsSold (CarID, DateSold) Values('{0}', {1}'", ID, DateTime.Today); // Configure SqlCommand type. SqlCommand sqlCmd = new SqlCommand(myInsertQuery); sqlCmd.Connection = sqlConn; // Insert the record. sqlCmd.ExecuteNonQuery(); sqlConn.Close(); ContextUtil.SetComplete(); } catch { ContextUtil.SetAbort(); } }
///<summary>dbAccess</summary> public void dbAccess(int pID1, int onOrder, int pID2, int inStock) { OleDbCommand oleDbCommand = null; OleDbConnection oleDbConnection = null; try { oleDbConnection = new OleDbConnection(DatabaseConnectionString); oleDbConnection.Open(); oleDbCommand = new OleDbCommand ( "UPDATE myProducts SET UnitsonOrder = " + onOrder + " WHERE productID = " + pID1, oleDbConnection ); oleDbCommand.ExecuteNonQuery(); oleDbCommand.CommandText = "UPDATE myProducts SET UnitsinStock = " + inStock + " WHERE productID = " + pID2; oleDbCommand.ExecuteNonQuery(); ContextUtil.SetComplete(); } catch (Exception ex) { ContextUtil.SetAbort(); System.Console.WriteLine("Exception: {0}", ex.Message); } }
private void AbortRunningTransaction() { if (ContextUtil.IsInTransaction) { ContextUtil.SetAbort(); } }
public void MyTestCleanup() { if (ContextUtil.IsInTransaction) { ContextUtil.SetAbort(); } }
private static void ClickEnroll() // This simulates input from a web form for enrollment { try { // Setup context ServiceConfig context = new ServiceConfig { Transaction = TransactionOption.Required }; ServiceDomain.Enter(context); // enter the transactional context (not using MTS) // Business Logic var courseReg = new CourseRegistrationR(); courseReg.RegisterStudent(); // Check success TransactionStatus status = ServiceDomain.Leave(); Console.WriteLine("Transaction result {0}. Enrollments: {1}, Open Seats: {2}", status, Helper.GetTotalEnrollments(), Helper.GetOpenSeats()); // TODO: Handle result accordingly } catch (Exception ex) { Console.WriteLine("Caught Exception: {0}", ex.Message); ContextUtil.SetAbort(); TransactionStatus status = ServiceDomain.Leave(); Console.WriteLine("Transaction result {0}", status); } }
public void BuyCar(int carID) { // Build a SQL statement based on incoming params. string myInsertQuery = string.Format("DELETE FROM Inventory WHERE CarID = '{0}'", carID); try { // Log car to be purchased. LogSale log = new LogSale(); log.Log(carID); log.Dispose(); // Configure SqlCommand type. SqlCommand sqlCmd = new SqlCommand(myInsertQuery); sqlCmd.Connection = sqlConn; sqlConn.Open(); // Delete the record. sqlCmd.ExecuteNonQuery(); // Update our context. // Could also call MyTransactionVote / DeactivateOnReturn // or use AutoCompleteAttribute. ContextUtil.SetComplete(); } catch { ContextUtil.SetAbort(); } }
public void TearDown() { if (ContextUtil.IsInTransaction) { ContextUtil.SetAbort(); } }
public void Insert(int orderId, OrderLine orderDetail) { var connection = new SqlConnection(connectionString); try { var command = connection.CreateCommand(); command.CommandText = "INSERT INTO [Order Details] (OrderId, " + "ProductId, UnitPrice, Quantity)" + "VALUES(@OrderId, @ProductId, @UnitPrice, @Quantity)"; command.Parameters.AddWithValue("@OrderId", orderId); command.Parameters.AddWithValue("@ProductId", orderDetail.ProductId); command.Parameters.AddWithValue("@UnitPrice", orderDetail.UnitPrice); command.Parameters.AddWithValue("@Quantity", orderDetail.Quantity); connection.Open(); command.ExecuteNonQuery(); } catch (Exception) { ContextUtil.SetAbort(); throw; } finally { connection.Close(); } ContextUtil.SetComplete(); }
public void TransactionTestCleanup() // 测试方法结束后,所有事务撤销 { if (ContextUtil.IsInTransaction) { ContextUtil.SetAbort(); } }
public void TransactionTest() { if (ContextUtil.IsInTransaction) //如果这个类是事务 { ContextUtil.SetAbort(); //撤销操作,相当于回滚操作 } }
public void Insert(int orderId, OrderLine orderLine) { SqlConnection northConnection = null; try { northConnection = new SqlConnection(_connectionString); SqlCommand insertCmd = northConnection.CreateCommand(); insertCmd.CommandText = "INSERT INTO [Order Details] (OrderId, ProductId, UnitPrice, Quantity) VALUES (@OrderId, @ProductId, @UnitPrice, @Quantity)"; insertCmd.Parameters.AddWithValue("@OrderId", orderId); insertCmd.Parameters.AddWithValue("@ProductId", orderLine.ProductId); insertCmd.Parameters.AddWithValue("@UnitPrice", orderLine.UnitPrice); insertCmd.Parameters.AddWithValue("@Quantity", orderLine.Quantity); northConnection.Open(); insertCmd.ExecuteNonQuery(); } catch (Exception) { ContextUtil.SetAbort(); throw; } finally { if (northConnection != null && northConnection.State != ConnectionState.Closed) { northConnection.Close(); } } ContextUtil.SetComplete(); }
// Debit the account, public void DebitAccount(int ammount) { // Create a new clerk using the AccountCompensator class. Clerk clerk = new Clerk(typeof(AccountCompensator), "An account transaction compensator", CompensatorOptions.AllPhases); // Create a record of previous account status, and deliver it to the clerk. int balance = AccountManager.ReadAccountBalance(filename); Object[] record = new Object[2]; record[0] = filename; record[1] = balance; clerk.WriteLogRecord(record); clerk.ForceLog(); // Perform the transaction balance -= ammount; AccountManager.WriteAccountBalance(filename, balance); // Commit or abort the transaction if (commit) { ContextUtil.SetComplete(); } else { ContextUtil.SetAbort(); } }
/// <summary> /// Rollback method set abort the current transaction. /// </summary> public virtual void Rollback() { //if it is part of a transaction, abort it. if (ContextUtil.IsInTransaction) { ContextUtil.SetAbort(); } }
public void Dispose() { if (!this.consistent) { //取消事务 ContextUtil.SetAbort(); } ServiceDomain.Leave(); }
//updates the detail quantity for the product. public bool UpdateDetailQuantity(int OrderID, string ProductName, int Quantity) { //grab the connection object SqlConnection currentConnection = CreateConnection(); //open the connection object currentConnection.Open(); try { //try to update the quantity //check to see if a transaction exists. //if not the throw an exception. if (!ContextUtil.IsInTransaction) { throw new Exception("Requires Transaction"); } //set the command text to be executed. string CommandText = "Update [Order Details] set Quantity = " + Quantity + " where OrderID = " + OrderID + " AND [Order Details].ProductID IN"; CommandText += "(Select ProductID from Products where ProductName = '" + ProductName + "')"; //create the command object and //set the connection property. SqlCommand sqlCommandToExecute = new SqlCommand(); sqlCommandToExecute.Connection = currentConnection; //set the command type and provide //the command text. sqlCommandToExecute.CommandType = CommandType.Text; sqlCommandToExecute.CommandText = CommandText; //execute the query. sqlCommandToExecute.ExecuteNonQuery(); //complete the transaction. ContextUtil.SetComplete(); return(true); } catch (Exception e) { //if an exception is thrown //close the connection object //and abort the transaction. currentConnection.Close(); ContextUtil.SetAbort(); return(false); } finally { //close the connection object. currentConnection.Close(); } }
public void TestMethod1() { ServiceDomain.Enter(new ServiceConfig()); ISomething something = MockRepository.Mock <ISomething>(); something.VerifyAllExpectations(); ContextUtil.SetAbort(); ServiceDomain.Leave(); }
public void SetAbort() { try { ContextUtil.SetAbort(); } catch (Exception e) { throw e; } }
public static void TransactionLeave() { Console.WriteLine("Attempting to Leave transactional context..."); if (ContextUtil.IsInTransaction) { // Abort the running transaction ContextUtil.SetAbort(); } ServiceDomain.Leave(); Console.WriteLine("Left context!"); }
public void TestMethod1() { ServiceDomain.Enter(new ServiceConfig()); MockRepository mocks = new MockRepository(); ISomething something = (ISomething)mocks.StrictMock(typeof(ISomething)); mocks.ReplayAll(); mocks.VerifyAll(); ContextUtil.SetAbort(); ServiceDomain.Leave(); }
public bool OrderProduct(int ProductID, int Units) { SqlConnection conn = new SqlConnection("Data Source=dougp\\dogdata;" + "Initial Catalog=Northwind;User ID=sa;Password=datadog"); try { if (!ContextUtil.IsInTransaction) { throw new Exception("Not in transaction"); } conn.Open(); SqlCommand cmd = new SqlCommand("UPDATE Products SET UnitsOnOrder = " + "UnitsOnOrder + " + Units + " WHERE ProductID = " + ProductID, conn); int rowsAffected = cmd.ExecuteNonQuery(); if (rowsAffected != 1) { throw new Exception("Invalid number of rows affected"); } cmd = new SqlCommand("UPDATE Products SET UnitsInStock = " + "UnitsInStock - " + Units + " WHERE ProductID = " + ProductID, conn); rowsAffected = cmd.ExecuteNonQuery(); if (rowsAffected != 1) { throw new Exception("Invalid number of rows affected"); } ContextUtil.SetComplete(); return(true); } catch (Exception e) { Console.WriteLine("Transaction aborted with error: {0}", e.Message); ContextUtil.SetAbort(); return(false); } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } }
public void TestMethod1() { ServiceDomain.Enter(new ServiceConfig()); ISomething something = MockRepository.Mock <ISomething>(); something.SetUnexpectedBehavior(UnexpectedCallBehaviors.BaseOrDefault); something.VerifyAllExpectations(); ContextUtil.SetAbort(); ServiceDomain.Leave(); }
public void TryThisTransaction() { try { // Do the work here... ContextUtil.SetComplete(); } catch { ContextUtil.SetAbort(); } }
public bool verifyIBAN(string iban) { bool res = false; string tmpStr = ""; string convertStr = ""; // try { // Check that the total IBAN length is correct as per the country. If not, the IBAN is invalid. // total IBAN length must be 24 characters if (iban.Length != 24) { return(false); } // // Move the four initial characters to the end of the string. tmpStr = iban.Substring(4, 20).ToUpper() + iban.Substring(0, 4).ToUpper(); // // Replace each letter in the string with two digits, thereby expanding the string, where A = 10, B = 11, ..., Z = 35. for (int i = 0; i < iban.Length; i++) { bool isLetter = !String.IsNullOrEmpty(tmpStr) && Char.IsLetter(tmpStr[i]); if (isLetter) { convertStr += ConvertLetterToDigit(tmpStr[i]); } else { convertStr += tmpStr[i]; } } // // Interpret the string as a decimal integer and compute the remainder of that number on division by 97. if (CalculateMod97(convertStr) == 1) { // If the remainder is 1, the check digit test is passed and the IBAN might be valid. res = true; } else { res = false; } ContextUtil.SetComplete(); } catch (Exception) { ContextUtil.SetAbort(); } return(res); }
// The sole method of the COM+ aware .NET type. public void RemoveCar(int id) { try { // Make use of ADO(.NET) to open the // data source and remove the correct // car. ContextUtil.SetComplete(); } catch { ContextUtil.SetAbort(); } }
public void MethodA() { // MTS style JITA. if (DoSomeWork()) { // Happy and done. ContextUtil.SetComplete(); } else { // Done but not happy. ContextUtil.SetAbort(); } }
public void DoTransaction() { try { // Operate on the resource managers like DBMS // ... ContextUtil.SetComplete(); // Commit } catch (Exception ex) { ContextUtil.SetAbort(); // Rollback throw ex; } }
public string getIBAN(string AccNum) { string iban = ""; try { dbIBAN db = new dbIBAN(); iban = db.getIBAN(AccNum); ContextUtil.SetComplete(); } catch (Exception) { ContextUtil.SetAbort(); } return(iban); }
public long m_lngSaveAll(System.Security.Principal.IPrincipal p_objPrincipal, clsLisQCDataVO[] p_objInsertArr, clsLisQCDataVO[] p_objUpdateArr, int[] p_intDelArr, out int[] p_intISeqArr) { p_intISeqArr = null; long lngRes = 0; com.digitalwave.security.clsPrivilegeHandleService objPrivilege = new clsPrivilegeHandleService(); lngRes = objPrivilege.m_lngCheckCallPrivilege(p_objPrincipal, m_strCurrentSvcDetailName, "m_lngSaveAll"); objPrivilege = null; if (lngRes <= 0) { return(lngRes); } if (p_objUpdateArr != null && p_objUpdateArr.Length > 0) { lngRes = m_lngUpdateByArr(p_objPrincipal, p_objUpdateArr); if (lngRes <= 0) { ContextUtil.SetAbort(); } } if (p_objInsertArr != null && p_objInsertArr.Length > 0) { lngRes = m_lngInsertByArr(p_objPrincipal, p_objInsertArr, out p_intISeqArr); if (lngRes <= 0) { p_intISeqArr = null; ContextUtil.SetAbort(); } } if (p_intDelArr != null && p_intDelArr.Length > 0) { lngRes = m_lngDeleteByArr(p_objPrincipal, p_intDelArr); if (lngRes <= 0) { ContextUtil.SetAbort(); } } p_intDelArr = null; p_objInsertArr = null; p_objUpdateArr = null; return(lngRes); }
/// <summary> Commit the database transaction.</summary> public static void RollbackTransaction() { try { log.Debug("Trying to rollback database transaction of this context."); ContextUtil.SetAbort(); ServiceDomain.Leave(); } catch (HibernateException ex) { throw new InfrastructureException(ex); } finally { CloseSession(); } }