public static void Withdraw(string number, string pin, decimal amount) { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = IsolationLevel.RepeatableRead; TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options); using (scope) { ATMEntities context = new ATMEntities(); using (context) { var account = context.CardAccounts.First(x => x.CardNumber == number && x.CardPIN == pin); if (account != null) { if (amount <= account.CardCash && amount > 0) { account.CardCash -= amount; AddTransaction.Add(number, DateTime.Now, amount, context); } } context.SaveChanges(); scope.Complete(); } } }
// TODO: Issue #10353 - These variations need to be added once we have promotion support. /* [InlineData(CloneType.Normal, true, true, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.RepeatableRead, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.ReadCommitted, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.ReadUncommitted, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.Snapshot, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.Chaos, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.Unspecified, false, false, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.Serializable, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.RepeatableRead, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.ReadCommitted, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.ReadUncommitted, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.Snapshot, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.Chaos, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.Unspecified, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.Serializable, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.RepeatableRead, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.ReadCommitted, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.ReadUncommitted, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.Snapshot, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.Chaos, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.Unspecified, true, true, TransactionStatus.Committed)] */ public void Run(CloneType cloneType, IsolationLevel isoLevel, bool forcePromote, bool completeClone, TransactionStatus expectedStatus ) { TransactionOptions options = new TransactionOptions { IsolationLevel = isoLevel, // Shorten the delay before a timeout for blocking clones. Timeout = TimeSpan.FromSeconds(1) }; CommittableTransaction tx = new CommittableTransaction(options); Transaction clone; switch (cloneType) { case CloneType.Normal: { clone = tx.Clone(); break; } case CloneType.BlockingDependent: { clone = tx.DependentClone(DependentCloneOption.BlockCommitUntilComplete); break; } case CloneType.RollbackDependent: { clone = tx.DependentClone(DependentCloneOption.RollbackIfNotComplete); break; } default: { throw new Exception("Unexpected CloneType - " + cloneType.ToString()); } } if (forcePromote) { HelperFunctions.PromoteTx(tx); } Assert.Equal(clone.IsolationLevel, tx.IsolationLevel); Assert.Equal(clone.TransactionInformation.Status, tx.TransactionInformation.Status); Assert.Equal(clone.TransactionInformation.LocalIdentifier, tx.TransactionInformation.LocalIdentifier); Assert.Equal(clone.TransactionInformation.DistributedIdentifier, tx.TransactionInformation.DistributedIdentifier); CommittableTransaction cloneCommittable = clone as CommittableTransaction; Assert.Null(cloneCommittable); try { tx.Commit(); } catch (TransactionAbortedException) { Assert.Equal(expectedStatus, TransactionStatus.Aborted); } Assert.Equal(expectedStatus, tx.TransactionInformation.Status); }
private static void RunTest(IsolationLevel isolationLevel) { // Handles are used only to wait for both workers to complete var handles = new WaitHandle[] { new ManualResetEvent(false), new ManualResetEvent(false) }; var options = new TransactionOptions { IsolationLevel = isolationLevel, Timeout = new TimeSpan(0, 0, 0, 10) }; // Worker's job WaitCallback job = state => { try { using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, options)) { using (var context = new NorthwindEntities()) { var region = GetRegionById(context, 4); Console.WriteLine("Updating description"); region.RegionDescription = region.RegionDescription.Trim() + " updated"; Console.WriteLine("Saving"); context.SaveChanges(); // Save changes to DB } scope.Complete(); // Commit transaction Console.WriteLine("Persisted"); } } catch (Exception e) { PrintError(e); } finally { // Signal to the main thread that the worker has completed ((ManualResetEvent)state).Set(); } }; // Run workers ThreadPool.QueueUserWorkItem(job, handles[0]); ThreadPool.QueueUserWorkItem(job, handles[1]); // Wait for both workers to complete WaitHandle.WaitAll(handles); }
private bool Equals(TransactionOptions other) => _timeout == other._timeout && _isolationLevel == other._isolationLevel;
// TODO: Issue #10353 - These variations need to be added once we have promotion support. /* [InlineData(CloneType.Normal, true, true, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.RepeatableRead, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.ReadCommitted, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.ReadUncommitted, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.Snapshot, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.Chaos, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, IsolationLevel.Unspecified, false, false, TransactionStatus.Committed)] [InlineData(CloneType.Normal, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.Serializable, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.RepeatableRead, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.ReadCommitted, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.ReadUncommitted, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.Snapshot, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.Chaos, true, true, TransactionStatus.Committed)] [InlineData(CloneType.BlockingDependent, IsolationLevel.Unspecified, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.Serializable, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.RepeatableRead, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.ReadCommitted, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.ReadUncommitted, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.Snapshot, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.Chaos, true, true, TransactionStatus.Committed)] [InlineData(CloneType.RollbackDependent, IsolationLevel.Unspecified, true, true, TransactionStatus.Committed)] */ public void Run(CloneType cloneType, IsolationLevel isoLevel, bool forcePromote, bool completeClone, TransactionStatus expectedStatus ) { TransactionOptions options = new TransactionOptions { IsolationLevel = isoLevel, // Shorten the delay before a timeout for blocking clones. Timeout = TimeSpan.FromSeconds(1) }; // If we are dealing with a "normal" clone, we fully expect the transaction to commit successfully. // But a timeout of 1 seconds may not be enough for that to happen. So increase the timeout // for "normal" clones. This will not increase the test execution time in the "passing" scenario. if (cloneType == CloneType.Normal) { options.Timeout = TimeSpan.FromSeconds(10); } CommittableTransaction tx = new CommittableTransaction(options); Transaction clone; switch (cloneType) { case CloneType.Normal: { clone = tx.Clone(); break; } case CloneType.BlockingDependent: { clone = tx.DependentClone(DependentCloneOption.BlockCommitUntilComplete); break; } case CloneType.RollbackDependent: { clone = tx.DependentClone(DependentCloneOption.RollbackIfNotComplete); break; } default: { throw new Exception("Unexpected CloneType - " + cloneType.ToString()); } } if (forcePromote) { HelperFunctions.PromoteTx(tx); } Assert.Equal(tx.IsolationLevel, clone.IsolationLevel); Assert.Equal(tx.TransactionInformation.Status, clone.TransactionInformation.Status); Assert.Equal(tx.TransactionInformation.LocalIdentifier, clone.TransactionInformation.LocalIdentifier); Assert.Equal(tx.TransactionInformation.DistributedIdentifier, clone.TransactionInformation.DistributedIdentifier); CommittableTransaction cloneCommittable = clone as CommittableTransaction; Assert.Null(cloneCommittable); try { tx.Commit(); } catch (TransactionAbortedException ex) { Assert.Equal(expectedStatus, TransactionStatus.Aborted); switch (cloneType) { case CloneType.Normal: { // We shouldn't be getting TransactionAbortedException for "normal" clones, // so we have these two Asserts to possibly help determine what went wrong. Assert.Null(ex.InnerException); Assert.Equal("There shouldn't be any exception with this Message property", ex.Message); break; } case CloneType.BlockingDependent: { Assert.IsType<TimeoutException>(ex.InnerException); break; } case CloneType.RollbackDependent: { Assert.Null(ex.InnerException); break; } default: { throw new Exception("Unexpected CloneType - " + cloneType.ToString()); } } } Assert.Equal(expectedStatus, tx.TransactionInformation.Status); }
// // Enroll(): // // If possible, function enrolls the student in the course. // // Return values: // -1 - error // 0 - Student already enrolled // 1 - Student enrolled // 2 - Student already waitlisted // 3 - Student waitlisted // private int Enroll(int sid, int cid) { int retries = 0; // make sure parameters are valid if (sid < 0 || cid < 0) { return(-1); } using (var db = new CoursemoDataContext()) { while (retries < 3) { try { var txOptions = new TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var transaction = new TransactionScope(TransactionScopeOption.Required, txOptions)) { // check if student is already enrolled if (StudentEnrolled(sid, cid)) { return(0); } // class is full, add to waitlist if (GetCourseCapacity(cid) - GetCurrentEnrollment(cid) < 1) { // check if student is not on waitlist alread if (StudentWaitlisted(sid, cid)) { return(2); } db.WaitlistStudent(sid, cid); db.SubmitChanges(); transaction.Complete(); return(3); } // enroll else { System.Threading.Thread.Sleep(_delay); db.RegisterStudent(sid, cid); db.SubmitChanges(); transaction.Complete(); return(1); } } } catch (SqlException exc) { // deadlock if (exc.Number == 1205) { retries++; } } catch (Exception e) { MessageBox.Show("Enroll(): " + e.Message); return(-1); } } // while } return(-1); } // Enroll()
/// <summary> /// 使用事物 在事物里面的代码都是走master /// </summary> /// <param name="func"></param> /// <param name="scopeOption">TransactionScopeOption</param> /// <param name="options">TransactionOptions</param> public void UseTransaction(System.Action <DbContext <T> > func, TransactionScopeOption scopeOption, TransactionOptions options) { using (var scope = new System.Transactions.TransactionScope(scopeOption, options)) { func(this); scope.Complete(); } }
public void SetJobState_EnlistsInAmbientTransaction(bool completeTransactionScope) { TransactionScope CreateTransactionScope(System.Transactions.IsolationLevel isolationLevel = System.Transactions.IsolationLevel.RepeatableRead) { var transactionOptions = new TransactionOptions() { IsolationLevel = isolationLevel, Timeout = TransactionManager.MaximumTimeout }; return(new TransactionScope(TransactionScopeOption.Required, transactionOptions)); } string arrangeSql = @" insert into """ + GetSchemaName() + @""".""job"" (""invocationdata"", ""arguments"", ""createdat"") values ('', '', now() at time zone 'utc') returning ""id"""; string jobId = null; string anotherJobId = null; UseConnection(sql => { jobId = sql.Query(arrangeSql).Single().id.ToString(); anotherJobId = sql.Query(arrangeSql).Single().id.ToString(); }); using (var scope = CreateTransactionScope()) { UseConnection(sql => { var state = new Mock <IState>(); state.Setup(x => x.Name).Returns("State"); state.Setup(x => x.Reason).Returns("Reason"); state.Setup(x => x.SerializeData()) .Returns(new Dictionary <string, string> { { "Name", "Value" } }); Commit(sql, x => x.SetJobState(jobId, state.Object)); }); if (completeTransactionScope) { scope.Complete(); } } UseConnection(sql => { var job = GetTestJob(sql, jobId); if (completeTransactionScope) { Assert.Equal("State", job.statename); Assert.NotNull(job.stateid); var jobState = sql.Query(@"select * from """ + GetSchemaName() + @""".""state""").Single(); Assert.Equal((string)jobId, jobState.jobid.ToString()); Assert.Equal("State", jobState.name); Assert.Equal("Reason", jobState.reason); Assert.NotNull(jobState.createdat); Assert.Equal("{\"Name\":\"Value\"}", jobState.data); } else { Assert.Null(job.statename); Assert.Null(job.stateid); Assert.Null(sql.Query(@"select * from """ + GetSchemaName() + @""".""state""").SingleOrDefault()); } var anotherJob = GetTestJob(sql, anotherJobId); Assert.Null(anotherJob.statename); Assert.Null(anotherJob.stateid); }); }
private async Task <PooledSession> AcquireSessionImplAsync(TransactionOptions transactionOptions, CancellationToken cancellationToken) { var transactionMode = transactionOptions?.ModeCase ?? ModeOneofCase.None; var sessionAcquisitionTask = GetSessionAcquisitionTask(transactionMode, cancellationToken); // We've either fetched a task from the pool, or registered that a caller is waiting for one. // We may want to start creation tasks, either to replenish the pool or (if there were no pool entries) // to make sure that there's something creating a session for us. StartAcquisitionTasksIfNecessary(); var session = await sessionAcquisitionTask.ConfigureAwait(false); // Note: deliberately no test for refresh or eviction. // We do this when a session is released, and in the maintenance task. // These happen frequently enough that we shouldn't need to worry about them here. // Update statistics for prewarming - only after we've already acquired the session. if (transactionMode == ModeOneofCase.ReadWrite) { Interlocked.Increment(ref _rwTransactionRequests); if (session.TransactionMode == transactionMode) { Interlocked.Increment(ref _rwTransactionRequestsPrewarmed); } } // If we've already got the right transaction mode, we're done. if (session.TransactionMode == transactionMode) { return(session); } // Otherwise, we may need to forget an existing transaction, or request a new one. else { // If we asked for a session with no transaction but we got one *with* a tranasction, // we don't need to perform any RPCs - but we do need to return a PooledSession with // no transaction ID. if (transactionMode == ModeOneofCase.None) { return(session.WithTransaction(null, ModeOneofCase.None)); } else { bool success = false; try { session = await BeginTransactionAsync(session, transactionOptions, cancellationToken).ConfigureAwait(false); success = true; return(session); } finally { // If we succeeded in getting a session but not a transaction, we can reuse the session later, but still fail this call. // It counts as "inactive" because the failure will decrement the active session count already. // Note that the only way success is false is if we're throwing an exception, so we'll never release it // *and* then return it. if (!success) { ReleaseInactiveSession(session, maybeCreateReadWriteTransaction: false); } } } } }
//Metode der tilføjer salgslinjen til ordren, her håndteres der samtidighed ved hjælp af repeatable read. public bool AddSalesLineItemToOrder(List <SalesLineItem> sli) { bool result = false; // Laver en transaction option som sætter isolationsniveauet til repeatableread TransactionOptions to = new TransactionOptions(); to.IsolationLevel = IsolationLevel.RepeatableRead; int deadlockRetries = 0; using (TransactionScope scope = new TransactionScope()) { using (SqlConnection connection = new SqlConnection(_connectionString)) { connection.Open(); while (deadlockRetries < 3) { foreach (SalesLineItem lineItem in sli) { try { // SQL kommando til at få fat i underprodukter. using (SqlCommand getStockCommand = connection.CreateCommand()) { getStockCommand.CommandText = "SELECT stock FROM ProductVersion WHERE productID = @ProdID AND sizeCode = @SizeCode AND colorCode = @ColorCode"; getStockCommand.Parameters.AddWithValue("ProdID", lineItem.Product.StyleNumber); getStockCommand.Parameters.AddWithValue("SizeCode", lineItem.ProductVersion.SizeCode); getStockCommand.Parameters.AddWithValue("ColorCode", lineItem.ProductVersion.ColorCode); var stock = (int)getStockCommand.ExecuteScalar(); // tjek om nok på lager if (stock < lineItem.amount) { throw new Exception("Not enough in stock of product: " + lineItem.Product.Name); } else { // indsæt saleslineitem using (SqlCommand insertSalesLineCommand = connection.CreateCommand()) { insertSalesLineCommand.CommandText = "INSERT INTO SalesLineItem VALUES (@Amount, @Price, @OrderID, @ProductID, @SizeCode, @ColorCode)"; insertSalesLineCommand.Parameters.AddWithValue("Amount", lineItem.amount); insertSalesLineCommand.Parameters.AddWithValue("Price", lineItem.Price); insertSalesLineCommand.Parameters.AddWithValue("OrderID", lineItem.Order.OrderId); insertSalesLineCommand.Parameters.AddWithValue("ProductID", lineItem.Product.StyleNumber); insertSalesLineCommand.Parameters.AddWithValue("SizeCode", lineItem.ProductVersion.SizeCode); insertSalesLineCommand.Parameters.AddWithValue("ColorCode", lineItem.ProductVersion.ColorCode); // execute insertSalesLineCommand.ExecuteNonQuery(); } // opdater lager using (SqlCommand updateStockCommand = connection.CreateCommand()) { updateStockCommand.CommandText = "UPDATE ProductVersion SET stock = stock - @Amount WHERE productID = @ProdID AND sizeCode = @SizeCode AND colorCode = @ColorCode"; updateStockCommand.Parameters.AddWithValue("Amount", lineItem.amount); updateStockCommand.Parameters.AddWithValue("ProdID", lineItem.Product.StyleNumber); updateStockCommand.Parameters.AddWithValue("SizeCode", lineItem.ProductVersion.SizeCode); updateStockCommand.Parameters.AddWithValue("ColorCode", lineItem.ProductVersion.ColorCode); // execute updateStockCommand.ExecuteNonQuery(); deadlockRetries = 10; } } } } catch (SqlException ex) { // Fejll kode 1205 fra Db = Deadlock if (ex.Number == 1205) { //Console.WriteLine(ex.Message); deadlockRetries++; } else { throw new Exception("Der opstod en fejl: " + ex.Message); } } } } } scope.Complete(); // end transaction result = true; } return(result); }
// public bool ApproveNewUser(sec_UserRepo repo_user) // { // //Get connectoin // var app = new AppSettings(); // TransactionOptions tsOp = new TransactionOptions(); // tsOp.IsolationLevel = System.Transactions.IsolationLevel.Snapshot; // TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew, tsOp); // tsOp.Timeout = TimeSpan.FromMinutes(20); // using (OracleConnection conn = new OracleConnection(app.conString())) // // { // try // { // string queryinternet = "select * from setup_company"; // #region get email properties // { // var paramuser = new DynamicParameters(); // paramuser.Add("P_USER_ID", repo_user.User_Id, DbType.String, ParameterDirection.Input); // paramuser.Add("REMAIL", "", DbType.String, ParameterDirection.Output); // paramuser.Add("RPASSWORD", "", DbType.String, ParameterDirection.Output); // paramuser.Add("RFULLNAME", "", DbType.String, ParameterDirection.Output); // con.Execute("SEL_EMAIL_PROP", paramuser, commandType: CommandType.StoredProcedure); // repo_user.Email = paramuser.Get<string>("REMAIL"); // repo_user.Password = paramuser.Get<string>("RPASSWORD"); // repo_user.Employee_Name = paramuser.Get<string>("RFULLNAME"); // } // #endregion // #region send email // OracleCommand commandinternet = new OracleCommand(queryinternet, conn); // conn.Open(); // OracleDataReader readerinternet; // readerinternet = commandinternet.ExecuteReader(); // // Always call Read before accessing data. // while (readerinternet.Read()) // { // internetRepo.smtp = (string)readerinternet["smtp"]; // internetRepo.email_from = (string)readerinternet["email_from"]; // internetRepo.email_password = (string)readerinternet["email_password"]; // internetRepo.port = Convert.ToInt16(readerinternet["port"]); // internetRepo.company_name = (string)readerinternet["company_name"]; // } // string security_Code = "[email protected]"; // repo_user.Password = GlobalValue.AES_Decrypt(repo_user.Password, security_Code); // var msg = $@"<b>Dear {repo_user.Employee_Name}</b> <br/> <br/><font color=blue>Your User Name is {repo_user.User_Id} and Password is {repo_user.Password}</font>"; // string from = internetRepo.email_from, pass = internetRepo.email_password, subj = "Teksol Penfad authentication for " + repo_user.Employee_Name, to = repo_user.Email; // string smtp = internetRepo.smtp; // int port = internetRepo.port; // internetRepo.SendIt(from, pass, subj, msg, to, smtp, port); // #endregion // #region Approve user // var param = new DynamicParameters(); // param.Add(name: "p_UserId", value: repo_user.User_Id, dbType: DbType.String, direction: ParameterDirection.Input); // param.Add(name: "p_UserStatus", value: "ACTIVE", dbType: DbType.String, direction: ParameterDirection.Input); // param.Add(name: "p_AuthStatus", value: "AUTHORIZED", dbType: DbType.String, direction: ParameterDirection.Input); // param.Add(name: "p_AuthDate", value: GlobalValue.Scheme_Today_Date, dbType: DbType.Date, direction: ParameterDirection.Input); // param.Add(name: "p_AuthId", value: GlobalValue.User_ID, dbType: DbType.String, direction: ParameterDirection.Input); // con.Execute(sql: "APP_SEC_USER", param: param, commandType: CommandType.StoredProcedure); // #endregion // //ts.Complete(); // return true; // } // catch (Exception ex) // { // throw ex; // } // finally // { // if (con.State == ConnectionState.Open) // { // con.Close(); // } // } // } //} public void ApproveNewUser(sec_UserRepo repo_user) { var app = new AppSettings(); TransactionOptions tsOp = new TransactionOptions(); tsOp.IsolationLevel = System.Transactions.IsolationLevel.Snapshot; TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew, tsOp); tsOp.Timeout = TimeSpan.FromMinutes(20); string queryinternet = "select * from setup_company"; using (OracleConnection conn = new OracleConnection(app.conString())) // { try { //string password_hash = cSecurityRepo.AES_Encrypt(repo_user.Password); #region get email properties { var paramuser = new DynamicParameters(); paramuser.Add("P_USER_ID", repo_user.User_Id, DbType.String, ParameterDirection.Input); paramuser.Add("REMAIL", "", DbType.String, ParameterDirection.Output); paramuser.Add("RPASSWORD", "", DbType.String, ParameterDirection.Output); paramuser.Add("RFULLNAME", "", DbType.String, ParameterDirection.Output); conn.Execute("SEL_EMAIL_PROP", paramuser, commandType: CommandType.StoredProcedure); repo_user.Email = paramuser.Get <string>("REMAIL"); repo_user.Employee_Name = paramuser.Get <string>("RFULLNAME"); } #endregion #region reassign user var param = new DynamicParameters(); param.Add(name: "p_UserId", value: repo_user.User_Id, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_UserStatus", value: "ACTIVE", dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_AuthStatus", value: "AUTHORIZED", dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_AuthDate", value: GlobalValue.Scheme_Today_Date, dbType: DbType.Date, direction: ParameterDirection.Input); param.Add(name: "p_AuthId", value: GlobalValue.User_ID, dbType: DbType.String, direction: ParameterDirection.Input); conn.Execute(sql: "APP_SEC_USER", param: param, commandType: CommandType.StoredProcedure); #endregion #region send email OracleCommand commandinternet = new OracleCommand(queryinternet, conn); conn.Open(); OracleDataReader readerinternet; readerinternet = commandinternet.ExecuteReader(); // Always call Read before accessing data. while (readerinternet.Read()) { internetRepo.smtp = (string)readerinternet["smtp"]; internetRepo.email_from = (string)readerinternet["email_from"]; internetRepo.email_password = (string)readerinternet["email_password"]; internetRepo.port = Convert.ToInt16(readerinternet["port"]); internetRepo.company_name = (string)readerinternet["company_name"]; } string security_Code = "[email protected]"; repo_user.Password = GlobalValue.AES_Decrypt(repo_user.Password, security_Code); var msg = $@"<b>Dear {repo_user.Employee_Name}</b> <br/> <br/><font color=blue>Your User Name is {repo_user.User_Id} and Password is {repo_user.Password}</font>"; string from = internetRepo.email_from, pass = internetRepo.email_password, subj = "Teksol Penfad authentication for " + repo_user.Employee_Name, to = repo_user.Email; string smtp = internetRepo.smtp; int port = internetRepo.port; // internetRepo.SendIt(from, pass, subj, msg, to, smtp, port); internetRepo.SendIt(from, pass, subj, msg, to, smtp, port, internetRepo.company_name); #endregion ts.Complete(); } catch (Exception ex) { throw ex; } finally { ts.Dispose(); if (conn.State == ConnectionState.Open) { conn.Close(); } } } }
static Constant() { option = new TransactionOptions(); option.IsolationLevel = IsolationLevel.ReadCommitted; option.Timeout = new TimeSpan(0, AppSettingHelper.GetInteger(Appsetting_Timeout, Appsetting_Timeout_Default), 0); }
public CommittableTransaction(TransactionOptions options) { }
private void btnFinish_Click(object sender, EventArgs e) { if (ActionType == WhistlingPalms.ActionType.Addition.ToString()) { try { TransactionDataSet ds = ((uscAddStock)uscTransactionDetails).dsTransaction; if (ds.TransactionDetails.Rows.Count <= 0) { MessageBox.Show("Please add atleast one item details for the transaction", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var transactionOptions = new TransactionOptions(); transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; transactionOptions.Timeout = TimeSpan.MaxValue; using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) { InventoryStoreDataSetTableAdapters.tblTransactionTableAdapter adpTransaction = new InventoryStoreDataSetTableAdapters.tblTransactionTableAdapter(); InventoryStoreDataSetTableAdapters.tblTransactionDetailsTableAdapter adpTransactionDetails = new InventoryStoreDataSetTableAdapters.tblTransactionDetailsTableAdapter(); InventoryStoreDataSetTableAdapters.tblTransactionStockInformationTableAdapter adpTransactionStock = new InventoryStoreDataSetTableAdapters.tblTransactionStockInformationTableAdapter(); InventoryStoreDataSetTableAdapters.tblInventoryTableAdapter adpInventory = new InventoryStoreDataSetTableAdapters.tblInventoryTableAdapter(); int?ClientID = null; if ((int)cmbClient.SelectedValue > 0) { ClientID = (int)cmbClient.SelectedValue; } int TransactionID = Convert.ToInt32(adpTransaction.InsertTransaction(txtTransactionDetails.Text.Trim(), dtpTransactionDate.Value, (int)cmbTransactionType.SelectedValue, txtRemarks.Text.Trim(), txtOrderNo.Text.Trim(), ClientID)); if (TransactionID > 0) { foreach (TransactionDataSet.TransactionDetailsRow dr in ds.TransactionDetails.Rows) { int?ToWareHouseID = null; if (!dr.IsToWareHouseIDNull()) { ToWareHouseID = dr.ToWareHouseID; } int TransactionDetailID = Convert.ToInt32(adpTransactionDetails.InsertTransactionDetails(TransactionID, dr.ProductID, dr.FromWareHouseID, ToWareHouseID, dr.TransactQuantity, dr.TransactCost, dr.TotalCost)); if (TransactionDetailID > 0) { foreach (TransactionDataSet.TransactionStockInformationRow tsr in ds.TransactionStockInformation.Rows) { if (tsr.TransactionDetailID == dr.TransactionDetailID) { int TransactionStockID = adpTransactionStock.Insert(TransactionDetailID, tsr.Cost, tsr.OldQuantity, tsr.NewQuantity, tsr.IsFromWareHouse); if (TransactionStockID > 0) { int retval; if (tsr.OldQuantity == 0) { retval = adpInventory.Insert(dr.ProductID, dr.FromWareHouseID, tsr.Cost, tsr.NewQuantity); } else { retval = adpInventory.UpdateQuantity(tsr.NewQuantity, dr.ProductID, dr.FromWareHouseID, tsr.Cost); } if (retval <= 0) { throw new Exception("Unable to update into Inventory Table"); } } else { throw new Exception("Unable to insert into Transaction Stock Change Information"); } } } } else { throw new Exception("Unable to insert into Transaction Details"); } } } else { throw new Exception("Unable to insert into Transaction Master"); } ts.Complete(); this.Close(); } } catch (Exception ex) { MessageBox.Show("Failed to Insert Transaction. Error Details:" + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else if (ActionType == WhistlingPalms.ActionType.Deduction.ToString()) { try { TransactionDataSet ds = ((uscRemoveStock)uscTransactionDetails).dsTransaction; if (ds.TransactionDetails.Rows.Count <= 0) { MessageBox.Show("Please add atleast one item details for the transaction", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var transactionOptions = new TransactionOptions(); transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; transactionOptions.Timeout = TimeSpan.MaxValue; using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) { InventoryStoreDataSetTableAdapters.tblTransactionTableAdapter adpTransaction = new InventoryStoreDataSetTableAdapters.tblTransactionTableAdapter(); InventoryStoreDataSetTableAdapters.tblTransactionDetailsTableAdapter adpTransactionDetails = new InventoryStoreDataSetTableAdapters.tblTransactionDetailsTableAdapter(); InventoryStoreDataSetTableAdapters.tblTransactionStockInformationTableAdapter adpTransactionStock = new InventoryStoreDataSetTableAdapters.tblTransactionStockInformationTableAdapter(); InventoryStoreDataSetTableAdapters.tblInventoryTableAdapter adpInventory = new InventoryStoreDataSetTableAdapters.tblInventoryTableAdapter(); int?ClientID = null; if ((int)cmbClient.SelectedValue > 0) { ClientID = (int)cmbClient.SelectedValue; } int TransactionID = Convert.ToInt32(adpTransaction.InsertTransaction(txtTransactionDetails.Text.Trim(), dtpTransactionDate.Value, (int)cmbTransactionType.SelectedValue, txtRemarks.Text.Trim(), txtOrderNo.Text.Trim(), ClientID)); if (TransactionID > 0) { foreach (TransactionDataSet.TransactionDetailsRow dr in ds.TransactionDetails.Rows) { int?ToWareHouseID = null; if (!dr.IsToWareHouseIDNull()) { ToWareHouseID = dr.ToWareHouseID; } int TransactionDetailID = Convert.ToInt32(adpTransactionDetails.InsertTransactionDetails(TransactionID, dr.ProductID, dr.FromWareHouseID, ToWareHouseID, dr.TransactQuantity, dr.TransactCost, dr.TotalCost)); if (TransactionDetailID > 0) { foreach (TransactionDataSet.TransactionStockInformationRow tsr in ds.TransactionStockInformation.Rows) { if (tsr.TransactionDetailID == dr.TransactionDetailID && tsr.TransactQuantity > 0) { int TransactionStockID = adpTransactionStock.Insert(TransactionDetailID, tsr.Cost, tsr.OldQuantity, tsr.NewQuantity, tsr.IsFromWareHouse); if (TransactionStockID > 0) { int retval; if (tsr.NewQuantity == 0) { retval = adpInventory.DeleteInventoryEntry(dr.ProductID, dr.FromWareHouseID, tsr.Cost); } else { retval = adpInventory.UpdateQuantity(tsr.NewQuantity, dr.ProductID, dr.FromWareHouseID, tsr.Cost); } if (retval <= 0) { throw new Exception("Unable to update into Inventory Table"); } } else { throw new Exception("Unable to insert into Transaction Stock Change Information"); } } } } else { throw new Exception("Unable to insert into Transaction Details"); } } } else { throw new Exception("Unable to insert into Transaction Master"); } ts.Complete(); this.Close(); } } catch (Exception ex) { MessageBox.Show("Failed to Insert Transaction. Error Details:" + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else if (ActionType == WhistlingPalms.ActionType.Transfer.ToString()) { try { TransactionDataSet ds = ((uscTransferStock)uscTransactionDetails).dsTransaction; if (ds.TransactionDetails.Rows.Count <= 0) { MessageBox.Show("Please add atleast one item details for the transaction", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } var transactionOptions = new TransactionOptions(); transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; transactionOptions.Timeout = TimeSpan.MaxValue; using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) { InventoryStoreDataSetTableAdapters.tblTransactionTableAdapter adpTransaction = new InventoryStoreDataSetTableAdapters.tblTransactionTableAdapter(); InventoryStoreDataSetTableAdapters.tblTransactionDetailsTableAdapter adpTransactionDetails = new InventoryStoreDataSetTableAdapters.tblTransactionDetailsTableAdapter(); InventoryStoreDataSetTableAdapters.tblTransactionStockInformationTableAdapter adpTransactionStock = new InventoryStoreDataSetTableAdapters.tblTransactionStockInformationTableAdapter(); InventoryStoreDataSetTableAdapters.tblInventoryTableAdapter adpInventory = new InventoryStoreDataSetTableAdapters.tblInventoryTableAdapter(); int?ClientID = null; if ((int)cmbClient.SelectedValue > 0) { ClientID = (int)cmbClient.SelectedValue; } int TransactionID = Convert.ToInt32(adpTransaction.InsertTransaction(txtTransactionDetails.Text.Trim(), dtpTransactionDate.Value, (int)cmbTransactionType.SelectedValue, txtRemarks.Text.Trim(), txtOrderNo.Text.Trim(), ClientID)); if (TransactionID > 0) { foreach (TransactionDataSet.TransactionDetailsRow dr in ds.TransactionDetails.Rows) { int? ToWareHouseID = null; decimal?TransactCost = null; decimal?TotalCost = null; if (!dr.IsToWareHouseIDNull()) { ToWareHouseID = dr.ToWareHouseID; } if (!dr.IsTotalCostNull()) { TotalCost = dr.TotalCost; } if (!dr.IsTransactCostNull()) { TransactCost = dr.TransactCost; } int TransactionDetailID = Convert.ToInt32(adpTransactionDetails.InsertTransactionDetails(TransactionID, dr.ProductID, dr.FromWareHouseID, ToWareHouseID, dr.TransactQuantity, TransactCost, TotalCost)); if (TransactionDetailID > 0) { foreach (TransactionDataSet.TransactionStockInformationRow tsr in ds.TransactionStockInformation.Rows) { if (tsr.TransactionDetailID == dr.TransactionDetailID && tsr.TransactQuantity > 0 && tsr.IsFromWareHouse == true) { int TransactionStockID = adpTransactionStock.Insert(TransactionDetailID, tsr.Cost, tsr.OldQuantity, tsr.NewQuantity, tsr.IsFromWareHouse); if (TransactionStockID > 0) { int retval; if (tsr.NewQuantity == 0) { retval = adpInventory.DeleteInventoryEntry(dr.ProductID, dr.FromWareHouseID, tsr.Cost); } else { retval = adpInventory.UpdateQuantity(tsr.NewQuantity, dr.ProductID, dr.FromWareHouseID, tsr.Cost); } if (retval <= 0) { throw new Exception("Unable to update into Inventory Table"); } } else { throw new Exception("Unable to insert into Transaction Stock Change Information"); } } else if (tsr.TransactionDetailID == dr.TransactionDetailID && tsr.TransactQuantity > 0 && tsr.IsFromWareHouse == false) { int TransactionStockID = adpTransactionStock.Insert(TransactionDetailID, tsr.Cost, tsr.OldQuantity, tsr.NewQuantity, tsr.IsFromWareHouse); if (TransactionStockID > 0) { int retval; if (tsr.OldQuantity == 0) { retval = adpInventory.Insert(dr.ProductID, dr.ToWareHouseID, tsr.Cost, tsr.NewQuantity); } else { retval = adpInventory.UpdateQuantity(tsr.NewQuantity, dr.ProductID, dr.ToWareHouseID, tsr.Cost); } if (retval <= 0) { throw new Exception("Unable to update into Inventory Table"); } } else { throw new Exception("Unable to insert into Transaction Stock Change Information"); } } } } else { throw new Exception("Unable to insert into Transaction Details"); } } } else { throw new Exception("Unable to insert into Transaction Master"); } ts.Complete(); this.Close(); } } catch (Exception ex) { MessageBox.Show("Failed to Insert Transaction. Error Details:" + Environment.NewLine + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
private int Enroll(int sid, int cid) { // make sure parameters are valid if (sid < 0 || cid < 0) { return(-1); } try { var txOptions = new TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var transaction = new TransactionScope(TransactionScopeOption.Required, txOptions)) { // check if student is already enrolled int enrolled = (from reg in db.Registrations where reg.SID == sid && reg.CID == cid select reg).Count(); if (enrolled > 0) { return(0); } // check for available spot int capacity = Convert.ToInt32((from c in db.Courses where c.CID == cid select c.ClassSize).Single()); // get max enrollment in the course int currEnrollment = Convert.ToInt32((from r in db.Registrations where r.CID == cid select r).Count()); // class is full, add to waitlist if (capacity - currEnrollment < 1) { // check if student is not on waitlist already int waitlisted = (from wait in db.Waitlists where wait.SID == sid && wait.CID == cid select wait).Count(); if (waitlisted > 0) { return(2); } db.WaitlistStudent(sid, cid); db.SubmitChanges(); transaction.Complete(); MessageBox.Show("Added to waitlist s: " + sid + "c: " + cid); return(1); } // enroll else { db.RegisterStudent(sid, cid); db.SubmitChanges(); transaction.Complete(); return(3); } } } catch (Exception e) { MessageBox.Show("Enroll(): " + e.Message); return(-1); } }
public bool Reverse_Journal(GLJournalRepo GLRepo) { var app = new AppSettings(); // get the pending purchase record GLRepo.GetJournalPendingList(TID); TransactionOptions tsOp = new TransactionOptions(); tsOp.IsolationLevel = System.Transactions.IsolationLevel.Snapshot; TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew, tsOp); tsOp.Timeout = TimeSpan.FromMinutes(20); using (OracleConnection conn = new OracleConnection(app.conString())) // { try { // UPDATE GL_JOURNAL_LOG TABLE DynamicParameters param = new DynamicParameters(); param.Add(name: "P_TID", value: TID, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "P_JOURNAL_STATUS", value: "REVERSED", dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "P_AUTH_STATUS", value: "AUTHORIZED", dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "P_REVERSAL_REASON", value: Reversal_Reason, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "P_REVERSAL_ID", value: GlobalValue.User_ID, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "P_REVERSAL_DATE", value: GlobalValue.Scheme_Today_Date, dbType: DbType.Date, direction: ParameterDirection.Input); conn.Execute("REV_JOURNAL", param, commandType: CommandType.StoredProcedure); //UPDATE GL_ACCOUNT TABLE AND GL_TRANSACTION TABLE DynamicParameters param_gl = new DynamicParameters(); param_gl.Add(name: "P_DEBIT_NO", value: GLRepo.Debit_Gl_No, dbType: DbType.String, direction: ParameterDirection.Input); param_gl.Add(name: "P_CREDIT_NO", value: GLRepo.Credit_Gl_No, dbType: DbType.String, direction: ParameterDirection.Input); param_gl.Add(name: "P_AMOUNT", value: GLRepo.Amount, dbType: DbType.Decimal, direction: ParameterDirection.Input); param_gl.Add(name: "P_NARRATION", value: GLRepo.Narration, dbType: DbType.String, direction: ParameterDirection.Input); param_gl.Add(name: "P_TID", value: GLRepo.TID, dbType: DbType.Decimal, direction: ParameterDirection.Input); param_gl.Add(name: "P_AUTH_ID", value: GlobalValue.User_ID, dbType: DbType.String, direction: ParameterDirection.Input); param_gl.Add(name: "P_AUTH_DATE", value: GlobalValue.Scheme_Today_Date, dbType: DbType.DateTime, direction: ParameterDirection.Input); param_gl.Add(name: "P_TRANS_DATE", value: GLRepo.Trans_Date, dbType: DbType.DateTime, direction: ParameterDirection.Input); conn.Execute("REV_JOURNAL_GL_TRANS", param_gl, commandType: CommandType.StoredProcedure); ts.Complete(); return(true); } catch (Exception ex) { string xx = ex.ToString(); throw; } finally { ts.Dispose(); if (con.State == ConnectionState.Open) { conn.Close(); } } } }
public ActionResult RemitConMigrationUpload(Remit_Con_Log remit_con_logrepo) { try { string extension = string.Empty; string file_loc = string.Empty; remitConLogstaticlist.Clear(); remitConLogDetailsStaticlist.Clear(); if (this.GetCmp <FileUploadField>("Remit_Con_Migration_remitfile_upload1").HasFile) { HttpPostedFile file_posted = this.GetCmp <FileUploadField>("Remit_Con_Migration_remitfile_upload1").PostedFile; extension = Path.GetExtension(file_posted.FileName); if (extension != ".xlsx" && extension != ".xls") { X.Msg.Show(new MessageBoxConfig { Title = "Error", Message = "selected file must be an excel file.Process aborted.", Buttons = MessageBox.Button.OK, Icon = MessageBox.Icon.INFO, Width = 350 }); return(this.Direct()); } file_loc = ImageWork.Upload_Any_File_Not_Image(file_posted); } string consString_excel = ""; switch (extension) { case ".xls": consString_excel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file_loc + ";Extended Properties=Excel 8.0;HDR=Yes;IMEX=2"; break; case ".xlsx": consString_excel = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file_loc + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\""; break; } OleDbConnection con_ex = new OleDbConnection(); OleDbCommand cmd = new OleDbCommand(); //string query1 = "Select COUNT(*) AS NOS From [SalaryData$]"; string query2 = "Select * From [SalaryData$]"; con_ex.ConnectionString = consString_excel; con_ex.Open(); cmd.Connection = con_ex; cmd.CommandText = query2; OleDbDataReader srda = cmd.ExecuteReader(); srda.Read(); remitConLogstaticlist.Clear(); if (srda.HasRows) { int iii = srda.GetSchemaTable() .Rows .OfType <DataRow>() .Count(); // DateTime con_date = Convert.ToDateTime("8/1/2018"); DateTime con_date = Convert.ToDateTime("10/1/2012"); for (int i = 0; i < iii + iii; i++) { con_date = con_date.AddMonths(1); string con_date_string = Convert.ToString(con_date.ToString("MMM-yy")); if (srda.GetSchemaTable() .Rows .OfType <DataRow>() .Any(row => row["ColumnName"].ToString() == con_date_string)) { //////////////////////////////////////////////// if ((con_date.ToString("MM")).ToString().Length == 1) { clog = "0" + (con_date.ToString("MM")); } else { clog = (con_date.ToString("MM")).ToString(); } /////////////////////////////////////////////////// //Generate con log Remit_Con_Log new_conlog = new Remit_Con_Log(); string conlog = "CON" + remit_con_logrepo.ES_Id + Convert.ToInt32(con_date.ToString("yyyy")) + clog + "01"; new_conlog.Con_Log_Id = conlog; new_conlog.Employer_Id = remit_con_logrepo.Employer_Id; new_conlog.ES_Id = remit_con_logrepo.ES_Id; new_conlog.For_Month = con_date.Month; new_conlog.For_Year = con_date.Year; remitConLogstaticlist.Add(new_conlog); } } while (srda.Read()) { Remit_Con_Log_Details new_conlogdetails = new Remit_Con_Log_Details(); if (srda["EmployeeId"] != DBNull.Value) { new_conlogdetails.Employee_Id = srda["EmployeeId"].ToString(); } //get esf id for employee string new_EsfID = rcul.GetRemit_EmployeeSchemeFunds_DataReaderFund(srda["EmployeeId"].ToString(), remit_con_logrepo.Scheme_Id + srda["FUND"].ToString()); if (string.IsNullOrEmpty(new_EsfID)) { X.Msg.Show(new MessageBoxConfig { Title = "Error", Message = "Problem with excel (" + srda["SURNAME"].ToString() + " " + srda["MIDDLENAME"].ToString() + " " + srda["FirstName"].ToString() + ")", Buttons = MessageBox.Button.OK, Icon = MessageBox.Icon.INFO, Width = 350 }); con_ex.Close(); return(this.Direct()); } foreach (var conlogcols in remitConLogstaticlist) { DateTime ddd = Convert.ToDateTime(conlogcols.For_Month.ToString() + "/" + conlogcols.For_Year.ToString()); string con_date_str = ddd.ToString("MMM-yy"); //////////////////////////////////////////////// if (conlogcols.For_Month.ToString().Length == 1) { plog = "0" + conlogcols.For_Month; } else { plog = conlogcols.For_Month.ToString(); } /////////////////////////////////////////////////// if (srda[con_date_str] != DBNull.Value && srda[con_date_str].ToString() != "-" && Convert.ToDecimal(srda[con_date_str]) != 0) { Remit_Con_Log_Details new_conlogdetails_Newest = new Remit_Con_Log_Details(); new_conlogdetails_Newest.Employee_Id = srda["EmployeeId"].ToString(); new_conlogdetails_Newest.Employee_Con = Convert.ToDecimal(srda[con_date_str]); new_conlogdetails_Newest.Con_Log_Id = conlogcols.Con_Log_Id; new_conlogdetails_Newest.Esf_Id = new_EsfID; new_conlogdetails_Newest.Employee_Amt = Convert.ToDecimal(srda[con_date_str]); new_conlogdetails_Newest.Purchase_Log_Id = remit_con_logrepo.ES_Id + conlogcols.For_Year + plog + "01"; new_conlogdetails_Newest.ES_Id = remit_con_logrepo.ES_Id; remitConLogDetailsStaticlist.Add(new_conlogdetails_Newest); } } } con_ex.Close(); } TransactionOptions tsOp = new TransactionOptions(); tsOp.IsolationLevel = System.Transactions.IsolationLevel.Snapshot; TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew, tsOp); tsOp.Timeout = TimeSpan.FromMinutes(12000); var app = new AppSettings(); using (OracleConnection conn = new OracleConnection(app.conString())) // { conn.Open(); try { //Push Con Log details foreach (var conlogcols in remitConLogstaticlist) { //string cnl = remitConLogrepo.Create_Con_Log(conlogcols); //////////////////////////////////////////////// if (conlogcols.For_Month.ToString().Length == 1) { clog = "0" + conlogcols.For_Month; } else { clog = conlogcols.For_Month.ToString(); } /////////////////////////////////////////////////// ///create log for the upload Remit Log var paramb = new DynamicParameters(); string batchno = ""; paramb.Add(name: "p_Con_Log_Id ", value: conlogcols.Con_Log_Id, dbType: DbType.String, direction: ParameterDirection.Input); paramb.Add(name: "p_Employer_Id", value: conlogcols.Employer_Id, dbType: DbType.String, direction: ParameterDirection.Input); paramb.Add(name: "p_ES_Id", value: conlogcols.ES_Id, dbType: DbType.String, direction: ParameterDirection.Input); paramb.Add(name: "p_For_Month", value: clog, dbType: DbType.String, direction: ParameterDirection.Input); paramb.Add(name: "p_For_Year", value: conlogcols.For_Year, dbType: DbType.Int32, direction: ParameterDirection.Input); paramb.Add(name: "p_DeadLine_Date", value: GlobalValue.Scheme_Today_Date, dbType: DbType.Date, direction: ParameterDirection.Input); paramb.Add(name: "p_ISINARREAS_YesNo", value: "NO", dbType: DbType.String, direction: ParameterDirection.Input); paramb.Add(name: "p_Unit_Purchased_YesNo", value: "NO", dbType: DbType.String, direction: ParameterDirection.Input); paramb.Add(name: "p_Total_Contribution", value: 0, dbType: DbType.Decimal, direction: ParameterDirection.Input); paramb.Add(name: "p_Maker_Id", value: GlobalValue.User_ID, dbType: DbType.String, direction: ParameterDirection.Input); paramb.Add(name: "p_Make_date", value: GlobalValue.Scheme_Today_Date, dbType: DbType.DateTime, direction: ParameterDirection.Input); paramb.Add(name: "p_Auth_Status", value: "AUTHORIZED", dbType: DbType.String, direction: ParameterDirection.Input); paramb.Add(name: "p_Log_Status", value: "ACTIVE", dbType: DbType.String, direction: ParameterDirection.Input); paramb.Add(name: "p_GracePeriod", value: 0, dbType: DbType.Int32, direction: ParameterDirection.Input); paramb.Add(name: "p_Con_Type", value: "MAIN_CONTRIBUTION", dbType: DbType.String, direction: ParameterDirection.Input); paramb.Add(name: "p_BatchNo", value: conlogcols.ES_Id + "01", dbType: DbType.String, direction: ParameterDirection.Input); conn.Execute(sql: "ADD_MIGRATE_ALL_CON_LOG", param: paramb, commandType: CommandType.StoredProcedure); batchno = paramb.Get <string>("p_Con_Log_Id "); //return batchno; } //create purchase log foreach (var conlogcols in remitConLogstaticlist) { // string cnl = remitConLogrepo.PurchaseSaveRecord(conlogcols); //////////////////////////////////////////////// if (conlogcols.For_Month.ToString().Length == 1) { plog = "0" + conlogcols.For_Month; } else { plog = conlogcols.For_Month.ToString(); } /////////////////////////////////////////////////// //Get Connection DynamicParameters param = new DynamicParameters(); param.Add(name: "P_PURCHASE_LOG_ID", value: conlogcols.ES_Id + conlogcols.For_Year + plog, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "P_CON_LOG_ID", value: conlogcols.Con_Log_Id, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "P_TRANS_DATE", value: GlobalValue.Scheme_Today_Date, dbType: DbType.Date, direction: ParameterDirection.Input); param.Add(name: "P_MAKER_ID", value: GlobalValue.User_ID, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "P_MAKE_DATE", value: GlobalValue.Scheme_Today_Date, dbType: DbType.Date, direction: ParameterDirection.Input); param.Add(name: "p_Purchase_Type", value: "MAIN_CONTRIBUTION", dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_BatchNo", value: conlogcols.ES_Id + "01", dbType: DbType.String, direction: ParameterDirection.Input); conn.Execute("ADD_MIGRATE_UNIT_PURCHASES", param, commandType: CommandType.StoredProcedure); } //create payment logs //{ // remit_con_logrepo.PaymentSaveRecord(remit_con_logrepo); //} //Push Con Log details foreach (var conlogcolsdetails in remitConLogDetailsStaticlist) { //remitConLogdetailsrepo.Create_Con_Log_Details(conlogcolsdetails); var param = new DynamicParameters(); ///create log for the upload Remit Log param.Add(name: "p_Employee_Id", value: conlogcolsdetails.Employee_Id, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_ESF_ID", value: conlogcolsdetails.Esf_Id, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_Con_Log_Id", value: conlogcolsdetails.Con_Log_Id, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_Employer_Con", value: conlogcolsdetails.Employer_Con, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "p_Employee_Con", value: conlogcolsdetails.Employee_Con, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "p_Employer_Bal", value: 0, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "p_Employee_Bal", value: 0, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "p_Employer_Amt_Used", value: 0, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "p_Employee_Amt_Used", value: conlogcolsdetails.Employee_Con, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "p_Maker_Id", value: GlobalValue.User_ID, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_Make_date", value: GlobalValue.Scheme_Today_Date, dbType: DbType.DateTime, direction: ParameterDirection.Input); param.Add(name: "p_Auth_Status", value: "AUTHORIZED", dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_Employee_Salary", value: 0, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "p_Employee_Sal_Rate", value: 0, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "p_Req_Con", value: 0, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "p_Difference", value: 0, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "p_Req_Status", value: "ACTIVE", dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_Con_Type", value: "MAIN_CONTRIBUTION", dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_BatchNo", value: conlogcolsdetails.ES_Id + "01", dbType: DbType.String, direction: ParameterDirection.Input); conn.Execute(sql: "ADD_REMIT_CON_DETAILS_MIG", param: param, commandType: CommandType.StoredProcedure); } //Push Contribution into purchase trans table foreach (var conlogcolsdetails in remitConLogDetailsStaticlist) { //remitConLogdetailsrepo.Create_Unit_Log_Details(conlogcolsdetails); var param = new DynamicParameters(); ///create log for the upload Remit Log param.Add(name: "p_ESF_ID", value: conlogcolsdetails.Esf_Id, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_Employer_Amt", value: conlogcolsdetails.Employer_Amt, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "p_Employee_Amt", value: conlogcolsdetails.Employee_Amt, dbType: DbType.Decimal, direction: ParameterDirection.Input); param.Add(name: "p_Purchase_Log_Id", value: conlogcolsdetails.Purchase_Log_Id, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_Purchase_Type", value: "MAIN_CONTRIBUTION", dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_BatchNo", value: conlogcolsdetails.ES_Id + "01", dbType: DbType.String, direction: ParameterDirection.Input); conn.Execute(sql: "ADD_MIGRATE_CON", param: param, commandType: CommandType.StoredProcedure); } ts.Complete(); X.Msg.Show(new MessageBoxConfig { Title = "Success", Message = "Employees history remittances uploaded successfully", Buttons = MessageBox.Button.OK, Icon = MessageBox.Icon.INFO, Width = 350 }); return(this.Direct()); } catch (TransactionException transexeption) { X.Mask.Hide(); X.Msg.Show(new MessageBoxConfig { Title = "Error", Message = transexeption.ToString(), Buttons = MessageBox.Button.OK, Icon = MessageBox.Icon.ERROR, Width = 350 }); //throw; } catch (Exception ex) { X.Mask.Hide(); X.Msg.Show(new MessageBoxConfig { Title = "Error", Message = ex.ToString(), Buttons = MessageBox.Button.OK, Icon = MessageBox.Icon.ERROR, Width = 350 }); //throw; } finally { ts.Dispose(); //a_value = a_value; if (conn.State == ConnectionState.Open) { conn.Close(); } if (con_ex.State == ConnectionState.Open) { con_ex.Close(); } } } //end for transscope return(this.Direct()); } catch (Exception ex) { string ora_code = ex.Message.Substring(0, 9); if (ora_code == "ORA-20000") { ora_code = "Record already exist. Process aborted.."; } else if (ora_code == "ORA-20100") { ora_code = "Record is uniquely defined in the system. Process aborted.."; } else { ora_code = ex.ToString(); } X.Msg.Show(new MessageBoxConfig { Title = "Error", Message = ora_code, Buttons = MessageBox.Button.OK, Icon = MessageBox.Icon.INFO, Width = 350 }); //logger.WriteLog(ex.Message); return(this.Direct()); } finally { } }
/// <summary> /// 申请类型 /// </summary> /// <param name="opreationType"></param> /// <returns></returns> //internal static string GetOpreationTypeValue(int opreationType) //{ // try // { // return SYDictBLL.GetItemName(DictTypes.OperationType, opreationType.ToString(), true); // } // catch (Exception ex) // { // Logger.LogError("ECCommon", "GetOpreationTypeValue", AppError.EROR, 0, ex); // return ""; // } //} //public static string UpLoadFile(FileUpload fileUploadControl, out string fileName, string userName) //{ // return UpLoadFile(fileUploadControl, out fileName, userName, "EC/DownLoad"); //} //public static string UpLoadFile(FileUpload fileUploadControl, out string fileName, string userName, string path) //{ // fileName = string.Empty; // string filePath = string.Empty; // if (fileUploadControl.HasFile) // { // //todo 处理文件同名的情况 // fileName = System.IO.Path.GetFileName(fileUploadControl.PostedFile.FileName); // AttachmentUtility attch = new AttachmentUtility(userName); // //上传附件并获取附件的分类路径,该路径应该保存至附件数据库表中 // filePath = attch.SaveAttach(fileUploadControl.PostedFile, path, fileName); // } // return filePath; //} //internal static string ContactPersionTypeValue(string type) //{ // try // { // string tmp = SYDictBLL.GetItemName(DictTypes.EC_ContactType, type, true); // if (string.IsNullOrEmpty(tmp)) // { // List<SYDictInfo> list = SYDictBLL.SelectByDictTypeSimple(DictTypes.VAR_ContactType); // foreach (SYDictInfo info in list) // { // if (info.DictStringValue == type) // return info.DictItemName; // } // return string.Empty; // } // else // { // return tmp; // } // } // catch (Exception ex) // { // Logger.LogError("ECCommon", "ContactPersionTypeValue", AppError.EROR, 0, ex); // return string.Empty; // } //} //internal static string GetEntTypeValue(string entType) //{ // try // { // return SYDictBLL.GetItemName(DictTypes.EC_EntType, entType, true); // } // catch (Exception ex) // { // Logger.LogError("ECCommon", "GetEntTypeValue", AppError.EROR, 0, ex); // return ""; // } //} //public static string GetAttachmentFullUrl(string userName, string path) //{ // try // { // AttachmentUtility attch = new AttachmentUtility(userName); // return attch.GetAttachmentFullUrl(path); // } // catch (Exception ex) // { // Logger.LogError("ECCommon", "GetAttachmentFullUrl", AppError.EROR, 0, ex); // return string.Empty; // } //} public static TransactionOptions GetTransactionOptions() { TransactionOptions transactionOptions = new TransactionOptions(); switch (ConfigurationManager.AppSettings["IsolationLevel"].ToString()) { case "Chaos": transactionOptions.IsolationLevel = IsolationLevel.Chaos; break; case "ReadCommitted": transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted; break; case "ReadUncommitted": transactionOptions.IsolationLevel = IsolationLevel.ReadUncommitted; break; case "RepeatableRead": transactionOptions.IsolationLevel = IsolationLevel.RepeatableRead; break; case "Serializable": transactionOptions.IsolationLevel = IsolationLevel.Serializable; break; case "Snapshot": transactionOptions.IsolationLevel = IsolationLevel.Snapshot; break; case "Unspecified": transactionOptions.IsolationLevel = IsolationLevel.Unspecified; break; default: transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted; break; } return transactionOptions; }
public void ReassignNewUser(sec_UserRepo repo_user) { var app = new AppSettings(); TransactionOptions tsOp = new TransactionOptions(); tsOp.IsolationLevel = System.Transactions.IsolationLevel.Snapshot; TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew, tsOp); tsOp.Timeout = TimeSpan.FromMinutes(20); string queryinternet = "select * from setup_company"; using (OracleConnection conn = new OracleConnection(app.conString())) // { try { //string password_hash = cSecurityRepo.AES_Encrypt(repo_user.Password); #region get email properties { var paramuser = new DynamicParameters(); paramuser.Add("P_USER_ID", repo_user.User_Id, DbType.String, ParameterDirection.Input); paramuser.Add("REMAIL", "", DbType.String, ParameterDirection.Output); paramuser.Add("RPASSWORD", "", DbType.String, ParameterDirection.Output); paramuser.Add("RFULLNAME", "", DbType.String, ParameterDirection.Output); conn.Execute("SEL_EMAIL_PROP", paramuser, commandType: CommandType.StoredProcedure); repo_user.Email = paramuser.Get <string>("REMAIL"); repo_user.Employee_Name = paramuser.Get <string>("RFULLNAME"); } #endregion #region reassign user var param = new DynamicParameters(); param.Add(name: "p_UserId", value: repo_user.User_Id, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_UserGroup", value: repo_user.User_Group_Id, dbType: DbType.String, direction: ParameterDirection.Input); param.Add(name: "p_MakerId", value: GlobalValue.User_ID, dbType: DbType.String, direction: ParameterDirection.Input); conn.Execute(sql: "REASSIGN_SEC_USER", param: param, commandType: CommandType.StoredProcedure); #endregion #region send email OracleCommand commandinternet = new OracleCommand(queryinternet, conn); conn.Open(); OracleDataReader readerinternet; readerinternet = commandinternet.ExecuteReader(); // Always call Read before accessing data. while (readerinternet.Read()) { internetRepo.smtp = (string)readerinternet["smtp"]; internetRepo.email_from = (string)readerinternet["email_from"]; internetRepo.email_password = (string)readerinternet["email_password"]; internetRepo.port = Convert.ToInt16(readerinternet["port"]); internetRepo.company_name = (string)readerinternet["company_name"]; } var msg = $@"Dear {repo_user.Employee_Name}, Please be informed that your Teksol Penfad user group has been changed. Contact the system's aadministrator for clarification.</b> <br/> <br/> Thank you. </b> <br/> <br/>{internetRepo.company_name}"; string from = internetRepo.email_from, pass = internetRepo.email_password, subj = "Change of User Group; Teksol Penfad", to = repo_user.Email; string smtp = internetRepo.smtp; int port = internetRepo.port; //string attach = DocumentName; internetRepo.SendIt(from, pass, subj, msg, to, smtp, port, internetRepo.company_name); #endregion ts.Complete(); } catch (Exception ex) { throw ex; } finally { ts.Dispose(); if (conn.State == ConnectionState.Open) { conn.Close(); } } } }
public void ProcessRequest(HttpContext context) { string new_hash = ""; // string ccode = ConfigurationManager.AppSettings["ccode"]; string xcode = ConfigurationManager.AppSettings["xcode"]; JavaScriptSerializer ser = new JavaScriptSerializer(); var pp = context.Request["vv"]; var pp2 = context.Request["vid"]; HttpPostedFile fu_logo_pic = null; HttpPostedFile fu_sup_doc = null; HttpPostedFile fu_app_doc = null; HttpPostedFile fu_merger_doc = null; HttpPostedFile fu_ass_doc = null; HttpPostedFile fu_pub_doc = null; HttpPostedFile fu_cert_doc = null; if (context.Request.Files.Count > 0) { var files = new List <string>(); // interate the files and save on the server foreach (string file in context.Request.Files) { if (file == "FileUpload") { fu_logo_pic = context.Request.Files[file]; // var vfile = postedFile.FileName.Replace("\"", string.Empty).Replace("'", string.Empty); // vfile = Stp(vfile); // string FileName = context.Server.MapPath("~/admin/ag_docz/" + vfile); // dd.cac_file = "/images/" + vfile; // dd.cac_file = "admin/ag_docz/" + vfile; // postedFile.SaveAs(FileName); } if (file == "FileUpload2") { fu_app_doc = context.Request.Files[file]; } //if (file == "FileUpload3") //{ // fu_cert_doc = context.Request.Files[file]; //} if (file == "FileUpload4") { fu_pub_doc = context.Request.Files[file]; } if (file == "FileUpload5") { fu_cert_doc = context.Request.Files[file]; } // dd.File_path = "/Images/Patient/" + vfile; } } GetData gg = new GetData(); string sp = ""; string serverpath = context.Server.MapPath("~/"); Registration tt = new Registration(); TransactionOptions transactionOptions = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = new TimeSpan(0, 15, 0) }; TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, transactionOptions); String vt = null; vt = tt.UpdateTrademarkTx2(pp, pp2, fu_logo_pic, fu_app_doc, fu_cert_doc, fu_pub_doc, serverpath); if (vt != null) { scope.Complete(); scope.Dispose(); } else { scope.Dispose(); throw new Exception("Test Exception"); } // string sp = gg.addAgent(dd); // Ipong.Classes.Retriever kp = new Ipong.Classes.Retriever(); // sendemail(dd.Email, dd.CompName, sp); try { // kp.updateRegistrationSysID4(sp, "PENDING"); } catch (Exception ee) { } context.Response.ContentType = "application/json"; context.Response.Write(ser.Serialize(vt)); }
public TransactionScopeStrategy(TransactionOptions transactionOptions, MsmqFailureInfoStorage failureInfoStorage) { this.transactionOptions = transactionOptions; this.failureInfoStorage = failureInfoStorage; }
/// <summary> /// 保存 /// </summary> private void OnSave() { if (string.IsNullOrEmpty(userName)) { MessageBox.Messager(this.Page, this.Page.Controls[0], "当前没有任何用户,请检查!", "操作错误", "error"); return; } List <string> newRolesList = new List <string>(); foreach (ListItem li in cbList.Items) { if (li.Selected) { newRolesList.Add(li.Value); } } if (newRolesList.Count == 0) { if (ViewState["RolesForUser"] == null) { MessageBox.Messager(this.Page, this.Page.Controls[0], "没有选中任何一项,请检查!", "操作错误", "error"); return; } } List <string> oldRolesList = new List <string>(); CompareInRole(ref newRolesList, ref oldRolesList); if (newRolesList.Count == 0 && oldRolesList.Count == 0) { return; } string errorMsg = string.Empty; try { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = IsolationLevel.ReadUncommitted; options.Timeout = TimeSpan.FromSeconds(90); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { if (newRolesList.Count > 0) { Roles.AddUserToRoles(userName, newRolesList.ToArray()); } if (oldRolesList.Count > 0) { Roles.RemoveUserFromRoles(userName, oldRolesList.ToArray()); } scope.Complete(); MessageBox.MessagerShow(this.Page, this.Page.Controls[0], "操作成功!"); } } catch (Exception ex) { errorMsg = ex.Message; } if (!string.IsNullOrEmpty(errorMsg)) { MessageBox.Messager(this.Page, this.Page.Controls[0], errorMsg, "系统提示"); return; } }
private async Task <PooledSession> BeginTransactionAsync(PooledSession session, TransactionOptions options, CancellationToken cancellationToken) { // While we're creating a transaction, it's as if we're preparing a new session - it's a period of time // where there's already an RPC in flight, and when it completes a session will be available. Interlocked.Increment(ref _inFlightSessionCreationCount); var request = new BeginTransactionRequest { Options = options }; try { var transaction = await session.BeginTransactionAsync(request, Options.Timeout, cancellationToken).ConfigureAwait(false); return(session.WithTransaction(transaction.Id, options.ModeCase)); } finally { Interlocked.Decrement(ref _inFlightSessionCreationCount); } }
/// <inheritdoc /> public ITransactionContext NewTransactionContext() { return(NewTransactionContext(TransactionOptions.GetDefault())); }
internal OletxCommittableTransaction CreateTransaction( TransactionOptions properties ) { OletxCommittableTransaction tx = null; RealOletxTransaction realTransaction = null; ITransactionShim transactionShim = null; Guid txIdentifier = Guid.Empty; OutcomeEnlistment outcomeEnlistment = null; // Demand the distributed transation permission to create one of // these. DistributedTransactionPermission txPerm = new DistributedTransactionPermission(PermissionState.Unrestricted); txPerm.Demand(); TransactionManager.ValidateIsolationLevel(properties.IsolationLevel); // Never create a transaction with an IsolationLevel of Unspecified. if (IsolationLevel.Unspecified == properties.IsolationLevel) { properties.IsolationLevel = configuredTransactionOptions.IsolationLevel; } properties.Timeout = TransactionManager.ValidateTimeout(properties.Timeout); this.dtcTransactionManagerLock.AcquireReaderLock(-1); try { // OletxTransactionIsolationLevel oletxIsoLevel = OletxTransactionManager.ConvertIsolationLevel(properties.IsolationLevel); UInt32 oletxTimeout = DtcTransactionManager.AdjustTimeout(properties.Timeout); outcomeEnlistment = new OutcomeEnlistment(); IntPtr outcomeEnlistmentHandle = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { outcomeEnlistmentHandle = HandleTable.AllocHandle(outcomeEnlistment); dtcTransactionManager.ProxyShimFactory.BeginTransaction( oletxTimeout, oletxIsoLevel, outcomeEnlistmentHandle, out txIdentifier, out transactionShim ); } catch (COMException ex) { OletxTransactionManager.ProxyException(ex); throw; } finally { if (transactionShim == null && outcomeEnlistmentHandle != IntPtr.Zero) { HandleTable.FreeHandle(outcomeEnlistmentHandle); } } realTransaction = new RealOletxTransaction( this, transactionShim, outcomeEnlistment, txIdentifier, oletxIsoLevel, true ); tx = new OletxCommittableTransaction(realTransaction); if (DiagnosticTrace.Information) { TransactionCreatedTraceRecord.Trace(SR.GetString(SR.TraceSourceOletx), tx.TransactionTraceId ); } } finally { this.dtcTransactionManagerLock.ReleaseReaderLock(); } return(tx); }
/// <inheritdoc /> public ITransactionContext NewTransactionContext(TransactionOptions options) { return(new TransactionContextProxy(this, options)); }
/// <summary> /// 使用事物 在事物里面的代码都是走master /// </summary> /// <param name="func"></param> /// <param name="scopeOption">TransactionScopeOption</param> /// <param name="options">TransactionOptions</param> public void UseTransaction(System.Func <DbContext <T>, bool> func, TransactionScopeOption scopeOption, TransactionOptions options) { using (var scope = new System.Transactions.TransactionScope(scopeOption, options)) { if (func(this)) { scope.Complete(); } } }
/// <summary> /// Gets all questions with answers from specified category ID /// </summary> /// <param name="categoryId">the categoryId</param> /// <returns>returns a list of questions along with their answers by given category id</returns> public List <Question> GetAllQuestionsAndAnswersByCategoryId(int categoryId) { List <Question> questions = new List <Question>(); Question question = null; Answer answer = null; TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { using (var conn = new SqlConnection(connectionString)) { using (SqlCommand command = conn.CreateCommand()) { conn.Open(); command.CommandText = "SELECT Question.id AS QuestId, Question.[description] AS QuestDesc, categoryId, Answer.id AS AnsId, Answer.[description] AS AnswerDesc, Answer.isCorrect AS AnsIsCorrect, Answer.questionId AS QuestionIdFromAnswer FROM Question JOIN Answer ON questionId = Question.id WHERE categoryID = @categoryId"; command.Parameters.Add("categoryId", SqlDbType.Int).Value = categoryId; var reader = command.ExecuteReader(); while (reader.Read()) { if (question == null || question.description != reader.GetString(reader.GetOrdinal("QuestDesc"))) { question = new Question(); question.id = reader.GetInt32(reader.GetOrdinal("QuestId")); question.description = reader.GetString(reader.GetOrdinal("QuestDesc")); question.category = new Category() { id = reader.GetInt32(reader.GetOrdinal("categoryId")) }; answer = new Answer(); answer.id = reader.GetInt32(reader.GetOrdinal("AnsId")); answer.description = reader.GetString(reader.GetOrdinal("AnswerDesc")); answer.isCorrect = reader.GetBoolean(reader.GetOrdinal("AnsIsCorrect")); answer.Question = new Question() { id = reader.GetInt32(reader.GetOrdinal("QuestionIdFromAnswer")) }; question.Answers.Add(answer); questions.Add(question); } else { answer = new Answer(); answer.id = reader.GetInt32(reader.GetOrdinal("AnsId")); answer.description = reader.GetString(reader.GetOrdinal("AnswerDesc")); answer.isCorrect = reader.GetBoolean(reader.GetOrdinal("AnsIsCorrect")); answer.Question = new Question() { id = reader.GetInt32(reader.GetOrdinal("QuestionIdFromAnswer")) }; question.Answers.Add(answer); } } scope.Complete(); conn.Close(); return(questions); } } } }
// // Drop(): // // If possible, function drops the student from the course. // // Return values: // -1 - error // 0 - dropped, no waitlist // 1 - dropped, enrolled student from waitlist // 2 - not enrolled, dropped from waitlist // 3 - student was not either enrolled or waitlisted // private int Drop(int sid, int cid) { int retries = 0; // make sure parameters are valid if (sid < 0 || cid < 0) { return(-1); } using (var db = new CoursemoDataContext()) { while (retries < 3) { try { var txOptions = new TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var transaction = new TransactionScope(TransactionScopeOption.Required, txOptions)) { // student enrolled, drop course and enroll first student on waitlist if (StudentEnrolled(sid, cid)) { db.UnregisterStudent(sid, cid); // candidate on waitlist exists int sidFromWaitList = GetFirstStudentFromWaitlist(cid); System.Threading.Thread.Sleep(_delay); if (sidFromWaitList != 0) { db.RegisterStudent(sidFromWaitList, cid); db.UnwaitlistStudent(sidFromWaitList, cid); db.SubmitChanges(); transaction.Complete(); return(1); } db.SubmitChanges(); transaction.Complete(); return(0); } // student not enrolled, but waitlisted, remove from waitlist else if (StudentWaitlisted(sid, cid)) { db.UnwaitlistStudent(sid, cid); db.SubmitChanges(); transaction.Complete(); return(2); } else { return(3); } } } catch (SqlException exc) { // deadlock if (exc.Number == 1205) { retries++; } } catch (Exception e) { MessageBox.Show("Drop(): " + e.Message); return(-1); } } // while } return(-1); }
// // Drop(): // // 0 - dropped, no waitlist // 1 - dropped, enrolled student from waitlist // 2 - not enrolled, dropped from waitlist // 3 - student was not either enrolled or waitlisted // private int Drop(int sid, int cid) { // make sure parameters are valid if (sid < 0 || cid < 0) { return(-1); } try { var txOptions = new TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var transaction = new TransactionScope(TransactionScopeOption.Required, txOptions)) { // student enrolled, drop course and enroll first student on waitlist if (StudentEnrolled(sid, cid)) { db.UnregisterStudent(sid, cid); // check for waitlist if (GetFirstStudentFromWaitlist(cid) != -1) { } db.SubmitChanges(); transaction.Complete(); return(0); } // student waitlisted, remove from waitlist else if (StudentWaitlisted(sid, cid)) { } // class is full, add to waitlist if (GetCourseCapacity(cid) - GetCurrentEnrollment(cid) < 1) { // check if student is not on waitlist already bool waitlisted = StudentWaitlisted(sid, cid); if (waitlisted) { return(2); } db.WaitlistStudent(sid, cid); db.SubmitChanges(); transaction.Complete(); return(3); } // enroll else { db.RegisterStudent(sid, cid); db.SubmitChanges(); transaction.Complete(); return(1); } } } catch (Exception e) { MessageBox.Show("Enroll(): " + e.Message); return(-1); } }
internal DistributedCommittableTransaction CreateTransaction(TransactionOptions options) { throw DistributedTransaction.NotSupported(); }
public void Example1() { RequireServer.Check().ClusterTypes(ClusterType.ReplicaSet, ClusterType.Sharded).Supports(Feature.Transactions); var connectionString = CoreTestConfiguration.ConnectionString.ToString(); DropCollections( connectionString, CollectionNamespace.FromFullName("mydb1.foo"), CollectionNamespace.FromFullName("mydb2.bar")); string result = null; // Start Transactions withTxn API Example 1 // For a replica set, include the replica set name and a seedlist of the members in the URI string; e.g. // string uri = "mongodb://mongodb0.example.com:27017,mongodb1.example.com:27017/?replicaSet=myRepl"; // For a sharded cluster, connect to the mongos instances; e.g. // string uri = "mongodb://mongos0.example.com:27017,mongos1.example.com:27017/"; var client = new MongoClient(connectionString); // Prereq: Create collections. var database1 = client.GetDatabase("mydb1"); var collection1 = database1.GetCollection <BsonDocument>("foo").WithWriteConcern(WriteConcern.WMajority); collection1.InsertOne(new BsonDocument("abc", 0)); var database2 = client.GetDatabase("mydb2"); var collection2 = database2.GetCollection <BsonDocument>("bar").WithWriteConcern(WriteConcern.WMajority); collection2.InsertOne(new BsonDocument("xyz", 0)); // Step 1: Start a client session. using (var session = client.StartSession()) { // Step 2: Optional. Define options to use for the transaction. var transactionOptions = new TransactionOptions( readPreference: ReadPreference.Primary, readConcern: ReadConcern.Local, writeConcern: WriteConcern.WMajority); // Step 3: Define the sequence of operations to perform inside the transactions var cancellationToken = CancellationToken.None; // normally a real token would be used result = session.WithTransaction( (s, ct) => { collection1.InsertOne(s, new BsonDocument("abc", 1), cancellationToken: ct); collection2.InsertOne(s, new BsonDocument("xyz", 999), cancellationToken: ct); return("Inserted into collections in different databases"); }, transactionOptions, cancellationToken); } //End Transactions withTxn API Example 1 result.Should().Be("Inserted into collections in different databases"); var collection1Documents = collection1.Find(FilterDefinition <BsonDocument> .Empty).ToList(); collection1Documents.Count.Should().Be(2); collection1Documents[0]["abc"].Should().Be(0); collection1Documents[1]["abc"].Should().Be(1); var collection2Documents = collection2.Find(FilterDefinition <BsonDocument> .Empty).ToList(); collection2Documents.Count.Should().Be(2); collection2Documents[0]["xyz"].Should().Be(0); collection2Documents[1]["xyz"].Should().Be(999); }
public static bool op_Inequality(TransactionOptions x, TransactionOptions y) { }
internal OletxCommittableTransaction CreateTransaction( TransactionOptions properties ) { OletxCommittableTransaction tx = null; RealOletxTransaction realTransaction = null; ITransactionShim transactionShim = null; Guid txIdentifier = Guid.Empty; OutcomeEnlistment outcomeEnlistment = null; // Demand the distributed transation permission to create one of // these. DistributedTransactionPermission txPerm = new DistributedTransactionPermission( PermissionState.Unrestricted ); txPerm.Demand(); TransactionManager.ValidateIsolationLevel( properties.IsolationLevel ); // Never create a transaction with an IsolationLevel of Unspecified. if ( IsolationLevel.Unspecified == properties.IsolationLevel ) { properties.IsolationLevel = configuredTransactionOptions.IsolationLevel; } properties.Timeout = TransactionManager.ValidateTimeout( properties.Timeout ); this.dtcTransactionManagerLock.AcquireReaderLock( -1 ); try { // OletxTransactionIsolationLevel oletxIsoLevel = OletxTransactionManager.ConvertIsolationLevel( properties.IsolationLevel ); UInt32 oletxTimeout = DtcTransactionManager.AdjustTimeout( properties.Timeout ); outcomeEnlistment = new OutcomeEnlistment(); IntPtr outcomeEnlistmentHandle = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { outcomeEnlistmentHandle = HandleTable.AllocHandle( outcomeEnlistment ); dtcTransactionManager.ProxyShimFactory.BeginTransaction( oletxTimeout, oletxIsoLevel, outcomeEnlistmentHandle, out txIdentifier, out transactionShim ); } catch ( COMException ex ) { OletxTransactionManager.ProxyException( ex ); throw; } finally { if ( transactionShim == null && outcomeEnlistmentHandle != IntPtr.Zero ) { HandleTable.FreeHandle( outcomeEnlistmentHandle ); } } realTransaction = new RealOletxTransaction( this, transactionShim, outcomeEnlistment, txIdentifier, oletxIsoLevel, true ); tx = new OletxCommittableTransaction( realTransaction ); if ( DiagnosticTrace.Information ) { TransactionCreatedTraceRecord.Trace( SR.GetString( SR.TraceSourceOletx ), tx.TransactionTraceId ); } } finally { this.dtcTransactionManagerLock.ReleaseReaderLock(); } return tx; }
public CommittableTransaction(TransactionOptions options) {}
public TransactionScope(TransactionScopeOption scopeOption, TransactionOptions transactionOptions) { }
public static void RunTest() { PermissiveCertificatePolicy.Enact("CN=HTTPS-Server"); Console.Write("Initializing Sales Proxy..."); BicycleWorldSalesServiceClient proxy = new BicycleWorldSalesServiceClient("wsHttpBinding_BicycleWorldSalesService"); Console.WriteLine(" done"); proxy.ClientCredentials.UserName.UserName = "******"; proxy.ClientCredentials.UserName.Password = "******"; // Test the operations in the service try { Console.WriteLine(proxy.Test()); Console.WriteLine("Press ENTER to start shopping cart"); Console.ReadLine(); TransactionOptions transactionOptions = new TransactionOptions(); transactionOptions.IsolationLevel = IsolationLevel.RepeatableRead; transactionOptions.Timeout = new TimeSpan(0, 1, 0); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOptions)) { IDictionary <string, string> context = null; IContextManager contextManager = proxy.InnerChannel.GetProperty <IContextManager>(); if (context != null) { contextManager.SetContext(context); } proxy.AddItemToCart("BK-M18B-42"); if (context == null) { context = contextManager.GetContext(); } proxy.AddItemToCart("BK-M18B-42"); proxy.AddItemToCart("BB-7421"); proxy.AddItemToCart("BK-R19B-44"); proxy.RemoveItemFromCart("BK-R19B-44"); Console.WriteLine(proxy.GetShoppingCart()); if (proxy.Checkout()) { scope.Complete(); Console.WriteLine("Goods purchased."); } } Console.WriteLine(); // Disconnect from the service proxy.Close(); } catch (FaultException <SystemFault> sf) { Console.WriteLine("SystemFault {0}: {1}\n{2}", sf.Detail.SystemOperation, sf.Detail.SystemMessage, sf.Detail.SystemReason); } catch (FaultException <DatabaseFault> dbf) { Console.WriteLine("DatabaseFault {0}: {1}\n{2}", dbf.Detail.DbOperation, dbf.Detail.DbMessage, dbf.Detail.DbReason); } catch (FaultException e) { Console.WriteLine("{0}: {1}", e.Code.Name, e.Reason); } catch (Exception e) { Console.WriteLine("General exception: {0}", e.Message); Console.WriteLine("Inner Exception: {0}", e.InnerException); } Console.WriteLine("Press ENTER to continue"); Console.ReadLine(); }
/// <summary> /// Processes a booking to be made - flight /// </summary> /// <param name="newTravelBooking"></param> /// <param name="cardForBooking"></param> /// <returns>Returns a travel booking object updated with all the booking information</returns> public TravelBooking ProcessAirTravelBooking(TravelBooking newTravelBooking, Card cardForBooking) { bool isAvailable = false; string bookingReferenceNo = string.Empty; PaymentStatus status; string paymentReferenceNumber = string.Empty; //Checking for Availability of Schedules before porcessing the booking //1. Check for Availablity try { isAvailable = CheckAvailabilityForBooking(newTravelBooking); } catch (Search.FlightSeatsAvailabilityException Ex) { throw Ex; } catch (Exception ex) { throw new Search.FlightSeatsAvailabilityException("Unable to process booking. Please try again", ex); } //If available, then make payment and store in database using transactions //If Available then do rest of the code if (isAvailable) { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.MaximumTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { try { //Processing the payment paymentReferenceNumber = ProcessAirTravelBookingPayment(newTravelBooking, cardForBooking, out status); //Store in database if (status == PaymentStatus.Success) { //Persist in the database foreach (TravelDirection Direction in newTravelBooking.GetBookingTravelDirections()) { bookingReferenceNo = StoreBookingInDatabase(newTravelBooking.GetBookingForTravel(Direction)); newTravelBooking.GetBookingForTravel(Direction).ReferenceNo = bookingReferenceNo; } scope.Complete(); } } catch (PaymentProcessException ex) { scope.Dispose(); throw ex; } catch (InvalidBookingTypeException ex) { scope.Dispose(); throw ex; } catch (StoreBookingInDatabaseException ex) { scope.Dispose(); throw new BookingException("Unable to Book Tickets", ex); } catch (Exception ex) { scope.Dispose(); throw new BookingException("Unable to Book Tickets", ex); } } } return(newTravelBooking); }
public string UpdateSiteSetup(string sType, DataTable bindingSiteDt, DataTable bindingSitePlotDt, DataTable bindingSiteDocDt, decimal pcfDocGuid, decimal stackId) { string result = string.Empty; TransactionOptions to = new TransactionOptions(); to.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; ProfitCashflow.oPcfDM.conn.Close(); using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew, to, EnterpriseServicesInteropOption.Full)) { SqlDataAdapter da = new SqlDataAdapter(); try { if (bindingSiteDt.GetChanges() != null) { if (sType == "I") { da.InsertCommand = new SqlCommand("SPN_XP_INS_SITE_SETUP", ProfitCashflow.oPcfDM.conn); da.InsertCommand.CommandType = CommandType.StoredProcedure; CreateSiteCommand(da.InsertCommand); } else if (sType == "U") { da.UpdateCommand = new SqlCommand("SPN_XP_UPD_SITE_SETUP", ProfitCashflow.oPcfDM.conn); da.UpdateCommand.CommandType = CommandType.StoredProcedure; CreateSiteCommand(da.UpdateCommand); } da.Update(bindingSiteDt.GetChanges()); } if (bindingSitePlotDt.GetChanges() != null) { UpdateSitePlot(bindingSitePlotDt.GetChanges(), da); } if (bindingSiteDocDt.GetChanges() != null) { UpdateSiteDoc(bindingSiteDocDt.GetChanges(), da); } if (sType == "I") { result = RetrieveSystemCreatedStack(bindingSiteDt.Rows[0]["SITE_CODE"].ToString(), Convert.ToDecimal(bindingSiteDt.Rows[0]["COMPANY_ID"]), ProfitCashflow.oPcfDM.UserName, pcfDocGuid, stackId, da); if (!string.IsNullOrEmpty(result)) { ts.Dispose(); return(result); } } ts.Complete(); } catch (Exception ex) { ts.Dispose(); throw ex; } finally { if (da != null) { da.Dispose(); } } } ProfitCashflow.oPcfDM.conn.Open(); return(result); }
/// <summary> /// 任务实体 /// </summary> /// <param name="lastExecuteTime"></param> public override void Execute(DateTime?lastExecuteTime) { try { LogService.Info("任务开始", LogInfoCategory); DataTable m_dt = QA_QuestionBll.GetInstance().GetToEndList(); if (m_dt != null && m_dt.Rows.Count > 0) { int total = 0; for (int i = 0; i < m_dt.Rows.Count; i++) { int sysno = int.Parse(m_dt.Rows[i]["sysno"].ToString()); DataTable m_answer = QA_AnswerBll.GetInstance().GetListByQuest(1, 10000, sysno, ref total); m_answer.Columns.Add("commcount"); m_answer.Columns.Add("score"); int totalcomm = 0; int totallenth = 0; int totallove = 0; int[,] tmpresult = new int[3, 2]; for (int j = 0; j < m_answer.Rows.Count; j++) { totallenth += m_answer.Rows[j]["Context"].ToString().Length; totallove += int.Parse(m_answer.Rows[j]["Love"].ToString()); DataTable m_comm = QA_CommentBll.GetInstance().GetListByAnswer(int.Parse(m_answer.Rows[j]["SysNo"].ToString())); totalcomm += m_comm.Rows.Count; m_answer.Rows[j]["commcount"] = m_comm.Rows.Count.ToString(); m_answer.Rows[j]["score"] = 0; } for (int j = 0; j < m_answer.Rows.Count; j++) { double tmp = Convert.ToDouble(m_answer.Rows[j]["Context"].ToString().Length *m_answer.Rows.Count) / Convert.ToDouble(totallenth); tmp -= 1; if (tmp > 0) { m_answer.Rows[j]["score"] = int.Parse(m_answer.Rows[j]["score"].ToString()) + Math.Floor(tmp * 10) * Math.Floor(tmp * 10) * 10; } tmp = Convert.ToDouble(m_answer.Rows[j]["Love"].ToString()) * Convert.ToDouble(m_answer.Rows.Count) / Convert.ToDouble(totallove); tmp -= 1; if (tmp > 0) { m_answer.Rows[j]["score"] = int.Parse(m_answer.Rows[j]["score"].ToString()) + Math.Floor(tmp * 10) * Math.Floor(tmp * 10) * 5; } tmp = Convert.ToDouble(m_answer.Rows[j]["commcount"].ToString()) * Convert.ToDouble(m_answer.Rows.Count) / Convert.ToDouble(totalcomm); tmp -= 1; if (tmp > 0) { m_answer.Rows[j]["score"] = int.Parse(m_answer.Rows[j]["score"].ToString()) + Math.Floor(tmp * 10) * Math.Floor(tmp * 10) * 3; } } TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.DefaultTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { m_answer.DefaultView.Sort = "award asc, score desc"; DataTable dtTemp = m_answer.DefaultView.ToTable(); if (dtTemp.Rows.Count == 1) { QA_AnswerBll.GetInstance().SetAward(QA_AnswerBll.GetInstance().GetModel(int.Parse(dtTemp.Rows[0]["SysNo"].ToString())), QA_QuestionBll.GetInstance().GetModel(int.Parse(m_dt.Rows[i]["SysNo"].ToString())), int.Parse(m_dt.Rows[i]["Award"].ToString()) - QA_AnswerBll.GetInstance().GetUsedAward(int.Parse(dtTemp.Rows[0]["SysNo"].ToString()))); } else { int awardremain = int.Parse(m_dt.Rows[i]["Award"].ToString()) - QA_AnswerBll.GetInstance().GetUsedAward(int.Parse(dtTemp.Rows[0]["SysNo"].ToString())); int award1 = awardremain * int.Parse(m_dt.Rows[0]["score"].ToString()) / (int.Parse(m_dt.Rows[0]["score"].ToString()) + int.Parse(m_dt.Rows[1]["score"].ToString())); int award2 = awardremain - award1; QA_AnswerBll.GetInstance().SetAward(QA_AnswerBll.GetInstance().GetModel(int.Parse(dtTemp.Rows[0]["SysNo"].ToString())), QA_QuestionBll.GetInstance().GetModel(int.Parse(m_dt.Rows[i]["SysNo"].ToString())), award1); QA_AnswerBll.GetInstance().SetAward(QA_AnswerBll.GetInstance().GetModel(int.Parse(dtTemp.Rows[1]["SysNo"].ToString())), QA_QuestionBll.GetInstance().GetModel(int.Parse(m_dt.Rows[i]["SysNo"].ToString())), award2); } USR_MessageMod m_notice = new USR_MessageMod(); m_notice.CustomerSysNo = int.Parse(m_dt.Rows[i]["CustomerSysNo"].ToString()); m_notice.Title = AppConst.AutoSendAward.Replace("@url", AppConfig.HomeUrl() + "Quest/Question.aspx?id=" + m_dt.Rows[i]["SysNo"].ToString()) .Replace("@question", m_dt.Rows[i]["Title"].ToString()); m_notice.DR = 0; m_notice.IsRead = 0; m_notice.Context = ""; m_notice.TS = DateTime.Now; m_notice.Type = (int)AppEnum.MessageType.notice; USR_MessageBll.GetInstance().AddMessage(m_notice); scope.Complete(); //EventLog.WriteEntry("Hi,I'm wiseman"); } } } LogService.Info("任务结束", LogInfoCategory); } catch (Exception ex) { LogService.Error("RewardTask 任务失败", LogInfoCategory); LogService.Error(ex, LogInfoCategory); } finally { this.NextExecuteTime = DateTime.Now.AddHours(1); } }
public TransactionScope(TransactionScopeOption scopeOption, TransactionOptions transactionOptions, EnterpriseServicesInteropOption interopOption) { }
/// <summary> /// 退款 /// </summary> /// <param name="entity"></param> public virtual void Refund(RefundBalanceInfo entity) { RefundBalanceInfo refundBalanceInfo; SOInfo soInfo; VerifyForRefund(entity, out soInfo, out refundBalanceInfo); soInfo.BaseInfo.GiftCardPay = soInfo.BaseInfo.GiftCardPay ?? 0M; refundBalanceInfo.GiftCardAmt = refundBalanceInfo.GiftCardAmt ?? 0M; refundBalanceInfo.PointAmt = refundBalanceInfo.PointAmt ?? 0; decimal availShipPrice, cashRemoveGiftCard, availGiftCard, totalRoBoBalanceAmt; int availPointAmt; CalculateAvailRefundAmt(entity, soInfo.BaseInfo, out availShipPrice, out cashRemoveGiftCard, out availGiftCard, out availPointAmt, out totalRoBoBalanceAmt); if (refundBalanceInfo.CashAmt > cashRemoveGiftCard || refundBalanceInfo.GiftCardAmt > availGiftCard || refundBalanceInfo.PointAmt > availPointAmt) { throw new BizException( ResouceManager.GetMessageString("RMA.RefundBalance", "Refund_ReCreateRefundBalance")); } decimal ROAmt; PreCheckForRefund(refundBalanceInfo, totalRoBoBalanceAmt, availShipPrice, out ROAmt); int tmpNewOrderSysNo = 0; #region 事务中执行退款操作 TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.DefaultTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { AbandonPoint(refundBalanceInfo); if (refundBalanceInfo.RefundPayType == RefundPayType.PrepayRefund) { if (refundBalanceInfo.CashAmt.Value > soInfo.BaseInfo.SOAmount) { throw new BizException(ResouceManager.GetMessageString("RMA.RefundBalance", "Refund_CashAmtValid")); } RefundPrepay(refundBalanceInfo); } else if (refundBalanceInfo.RefundPayType == RefundPayType.TransferPointRefund) { if (refundBalanceInfo.CashAmt.Value > soInfo.BaseInfo.SOAmount) { throw new BizException(ResouceManager.GetMessageString("RMA.RefundBalance", "Refund_CashAmtValid")); } TransferPointRefund(refundBalanceInfo); } CreateSOIncome(refundBalanceInfo); // 现金部分生成新礼品卡 RefundInfo refundInfo = refundProcessor.LoadBySysNo(entity.OriginalRefundSysNo.Value); if (refundBalanceInfo.RefundPayType == RefundPayType.GiftCardRefund && refundBalanceInfo.CashAmt > 0) { refundProcessor.CreateElectronicGiftCard(refundInfo, refundBalanceInfo.CashAmt.Value, "ROBalance"); } //礼品卡部分依次退返 if (refundBalanceInfo.GiftCardAmt > 0) { refundProcessor.RefundGiftCard(refundInfo, refundBalanceInfo.GiftCardAmt.Value, "ROBalance", refundBalanceInfo.SysNo.Value); } UpdateRefundBalanceForRefund(entity.SysNo.Value, ROAmt, out tmpNewOrderSysNo); //20130808 Chester Added:完成RMA退款调整单待审核- 待办事项: EventPublisher.Publish <RMACompleteRefundBalanceWaitingForAuditMessage>(new RMACompleteRefundBalanceWaitingForAuditMessage() { RefundBalanceSysNo = entity.SysNo.Value, RefundSysNo = entity.OriginalRefundSysNo.Value, CurrentUserSysNo = ServiceContext.Current.UserSysNo }); scope.Complete(); } #endregion //发送SSB string stockID = ExternalDomainBroker.GetSOItemList(soInfo.SysNo.Value).FirstOrDefault().StockSysNo.Value.ToString(); if (stockID != null && soInfo != null) { //if (stockID.Trim() == RMAConst.WarehouseNo_GZ // || stockID.Trim() == RMAConst.WarehouseNo_XA // || soInfo.InvoiceInfo.IsVAT == true) if (soInfo.InvoiceInfo.IsVAT == true) { ObjectFactory <SendSSBProcessor> .Instance.SendADJUSTMessage(tmpNewOrderSysNo, stockID, entity.CompanyCode); } } }