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(); } }
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(); }
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(); } }
// 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(); } }
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 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(); }
///<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); } }
//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 SetComplete() { try { ContextUtil.SetComplete(); } catch (Exception e) { throw e; } }
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 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(); } }
/// <summary> Commit the database transaction.</summary> public static void CommitTransaction() { try { log.Debug("Committing database transaction of this context."); ContextUtil.SetComplete(); ServiceDomain.Leave(); } catch (HibernateException ex) { RollbackTransaction(); throw new InfrastructureException(ex); } }
public void MethodA() { // MTS style JITA. if (DoSomeWork()) { // Happy and done. ContextUtil.SetComplete(); } else { // Done but not happy. ContextUtil.SetAbort(); } }
public int Oracle_UP_IN(string sql)//执行一个update/insert语句,返回影响行数 { try { var cmd = conn.CreateCommand(); cmd.CommandText = sql; int z = cmd.ExecuteNonQuery(); ContextUtil.SetComplete(); return(z); } catch (OracleException e) { throw new Exception(e.Message); } }
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 string getIBAN(string AccNum) { string iban = ""; string connStr = ConfigurationManager.AppSettings["connStr"]; OleDbConnection cnn = new OleDbConnection(connStr); OleDbCommand cmd = new OleDbCommand("SELECT iban FROM Accounts WHERE AccNum = @accnum", cnn); OleDbDataReader reader = null; cmd.Parameters.AddWithValue("accnum", AccNum); cmd.CommandType = CommandType.Text; cmd.CommandTimeout = 300; // try { cnn.Open(); reader = cmd.ExecuteReader(); // if (reader.HasRows) { reader.Read(); iban = reader["iban"].ToString(); } cnn.Close(); ContextUtil.SetComplete(); } catch (Exception) { ContextUtil.SetAbort(); } finally { if (cnn != null) { cnn.Dispose(); } if (cmd != null) { cmd.Dispose(); } if (reader != null) { reader.Dispose(); } } return(iban); }
/// <summary> /// Commit method commit the current transaction if all the transaction vode /// are good. /// </summary> public virtual void Commit() { //check if it is in a transaction if (ContextUtil.IsInTransaction) { //check if the transaction vote is good. if so, set complete on the transaction //otherwise, abort the transaction. if (ContextUtil.MyTransactionVote == TransactionVote.Commit) { ContextUtil.SetComplete(); } else { ContextUtil.SetAbort(); } } }
// This method tries to update the "current value", first it updates the // database, then it checks if the value is allowed, if not it calls // ContextUtil.SetAbort to rollback the transaction. public void Post(int newValue) { try { Database.Open(); SqlCommand sqlCommand = new SqlCommand(@" UPDATE currentValue SET currentValue=@currentValue " , Database); sqlCommand.Parameters.Add("@currentValue", SqlDbType.Int, 4); sqlCommand.Parameters["@currentValue"].Value = newValue; try { sqlCommand.ExecuteNonQuery(); } catch (Exception e) { throw new DatabaseExecutionException(e); } if (newValue < 0 || newValue > 10) { MessageBox.Show("About to abort the transaction because the new value (" + newValue + ") is either <0 or >10"); ContextUtil.SetAbort(); } else { MessageBox.Show("About to commit the transaction"); ContextUtil.SetComplete(); } } finally { Database.Close(); } }
public static void ExternalTransactionViaADO() { MessageQueue queueA = new MessageQueue(); try { queueA.Path = ConfigurationManager.AppSettings["TransactionalQ1"];; queueA.Send("OrderA for Message", "Order A", MessageQueueTransactionType.Automatic); string ConnectionString = ConfigurationManager.ConnectionStrings["TestConnection"].ToString(); Random r = new Random(); // testOrder = new TestOrder() { Id = r.Next(1, 10), CreatedDate = DateTime.Now.ToString(), Name = "Order_" + r.Next(11, 100) }; int inserted = 0; string QryString = "insert into TestOrder values(" + r.Next(1, 10) + ",'" + DateTime.Now.ToString() + "','Order_" + r.Next(11, 100) + "')"; SqlConnection conn = new SqlConnection(ConnectionString); SqlCommand CmdObj = new SqlCommand(QryString, conn); conn.Open(); inserted = CmdObj.ExecuteNonQuery(); if (ContextUtil.IsInTransaction) { ContextUtil.SetComplete(); } conn.Close(); } catch (Exception ex) { if (ContextUtil.IsInTransaction) { ContextUtil.SetAbort(); } throw; } finally { queueA.Close(); } }
/// <summary> /// 提交事务,页面需要设置《%@ Page Transaction="Required"%》 /// </summary> public void CommitTransaction() { ContextUtil.SetComplete(); }
/// <summary> /// Sets the consistent bit and the done bit to true in the COM+ context /// </summary> public void SetComplete() { ContextUtil.SetComplete(); }