public void GuardarAsignaciones(IList<int> ordenesVenta, IList<Usuario> asistentes) { try { var transactionOptions = new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted }; using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) { foreach (var idOrdenVenta in ordenesVenta) { var ordenVenta = _orderVentaDA.ObtenerPorID(idOrdenVenta); var asistenteConMenorCarga = asistentes.OrderBy(p => p.CantidadOV).FirstOrDefault(); if (asistenteConMenorCarga != null) { asistenteConMenorCarga.CantidadOV++; ordenVenta.Estado = Constantes.EstadoOrdenVenta.Asignado; ordenVenta.AsistentePlaneamiento = asistenteConMenorCarga; _orderVentaDA.AsignarAsistentePlaneamiento(ordenVenta); } } transactionScope.Complete(); } } catch (Exception ex) { throw ThrowException(ex, MethodBase.GetCurrentMethod().Name); } }
public virtual ITransactionContext Begin() { var options = new TransactionOptions() { IsolationLevel = IsolationLevel.ReadUncommitted }; this.transaction = new TransactionScope(TransactionScopeOption.Required, options); return this; }
public string GetThumbnail(int id, System.IO.Stream strm) { string fileName = this.DB.Products.Where(a => a.ProductID == id).Select(a => a.ThumbnailPhotoFileName).FirstOrDefault(); if (string.IsNullOrEmpty(fileName)) { return(""); } System.Transactions.TransactionOptions top = new System.Transactions.TransactionOptions(); top.Timeout = TimeSpan.FromSeconds(60); top.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, top)) using (DbConnection conn = DBConnectionFactory.GetRIAppDemoConnection()) { byte[] bytes = new byte[64 * 1024]; string fldname = "ThumbNailPhoto"; BlobStream bstrm = new BlobStream(conn as SqlConnection, "[SalesLT].[Product]", fldname, string.Format("WHERE [ProductID]={0}", id)); bstrm.Open(); int cnt = bstrm.Read(bytes, 0, bytes.Length); while (cnt > 0) { strm.Write(bytes, 0, cnt); cnt = bstrm.Read(bytes, 0, bytes.Length); } bstrm.Close(); scope.Complete(); } return(fileName); }
public void SaveThumbnail(int id, string fileName, System.IO.Stream strm) { var product = this.DB.Products.Where(a => a.ProductID == id).FirstOrDefault(); if (product == null) { throw new Exception("Product is not found"); } TransactionOptions topts = new System.Transactions.TransactionOptions(); topts.Timeout = TimeSpan.FromSeconds(60); topts.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (TransactionScope trxScope = new TransactionScope(TransactionScopeOption.Required, topts)) using (DbConnection conn = DBConnectionFactory.GetRIAppDemoConnection()) { System.IO.BinaryReader br = new System.IO.BinaryReader(strm); byte[] bytes = br.ReadBytes(64 * 1024); string fldname = "ThumbNailPhoto"; BlobStream bstrm = new BlobStream(conn as SqlConnection, "[SalesLT].[Product]", fldname, string.Format("WHERE [ProductID]={0}", id)); bstrm.InitColumn(); bstrm.Open(); while (bytes != null && bytes.Length > 0) { bstrm.Write(bytes, 0, bytes.Length); bytes = br.ReadBytes(64 * 1024);; } bstrm.Close(); br.Close(); trxScope.Complete(); } product.ThumbnailPhotoFileName = fileName; this.DB.SubmitChanges(); }
public void Abandon(int masterSysNo, int userSysNo) { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.DefaultTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { //�����dz�ʼ״̬ POInfo dbInfo = LoadPO(masterSysNo); if ( dbInfo == null ) throw new BizException("does not exist this po sysno"); if ( dbInfo.Status != (int)AppEnum.POStatus.Origin ) throw new BizException("status is not origin now, abandon failed"); //���� ���š�״̬������� Hashtable ht = new Hashtable(4); ht.Add("SysNo", masterSysNo); ht.Add("Status", (int)AppEnum.POStatus.Abandon); if ( 1!=new PODac().UpdateMaster(ht)) throw new BizException("expected one-row update failed, verify failed "); ProductIDManager.GetInstance().AbandonProductIDsByPO(masterSysNo); scope.Complete(); } }
public MsmqScopeOptions(TimeSpan? requestedTimeout = null, IsolationLevel? requestedIsolationLevel = null) { var timeout = TransactionManager.DefaultTimeout; var isolationLevel = IsolationLevel.ReadCommitted; if (requestedTimeout.HasValue) { var maxTimeout = GetMaxTimeout(); if (requestedTimeout.Value > maxTimeout) { throw new ConfigurationErrorsException( "Timeout requested is longer than the maximum value for this machine. Override using the maxTimeout setting of the system.transactions section in machine.config"); } timeout = requestedTimeout.Value; } if (requestedIsolationLevel.HasValue) { isolationLevel = requestedIsolationLevel.Value; } TransactionOptions = new TransactionOptions { IsolationLevel = isolationLevel, Timeout = timeout }; }
private static WaitCallback JobEntity(TransactionOptions options) { return state => { try { using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, options)) { using (var context = new ProjectTemplate_DevEntities()) { var element = context.Element.First(d => d.Id == "d0530ea7-639f-4d5e-91fb-1a4fed1debfe"); var intInternalName = Int32.Parse(element.InternalName); PrintMessage("ReadValue=" + intInternalName.ToString()); element.InternalName = (intInternalName + 1).ToString(); PrintMessage("Incrementing to" + element.InternalName); Thread.Sleep(2000); context.SaveChanges(); // Save changes to DB PrintMessage("Saving"); Thread.Sleep(2000); } scope.Complete(); // Commit transaction PrintMessage("Commit"); } } catch (Exception e) { PrintMessage( e.Message); }finally { ((ManualResetEvent)state).Set(); } }; }
public async Task Should_Fall_Inhability_Validate_Incidents() { var txOptions = new System.Transactions.TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using var scope = new TransactionScope(TransactionScopeOption.Required, txOptions, TransactionScopeAsyncFlowOption.Enabled); //Act Guid instanceId = Guid.NewGuid(); //Guid.Parse("33D7CA50-39E9-4B14-B482-5FCBEC07E8DB"); Guid identityWorkId = Guid.NewGuid(); //Guid.Parse("7535C4E6-4712-4DD6-955D-FCA86E054D49"); var middlewareManager = new MiddlewareManager <Inhability>(new BaseRecordManager <Inhability>(), new InhabilityValidator()); Guid id = Guid.Empty; try { var inhabilities = await new InhabilityManagerUT().CreateDefaultAsync <Inhability>(identityWorkId, instanceId); var employeeId = inhabilities.FirstOrDefault().EmployeeID; var incidentTypeId = inhabilities.FirstOrDefault().IncidentTypeID; var incidents = await new IncidentManagerUT().CreateDefaultAsync <Incident>(identityWorkId, instanceId, employeeId, incidentTypeId); Assert.False(true); } catch (Exception ex) { Assert.Contains("Existe 1 o más registros que ya existen en la base de datos con el campo: Folio", ex.Message); } }
/// <summary> /// ����rma�� /// </summary> /// <param name="rmaInfo"></param> public void AddRMA(RMARequestInfo rmaInfo) { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.DefaultTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { rmaInfo.SysNo = SequenceDac.GetInstance().Create("RMA_Request_Sequence"); rmaInfo.RequestID = this.BuildRMAID(rmaInfo.SysNo); rmaInfo.Status = (int)AppEnum.RMAStatus.Origin; this.InsertRequest(rmaInfo); foreach (RMARegisterInfo rmaItem in rmaInfo.ItemHash.Values) { rmaItem.SysNo = SequenceDac.GetInstance().Create("RMA_Register_Sequence"); rmaItem.Status = (int)AppEnum.RMARequestStatus.Orgin; rmaItem.OwnBy = (int)AppEnum.RMAOwnBy.Origin; rmaItem.Location = (int)AppEnum.RMALocation.Origin; RMARegisterManager.GetInstance().InsertRegister(rmaItem); RMARequestItemInfo rmaiteminfo = new RMARequestItemInfo(); rmaiteminfo.RegisterSysNo = rmaItem.SysNo; rmaiteminfo.RequestSysNo = rmaInfo.SysNo; this.InsertRequestItem(rmaiteminfo); } scope.Complete(); } //SendMail(rmaInfo); }
public void CommendCustomerEmailList(int CustomerSysNo,decimal FreeShipFee,Hashtable ht,string EmailBody) { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.DefaultTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { if (!VerifyValidEmailList(ht)) throw new BizException("�����ظ��Ƽ�!"); CustomerInfo cInfo = CustomerManager.GetInstance().Load(CustomerSysNo); string CustomerName = cInfo.CustomerName; string mailSubject = CustomerName + " �����Ƽ�ORS�̳���"; foreach (string email in ht.Keys) { UpdateCustomerCommendStatus(email, (int) AppEnum.CommendStatus.Origin); string mailBody = "@FriendName<br>" + EmailBody + "<br>@CustomerName<br>" + DateTime.Now.ToString(AppConst.DateFormat); mailBody = mailBody.Replace("@FriendName", ht[email].ToString()); mailBody = mailBody.Replace("@CustomerName", CustomerName); EmailInfo oEmail = new EmailInfo(email, mailSubject, mailBody); EmailManager.GetInstance().InsertEmail(oEmail); } SetFreeShipFee(CustomerSysNo, FreeShipFee, (int)AppEnum.FreeShipFeeLogType.CommendCustomer, "�Ƽ�����Email"); scope.Complete(); } }
public int AddItem(RMARevertInfo oParam) { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.DefaultTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { foreach (int registerSysNo in oParam.ItemHash.Keys) { RMARevertItemInfo oRevertItem = new RMARevertItemInfo(); oRevertItem.RegisterSysNo = registerSysNo; oRevertItem.RevertSysNo = oParam.SysNo; //��Register�ֿ��д��RMA_Revert_Item int revertStockSysNo = AppConst.IntNull; DataRow regdr = RMARegisterManager.GetInstance().GetRegisterRow(registerSysNo); revertStockSysNo = Util.TrimIntNull(regdr["RevertStockSysNo"]); oRevertItem.StockSysNo = Util.TrimIntNull(revertStockSysNo); this.InsertRevertItem(oRevertItem); } scope.Complete(); return oParam.SysNo; } }
public static TransactionScope CreateTransactionScope() { var transactionOptions = new TransactionOptions(); transactionOptions.IsolationLevel = IsolationLevel.ReadUncommitted; transactionOptions.Timeout = TimeSpan.FromSeconds(300); return new TransactionScope(TransactionScopeOption.Required, transactionOptions); }
/// <summary> /// Initializes the <see cref="IDequeueMessages" />. /// </summary> /// <param name="address">The address to listen on.</param> /// <param name="transactionSettings">The <see cref="TransactionSettings" /> to be used by <see cref="IDequeueMessages" />.</param> /// <param name="tryProcessMessage">Called when a message has been dequeued and is ready for processing.</param> /// <param name="endProcessMessage">Needs to be called by <see cref="IDequeueMessages" /> after the message has been processed regardless if the outcome was successful or not.</param> public void Init(Address address, TransactionSettings transactionSettings, Func<TransportMessage, bool> tryProcessMessage, Action<TransportMessage, Exception> endProcessMessage) { this.tryProcessMessage = tryProcessMessage; this.endProcessMessage = endProcessMessage; this.workQueue = this.NamePolicy.GetQueueName(address); this.clientInfo = string.Format("OracleAQDequeueStrategy for {0}", this.workQueue); this.transactionOptions = new TransactionOptions { IsolationLevel = transactionSettings.IsolationLevel, Timeout = transactionSettings.TransactionTimeout, }; this.dequeueOptions = new OracleAQDequeueOptions { DequeueMode = OracleAQDequeueMode.Remove, ProviderSpecificType = true, Wait = 0, }; if (this.PurgeOnStartup) { this.Purger.Purge(this.workQueue); } }
public void CommendCustomerEmailVerified(int CustomerSysNo,string CommendEmail) { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.DefaultTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { CustomerCommendInfo oInfo = LoadCustomerCommend(CommendEmail); if(oInfo == null) throw new BizException(""); decimal increment = 5; //�Ƽ��ĺ���ͨ��Email��֤����5���˷� int rowsAffected = new FreeShipFeeDac().SetFreeShipFee(CustomerSysNo, increment); if (rowsAffected != 1) throw new BizException("�ͻ��˷�������ʧ�ܣ�������Ϊ�˷����㡣"); UpdateCustomerCommendStatus(CommendEmail, (int) AppEnum.CommendStatus.Registered); //�����Ƽ�״̬ if (increment != 0) { int freeShipFeeLogType = (int)AppEnum.FreeShipFeeLogType.CustomerRegister; string freeShipFeeLogMemo = "�Ƽ��ͻ�ע�����˷� - " + CommendEmail; CustomerFreeShipFeeLogInfo oLog = new CustomerFreeShipFeeLogInfo(CustomerSysNo, freeShipFeeLogType, increment, freeShipFeeLogMemo); oLog.LogCheck = oLog.CalcLogCheck(); if (1 != new FreeShipFeeDac().Insert(oLog)) throw new BizException("�����˷����ʧ��"); } scope.Complete(); } }
public async Task Should_Create_Inhability_And_Get_ToValidate_Finally_do_Delete() { var txOptions = new System.Transactions.TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using var scope = new TransactionScope(TransactionScopeOption.Required, txOptions, TransactionScopeAsyncFlowOption.Enabled); //Act Guid identityWorkId = Guid.NewGuid(); //Guid.Parse("7535C4E6-4712-4DD6-955D-FCA86E054D49"); Guid instanceId = Guid.NewGuid(); //Guid.Parse("33D7CA50-39E9-4B14-B482-5FCBEC07E8DB"); var inhabilities = await new InhabilityManagerUT().CreateDefaultAsync <Inhability>(identityWorkId, instanceId); var middlewareManager = new MiddlewareManager <Inhability>(new BaseRecordManager <Inhability>(), new InhabilityValidator()); //Asserts //Get var result = await middlewareManager .GetByIdsAsync(inhabilities.Select(p => p.ID).ToList(), identityWorkId); Assert.True(result.Any()); //Delete await middlewareManager.DeleteAsync(inhabilities.Select(p => p.ID).ToList(), identityWorkId); //Get it again to verify if the registry it was deleted var result2 = await middlewareManager .GetByIdsAsync(inhabilities.Select(p => p.ID).ToList(), identityWorkId); Assert.False(result2.Any()); }
public DistributedTransactionCoordinator(IsolationLevel isolationLevel) { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = isolationLevel; this.transactionScope = new TransactionScope(TransactionScopeOption.Required, options); }
/// Execute action public override object Execute() { TransactionOptions options = new TransactionOptions { IsolationLevel = IsolationLevel, Timeout = (Utils.ToTimeSpan(Context.TransformStr(Timeout, Transform)) ?? TimeSpan.FromSeconds(60)) }; VerboseMessage(" -- Starting transaction {0} (Isolation: {1}) --",Option,IsolationLevel); object ret; using (TransactionScope scope=new TransactionScope(Option,options)) { try { ret = base.Execute(); scope.Complete(); VerboseMessage(" -- Transaction commit --"); } catch { VerboseMessage(" -- Transaction rollback --"); throw; } } return ret; }
public void TransactionCommit() { ITransactionScopeAdapter txAdapter = (ITransactionScopeAdapter) mocks.CreateMock(typeof(ITransactionScopeAdapter)); using (mocks.Ordered()) { Expect.Call(txAdapter.IsExistingTransaction).Return(false); TransactionOptions txOptions = new TransactionOptions(); txOptions.IsolationLevel = IsolationLevel.ReadCommitted; txAdapter.CreateTransactionScope(TransactionScopeOption.Required, txOptions, EnterpriseServicesInteropOption.None); Expect.Call(txAdapter.RollbackOnly).Return(false); txAdapter.Complete(); txAdapter.Dispose(); } mocks.ReplayAll(); TxScopeTransactionManager tm = new TxScopeTransactionManager(txAdapter); tm.TransactionSynchronization = TransactionSynchronizationState.Always; TransactionTemplate tt = new TransactionTemplate(tm); tt.Execute(status => { Assert.IsTrue(TransactionSynchronizationManager.SynchronizationActive); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); return null; }); Assert.IsFalse(TransactionSynchronizationManager.SynchronizationActive); Assert.IsFalse(TransactionSynchronizationManager.CurrentTransactionReadOnly); mocks.VerifyAll(); }
public void InsertUsingSystemTransactions() { var options = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }; SqliteSession.Trace = true; using (var db = new SqliteSession("Data Source=TempDb" + DateTime.Now.Ticks + ".db;DefaultTimeout=100", false)) { db.Connection.Open(); db.CreateTable<TestObj>(); db.Connection.Close(); using (var trans = new TransactionScope(TransactionScopeOption.Required, options)) { db.Connection.Open(); db.Insert(new TestObj { Text = "My Text" }); } Assert.AreEqual(0, db.Table<TestObj>().Count()); db.Connection.Close(); using (var trans = new TransactionScope(TransactionScopeOption.Required, options)) { db.Connection.Open(); db.Insert(new TestObj { Text = "My Text" }); trans.Complete(); } Assert.AreEqual(1, db.Table<TestObj>().Count()); } }
/// <summary> /// 获取事务隔离级别 /// </summary> /// <returns></returns> 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 bool RemoveFileVersionsForFile(int fileId) { try { var option = new TransactionOptions(); option.IsolationLevel = IsolationLevel.ReadCommitted; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, option)) { var fileVersions = from fv in dbContext.FileVersions where fv.FileId == fileId select fv; foreach (FileVersion fileVersion in fileVersions) { dbContext.FileVersions.DeleteOnSubmit(fileVersion); } dbContext.SubmitChanges(); scope.Complete(); } return true; } catch (Exception e) { Console.WriteLine("Fileversion for file could not be removed. File id: " + fileId + "Error: \n" + e); return false; } }
public bool AddProject(string title, string description, string projectFolder, Library.User projectAdministratorUser) { User adminUser = dbUser.FindUserById(projectAdministratorUser.Id); if (adminUser == null) { return false; } Project project = new Project(title, description, projectFolder, adminUser); try { var option = new TransactionOptions(); option.IsolationLevel = IsolationLevel.ReadCommitted; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, option)) { dbContext.Projects.InsertOnSubmit(project); dbContext.ProjectUsers.InsertOnSubmit(new ProjectUsers { Project = project, User = project.ProjectAdministrators.FirstOrDefault(), UserType = UserType.Administrator }); dbContext.SubmitChanges(); if (true) //TODO check if the data added to db were sucessfull / valid. scope.Complete(); } return true; } catch (Exception e) { throw new Exception("Project not added to db " + e); } }
//TransactionScopeAsyncFlowOption transactionScopeAsyncFlowOption = TransactionScopeAsyncFlowOption.Suppress) // .NET 4.5.1 feature public static TransactionScope CreateRepeatableRead( TransactionScopeOption transactionScopeOption = TransactionScopeOption.Required, TimeSpan? timeout = null) { var transactionOptions = new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead, }; // Upgrade isolation level if necessary if (transactionScopeOption == TransactionScopeOption.Required) { var currentTransaction = Transaction.Current; if (currentTransaction != null && currentTransaction.IsolationLevel == IsolationLevel.Serializable) { transactionOptions.IsolationLevel = currentTransaction.IsolationLevel; } } if (timeout.HasValue) { transactionOptions.Timeout = timeout.Value; } return new TransactionScope(transactionScopeOption, transactionOptions/*, transactionScopeAsyncFlowOption*/); }
public void CancelAbandon(int masterSysNo) { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.DefaultTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { AdjustInfo masterInfo = Load(masterSysNo); //�����Ƿ���״̬ if ( masterInfo.Status != (int)AppEnum.AdjustStatus.Abandon ) throw new BizException("status is not abandon now , cancel abandon failed"); //���� ���š�״̬ Hashtable ht = new Hashtable(4); ht.Add("SysNo", masterSysNo); ht.Add("Status", (int)AppEnum.AdjustStatus.Origin); if ( 1!=new AdjustDac().UpdateMaster(ht)) throw new BizException("expected one-row update failed, cancel abandon failed "); //���Ӷ�available������ռ�� foreach(AdjustItemInfo item in masterInfo.itemHash.Values) { if ( item.AdjustQty < 0 ) { InventoryManager.GetInstance().SetAvailableQty(masterInfo.StockSysNo, item.ProductSysNo, -1*item.AdjustQty); } } scope.Complete(); } }
public void Commit(TransactionScopeOption scopeOption, TransactionOptions transactionOptions) { using (TransactionScope scope = new TransactionScope(scopeOption, transactionOptions)) { foreach (UnitOfWork.Operation operation2 in from o in this.operations orderby o.ProcessDate select o) { switch (operation2.Type) { case UnitOfWork.OperationType.Insert: operation2.Repository.PersistNewItem(operation2.Entity); break; case UnitOfWork.OperationType.Update: operation2.Repository.PersistUpdatedItem(operation2.Entity); break; case UnitOfWork.OperationType.Delete: operation2.Repository.PersistDeletedItem(operation2.Entity); break; } } scope.Complete(); } foreach (EntityBase entityBase in (from operation in this.operations select operation.Entity).OfType<EntityBase>()) { entityBase.ClearChangedProperties(); } this.Reset(); }
public ATMOperationResult GetCardCash(string cardNumber, string cardPIN, out decimal cash) { cash = 0.0M; var options = new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead, Timeout = new TimeSpan(0, 0, 0, 10) }; using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew, options)) { var matches = this.atmContext.CardAccounts.Where(a => a.CardNumber == cardNumber).ToList(); if (matches.Count == 0) { return ATMOperationResult.CardNumberInvalid; } var account = matches[0]; if (account.CardPIN != cardPIN) { return ATMOperationResult.CardPINInvalid; } cash = account.CardCash; scope.Complete(); return ATMOperationResult.Success; } }
public static TransactionScope CreateTransactionScope() { var transactionOptions = new TransactionOptions(); transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted; transactionOptions.Timeout = TimeSpan.MaxValue; return new TransactionScope(TransactionScopeOption.Required, transactionOptions); }
public async Task Should_Create_PermanentMovement_And_Get_ToValidate_Finally_do_Delete() { var txOptions = new System.Transactions.TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using var scope = new TransactionScope(TransactionScopeOption.Required, txOptions, TransactionScopeAsyncFlowOption.Enabled); //Act Guid identityWorkId = Guid.NewGuid(); Guid instanceId = Guid.NewGuid(); var permanentMovements = await new PermanentMovementManagerUT().CreateDefaultAsync <PermanentMovement>(identityWorkId, instanceId); var middlewareManager = new MiddlewareManager <PermanentMovement>(new BaseRecordManager <PermanentMovement>(), new PermanentMovementValidator()); //Asserts //Get var result = await middlewareManager .GetByIdsAsync(permanentMovements.Select(p => p.ID).ToList(), identityWorkId); Assert.True(result.Any()); //Delete await middlewareManager.DeleteAsync(permanentMovements.Select(p => p.ID).ToList(), identityWorkId); Assert.True(result.FirstOrDefault().ID == permanentMovements.FirstOrDefault().ID); //Get it again to verify if the registry it was deleted var result2 = await middlewareManager .GetByIdsAsync(permanentMovements.Select(p => p.ID).ToList(), identityWorkId); Assert.False(result2.Any()); }
public static TransactionScope CreateTransactionScope() { var transactionOptions = new TransactionOptions(); transactionOptions.IsolationLevel = IsolationLevel.ReadCommitted; transactionOptions.Timeout = TransactionManager.MaximumTimeout; return new TransactionScope(TransactionScopeOption.Required, transactionOptions); }
public TransactionScope (TransactionScopeOption scopeOption, TransactionOptions options, DTCOption opt) { Initialize (scopeOption, null, options, opt, TransactionManager.DefaultTimeout); }
public static List<SalesHistoryData> GetSalesHistory() { List<SalesHistoryData> result = new List<SalesHistoryData>(); try { // The encrypted list will timeout for slightly large lists (in the hundreds), so the list is // being grabbed in smaller chunks. Transaction logic is used to lock the list while the list is being // grabbed. TransactionOptions transactionOptions = new TransactionOptions(); transactionOptions.IsolationLevel = IsolationLevel.RepeatableRead; transactionOptions.Timeout = new TimeSpan(0, 2, 0); using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew, transactionOptions)) { Console.WriteLine("Test 1: List all Sales Orders"); int take = 5; int count = UserSession.Current.Client.GetSalesOrderListCount(); for (int skip = 0; skip < count; skip = skip + take) { List<SalesHistoryData> salesOrders = UserSession.Current.Client.GetSalesHistory(take, skip).ToList(); result = result.Union(salesOrders).ToList(); } result = result.OrderByDescending(so => so.SalesOrderNumber).ThenBy(so => so.SortOrder).ToList(); //No scope.Complete here as no write tasks are being scoped. scope.Dispose(); } } catch (Exception) { throw; } return result; }
public void Import() { if ( !AppConfig.IsImportable) throw new BizException("Is Importable is false"); /* do not use the following code after Data Pour in */ string sql = " select top 1 * from currency "; DataSet ds = SqlHelper.ExecuteDataSet(sql); if ( Util.HasMoreRow(ds) ) throw new BizException("the table currency is not empty"); TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.DefaultTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { try { string sql1 = @"select a.*, isnull(b.exchangerate,0) as exchangerate from ipp2003..currency a, ipp2003..exchange_rate b where a.sysno *=b.currencysysno"; DataSet ds1 = SqlHelper.ExecuteDataSet(sql1); foreach(DataRow dr1 in ds1.Tables[0].Rows ) { CurrencyInfo item = new CurrencyInfo(); item.CurrencyID = Util.TrimNull(dr1["CurrencyID"]); item.CurrencyName = Util.TrimNull(dr1["CurrencyName"]); item.CurrencySymbol = Util.TrimNull(dr1["CurrencySymbol"]); if ( dr1["IfBasic"] == System.DBNull.Value ) item.IsLocal = (int)AppEnum.YNStatus.No; else if ( Convert.ToBoolean(dr1["IfBasic"])==true) item.IsLocal = (int)AppEnum.YNStatus.Yes; else item.IsLocal = (int)AppEnum.YNStatus.No; item.ExchangeRate = Util.TrimDecimalNull(dr1["ExchangeRate"]); item.ListOrder = Util.TrimNull(dr1["CurrencyID"]); item.Status = Util.TrimIntNull(dr1["Status"]); this.Insert(item); //insert into convert table ImportInfo oConvert = new ImportInfo(); oConvert.OldSysNo = Util.TrimIntNull(dr1["SysNo"]); oConvert.NewSysNo = item.SysNo; new ImportDac().Insert(oConvert, "Currency"); } } catch(Exception ex) { currencyHash.Clear(); throw ex; } scope.Complete(); } }
public void Import() { if ( !AppConfig.IsImportable) throw new BizException("Is Importable is false"); /* do not use the following code after Data Pour in */ string sql = " select top 1 * from bulletin "; DataSet ds = SqlHelper.ExecuteDataSet(sql); if ( Util.HasMoreRow(ds) ) throw new BizException("the table bulletin is not empty"); TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.DefaultTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { string sql1 = @"select 1 as sysno, message, status from ipp2003..messagebar"; DataSet ds1 = SqlHelper.ExecuteDataSet(sql1); foreach(DataRow dr1 in ds1.Tables[0].Rows ) { BulletinInfo item = new BulletinInfo(); map(item, dr1); new BulletinDac().Insert(item); } scope.Complete(); } }
/// <summary> /// ����rma�� /// </summary> /// <param name="rmaInfo"></param> public void AddRMA(RMAInfo rmaInfo) { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; options.Timeout = TransactionManager.DefaultTimeout; using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { if(!this.IfExistOpenedRMA(rmaInfo.SOSysNo)) { Hashtable leftHash = this.GetLeftRMAQty(rmaInfo.SOSysNo); foreach(RMAItemInfo item in rmaInfo.ItemHash.Values) { if(item.RMAQty>(int)leftHash[item.ProductSysNo]) throw new BizException("����д�ı�����Ʒ�����������۵���ʵ�ʹ�����������ȷ���豣����Ʒ��Ϊ�˵�����"); } rmaInfo.SysNo = SequenceDac.GetInstance().Create("RMA_Sequence"); rmaInfo.RMAID = this.BuildRMAID(rmaInfo.SysNo); rmaInfo.SubmitInfo = this.GetRMASnapShot(rmaInfo); rmaInfo.Status = (int)AppEnum.RMAStatus.Origin; this.InsertMaster(rmaInfo); foreach(RMAItemInfo rmaItem in rmaInfo.ItemHash.Values) { rmaItem.RMASysNo = rmaInfo.SysNo; this.InsertItem(rmaItem); } } else throw new BizException("�����۵��Ѿ�����һ�ű����ڴ����У�������������ύ�µı������룬����ϵORS�̳ǿͷ�"); scope.Complete(); } }
/// <summary> /// Implementors should start the /// transaction on the underlying resource /// </summary> public void Start() { TransactionScopeOption scopeOption = mode == TransactionMode.Requires ? TransactionScopeOption.Required : TransactionScopeOption.RequiresNew; TransactionOptions options = new TransactionOptions(); switch(isolationMode) { case IsolationMode.ReadCommitted: options.IsolationLevel = IsolationLevel.ReadCommitted; break; case IsolationMode.Chaos: options.IsolationLevel = IsolationLevel.Chaos; break; case IsolationMode.ReadUncommitted: options.IsolationLevel = IsolationLevel.ReadUncommitted; break; case IsolationMode.Serializable: options.IsolationLevel = IsolationLevel.Serializable; break; case IsolationMode.Unspecified: options.IsolationLevel = IsolationLevel.Unspecified; break; } scope = new TransactionScope(scopeOption, options); }
internal static TransactionScope SetTransScope() { TransactionScope tranScope = null; System.Transactions.TransactionOptions tranOpt = default(System.Transactions.TransactionOptions); tranOpt.Timeout = new System.TimeSpan(0, 30, 0); tranScope = new TransactionScope(TransactionScopeOption.Required, tranOpt); return(tranScope); }
protected void ExecuteInReadUnCommitedIsolation(Action operationsDelegate) { TransactionOptions opts = new System.Transactions.TransactionOptions(); opts.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using (NgTsTransactionScope tranScope = new NgTsTransactionScope(TransactionScopeOption.RequiresNew, opts)) { operationsDelegate(); tranScope.Complete(); } }
public async Task <List <Model.OrderAppointment> > ToListAsync(OrderAppointmentQuery query) { List <Entities.OrderAppointment> l = new List <OrderAppointment>(); var transactionOptions = new System.Transactions.TransactionOptions(); transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using (var t = new TransactionScope(TransactionScopeOption.Required, transactionOptions, TransactionScopeAsyncFlowOption.Enabled)) { l = await OrderAppointment_BuildQuery(query) .AsNoTracking() .ToListAsync(); t.Complete(); t.Dispose(); } var result = l.Select(x => new Model.OrderAppointment { BillOfLading = x.BillOfLading, BoxesCount = x.BoxesCount, BoxSize = x.BoxSize, ConfirmationNumber = x.ConfirmationNumber, CustomerId = x.CustomerId, DivisionId = x.DivisionId, EndDate = x.EndDate, Notes = x.Notes, PickTicketId = x.PickTicketId, Pieces = x.Pieces, PtBulk = x.PtBulk, PurchaseOrderId = x.PurchaseOrderId, ScacCode = x.ScacCode, ShipFor = x.ShipFor, ShipTo = x.ShipTo, Size = x.Size, StartDate = x.StartDate, Status = x.Status, Weigth = x.Weigth, CustomerName = x.Customer != null ? x.Customer.CompanyName : string.Empty, DivisionName = x.Division != null ? x.Division.Description : string.Empty, DeliveryTypeId = string.IsNullOrEmpty(x.Delivery) ? default(short?) : x.Delivery == "P" ? (short)1 : (short)2, Shipping = GetShippingDescription(x.Shipping), PathPOD = x.PathPOD, ExternalBol = x.ExternalBol, ShippingDateChanged = x.ShippingDateChanged, MasterBillOfLading = x.MasterBillOfLading }); return(result.ToList()); }
//Display registered courses for this student private void studentsLB_SelectedIndexChanged(object sender, EventArgs e) { this.registrationLB.Items.Clear(); Student student = getSelectedStudent(); if (student == null) { return; } using (var db = new CoursemoDataContext()) { var TxOptions = new System.Transactions.TransactionOptions(); TxOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var Tx = new System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Required, TxOptions)) { try { if (delay_flag) { Delay(); } var registeredCourses = (from r in db.Registrations join c in db.Courses on r.CRN equals c.CRN where r.Netid == student.netid orderby c.CRN select c).ToList(); if (registeredCourses.Count > 0) { foreach (var r in registeredCourses) { this.registrationLB.Items.Add(r.CRN + " " + r.Department + " " + r.CourseNum.ToString()); } } else { this.registrationLB.Items.Add("No registered courses..."); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Tx.Complete(); } } } }
internal string Insertdata(string nama, string phone, string email, string company, string country, string zip, string state, string city) { string response = ""; #region Insert_MST_Spreed Helper Help = new Helper(); ORMDataContext db = new ORMDataContext(Help.conStrODBC); db.Connection.Open(); person = new Contact_person() { Nama = nama, Phone = phone, Email = email, Company = company, Country = country, Zip_code = zip, State_ = state, City = city }; var txOptions = new System.Transactions.TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; using (var tran = new TransactionScope(TransactionScopeOption.Required, txOptions)) { try { db.Contact_persons.InsertOnSubmit(person); db.SubmitChanges(); tran.Complete(); response = "Sukses"; } catch (Exception ex) { Console.WriteLine("==> Error Data Insert MST_Spreed " + ex.Message); string data = ex.Message; tran.Dispose(); response = "Error : " + data; } } db.Connection.Close(); return(response); #endregion }
/// <summary> /// Traduce los valors que definen las opciones del ámbito de la transacción a un valor propio de la tecnología con que se implementa el soporte transaccional. /// </summary> /// <remarks></remarks> /// <returns>Opción del ambiente transaccional.</returns> /// <date>2008-04-07T00:00:00</date> /// <author>moviedo</author> private SysTrans.TransactionOptions GetTransactionOptions() { SysTrans.TransactionOptions wResult = new SysTrans.TransactionOptions(); switch (_IsolationLevel) { case IsolationLevel.Chaos: { wResult.IsolationLevel = SysTrans.IsolationLevel.Chaos; break; } case IsolationLevel.ReadCommitted: { wResult.IsolationLevel = SysTrans.IsolationLevel.ReadCommitted; break; } case IsolationLevel.ReadUncommitted: { wResult.IsolationLevel = SysTrans.IsolationLevel.ReadUncommitted; break; } case IsolationLevel.RepeatableRead: { wResult.IsolationLevel = SysTrans.IsolationLevel.RepeatableRead; break; } case IsolationLevel.Serializable: { wResult.IsolationLevel = SysTrans.IsolationLevel.Serializable; break; } case IsolationLevel.Snapshot: { wResult.IsolationLevel = SysTrans.IsolationLevel.Snapshot; break; } default: { throw new Exception("El comportamiento no está soportado por la actual implementación"); } } wResult.Timeout = _Timeout; return(wResult); }
public async Task Should_Create_Overdraft_And_Get_ToValidate_Finally_do_Delete() { var txOptions = new System.Transactions.TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using var scope = new TransactionScope(TransactionScopeOption.Required, txOptions, TransactionScopeAsyncFlowOption.Enabled); //Act Guid identityWorkId = Guid.NewGuid(); Guid instanceId = Guid.NewGuid(); var middlewareManager = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(), new OverdraftValidator()); var overdr = await middlewareManager.FindByExpressionAsync(p => p.ID == Guid.Parse("24062420-7C73-4453-B837-A9B25AC26595"), identityWorkId, new string[] { "OverdraftDetails" }); var detail = overdr.FirstOrDefault().OverdraftDetails .Where(p => p.ID == Guid.Parse("c1314de9-13cf-4531-8641-23b04a4ce187")); var middlewareManagerDetail = new MiddlewareManager <OverdraftDetail>(new BaseRecordManager <OverdraftDetail>(), new OverdraftDetailValidator()); var detail2 = await middlewareManagerDetail.FindByExpressionAsync(p => p.ID == Guid.Parse("c1314de9-13cf-4531-8641-23b04a4ce187"), identityWorkId); var overdrafts = await new OverdraftManagerUT().CreateDefaultOverdraftAsync(identityWorkId, instanceId); //Asserts //Get var result = await middlewareManager .GetByIdsAsync(overdrafts.Select(p => p.ID).ToList(), identityWorkId); Assert.True(result.Any()); //Delete var middlewareOverdraftDetailManager = new MiddlewareManager <OverdraftDetail>(new BaseRecordManager <OverdraftDetail>(), new OverdraftDetailValidator()); await middlewareOverdraftDetailManager.DeleteAsync(overdrafts.SelectMany(p => p.OverdraftDetails).Select(p => p.ID).ToList(), identityWorkId); await middlewareManager.DeleteAsync(overdrafts.Select(p => p.ID).ToList(), identityWorkId); Assert.True(result.FirstOrDefault().ID == overdrafts.FirstOrDefault().ID); //Get it again to verify if the registry it was deleted var result2 = await middlewareManager .GetByIdsAsync(overdrafts.Select(p => p.ID).ToList(), identityWorkId); Assert.False(result2.Any()); }
public async Task Should_Change_Status_To_UnregisteredUsingClient() { var txOptions = new System.Transactions.TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using var scope = new TransactionScope(TransactionScopeOption.Required, txOptions, TransactionScopeAsyncFlowOption.Enabled); //Act Guid identityWorkId = Guid.NewGuid(); //Guid.Parse("7535C4E6-4712-4DD6-955D-FCA86E054D49"); Guid instanceId = Guid.NewGuid(); //Guid.Parse("33D7CA50-39E9-4B14-B482-5FCBEC07E8DB"); var employees = await new EmployeeManagerUT().CreateDefaultAsync <Employee>(identityWorkId, instanceId, randomValues: true); var middlewareManager = new MiddlewareManager <Employee>(new BaseRecordManager <Employee>(), new EmployeeValidator()); //Asserts //Get var result = await middlewareManager .GetByIdsAsync(employees.Select(p => p.ID).ToList(), identityWorkId); Assert.True(result.Any()); var employeeFromDB = result.FirstOrDefault(); Assert.Equal(CotorriaStatus.Active, employeeFromDB.LocalStatus); Assert.Equal(DateTime.Now.Date, employeeFromDB.LastStatusChange.Date); //Set inactive DateTime?unregisteredDate = DateTime.Now.AddDays(1); var employeeId = employeeFromDB.ID; var statusClient = new StatusClient <Employee>("", ClientConfiguration.ClientAdapter.Local); await statusClient.SetUnregistered(new List <Guid>() { employeeId }, identityWorkId, unregisteredDate); //Asserts //GetAggain result = await middlewareManager .GetByIdsAsync(employees.Select(p => p.ID).ToList(), identityWorkId); Assert.True(result.Any()); employeeFromDB = result.FirstOrDefault(); //Asserts Assert.Equal(CotorriaStatus.Unregistered, employeeFromDB.LocalStatus); Assert.Equal(DateTime.Now.Date, employeeFromDB.LastStatusChange.Date); Assert.Equal(unregisteredDate.GetValueOrDefault().Date, employeeFromDB.UnregisteredDate.GetValueOrDefault().Date); }
/// <summary> /// Performs operations common to any application flow: validating the input, /// wrapping the flow in a transaction and finally executing each flow step. /// </summary> /// <param name="input">The flow input.</param> /// <param name="flowInitiator">The user who initiated executing this flow.</param> /// <returns>The flow output.</returns> protected override async Task <TOutput> InternalExecuteAsync(TInput input, IPrincipal flowInitiator) { var transactionOptions = new System.Transactions.TransactionOptions { IsolationLevel = applicationFlowOptions.TransactionOptions.IsolationLevel, Timeout = applicationFlowOptions.TransactionOptions.Timeout }; using var transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions, TransactionScopeAsyncFlowOption.Enabled); TOutput output = await base.InternalExecuteAsync(input, flowInitiator); transactionScope.Complete(); return(output); }
public void BeforeTest(TestDetails testDetails) { lock (_SyncLock) { if (_TransactionScope != null) { throw new InvalidOperationException(); } var transactionScopeOptions = new System.Transactions.TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TimeSpan.FromSeconds(30) }; this._TransactionScope = new TransactionScope(TransactionScopeOption.Required, transactionScopeOptions); } }
//Get students from DB //Display students in students listbox private void showStudentsButton_Click(object sender, EventArgs e) { this.studentsLB.Items.Clear(); using (var db = new CoursemoDataContext()) { var TxOptions = new System.Transactions.TransactionOptions(); TxOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var Tx = new System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Required, TxOptions)) { try { if (students == null) { if (delay_flag) { Delay(); } students = new List <Student>(); var query = (from s in db.Students orderby s.Netid select s).ToList(); foreach (var s in query) { students.Add(new Student(s.LastName, s.FirstName, s.Netid)); } } foreach (var s in students) { this.studentsLB.Items.Add(s); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Tx.Complete(); } } } }
private void showCoursesButton_Click(object sender, EventArgs e) { this.coursesLB.Items.Clear(); using (var db = new CoursemoDataContext()) { var TxOptions = new System.Transactions.TransactionOptions(); TxOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var Tx = new System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Required, TxOptions)) { try { if (courses == null) { courses = new List <Course>(); if (delay_flag) { Delay(); } var query = (from c in db.Courses orderby c.Department, c.CourseNum, c.CRN select c).ToList(); foreach (var c in query) { courses.Add(new Course(c.Department, c.CourseNum, c.Semester, c.Year, c.CRN, c.Time, c.Day, c.Time, c.Capacity)); } } foreach (var c in courses) { this.coursesLB.Items.Add(c); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Tx.Complete(); } } } }
public ActionResult Visualize(int?month, int?year, int?page) { int pageSize = 10; int pageNumber = page.HasValue ? Convert.ToInt32(page) : 1; var txOptions = new System.Transactions.TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using (var transaction = new TransactionScope(TransactionScopeOption.Required, txOptions)) { using (var context = new WeatherDBEntities()) { WeatherInfoViewModel model = new WeatherInfoViewModel(); model.weatherInfo = context.Weathers.Where(m => false).ToPagedList(pageNumber, pageSize); model.month = month; model.year = year; if (year == null && month == null) { model.weatherInfo = context.Weathers.ToList().ToPagedList <Weather>(pageNumber, pageSize); } else if (year == null && month != null) { model.errorMessage = "Specify year"; } else if (year != null && month == null) { model.weatherInfo = context.Weathers.Where(m => m.Date.Year == year) .OrderBy(m => m.Date.Year) .ToPagedList(pageNumber, pageSize); } else { model.weatherInfo = context.Weathers.Where(m => (m.Date.Year == year && m.Date.Month == month)) .OrderBy(m => m.Date.Year) .ToPagedList(pageNumber, pageSize); } return(View(model)); } } }
//Delete all rows in Registrations, Transactions, and Waitlist tables private void resetButton_Click(object sender, EventArgs e) { using (var db = new CoursemoDataContext()) { var TxOptions = new System.Transactions.TransactionOptions(); TxOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var Tx = new System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Required, TxOptions)) { try { if (delay_flag) { Delay(); } db.Registrations.DeleteAllOnSubmit(from r in db.Registrations select r); if (delay_flag) { Delay(); } db.Waitlists.DeleteAllOnSubmit(from w in db.Waitlists select w); if (delay_flag) { Delay(); } db.Transactions.DeleteAllOnSubmit(from t in db.Transactions select t); db.SubmitChanges(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Tx.Complete(); } } MessageBox.Show("Database reset."); } }
internal string Updatedata(string nama, string phone, string email, string company, string country, string zip, string state, string city) { string respon = ""; Helper Help = new Helper(); ORMDataContext db = new ORMDataContext(Help.conStrODBC); db.Connection.Open(); var txOptions = new System.Transactions.TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; using (var tran = new TransactionScope(TransactionScopeOption.Required, txOptions)) { try { person = (from q in db.Contact_persons where q.Nama == nama select q).Take(1).FirstOrDefault(); person.Nama = nama; person.Phone = phone; person.Email = email; person.Company = company; person.Country = country; person.Zip_code = zip; person.State_ = state; person.City = city; db.SubmitChanges(); tran.Complete(); respon = "Sukses"; } catch (Exception ex) { string data = ex.Message; tran.Dispose(); respon = "Error : " + data; } } db.Connection.Close(); return(respon); }
public TOTransaction CancelarReserva(short emp_codi, int id, int motivo) { string txterror = ""; SAeReser.SAeReserDMR com = new SAeReser.SAeReserDMR(); object[] varEntr = { usuario, Encrypta.EncriptarClave(password), alias, "SAeReser", "", "", "", "", "", "N" }; object varSali; try { var txOptions = new System.Transactions.TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; txOptions.Timeout = TimeSpan.MaxValue; if (com.ProgramLogin(varEntr, out varSali, out txterror) != 0) { throw new Exception("Error al ingresar a SEVEN-ERP, " + txterror); } object[] pdataIn = { emp_codi, id, motivo }; object pDatOut; if (com.Cancelar(pdataIn, out pDatOut, out txterror) != 0) { throw new Exception(txterror); } var pDataOut2 = (object[])pDatOut; return(new TOTransaction() { TxtError = txterror, Retorno = 0 }); } catch (Exception ex) { return(new TOTransaction() { Retorno = 1, TxtError = ex.Message }); } }
public async Task Should_Update_Employee_And_Get_ToValidate_Finally_do_Delete() { var txOptions = new System.Transactions.TransactionOptions(); txOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using var scope = new TransactionScope(TransactionScopeOption.Required, txOptions, TransactionScopeAsyncFlowOption.Enabled); //Act Guid identityWorkId = Guid.NewGuid(); //Guid.Parse("7535C4E6-4712-4DD6-955D-FCA86E054D49"); Guid instanceId = Guid.NewGuid(); //Guid.Parse("33D7CA50-39E9-4B14-B482-5FCBEC07E8DB"); var employees = await new EmployeeManagerUT().CreateDefaultAsync <Employee>(identityWorkId, instanceId, randomValues: true); var middlewareManager = new MiddlewareManager <Employee>(new BaseRecordManager <Employee>(), new EmployeeValidator()); //Asserts //Get var result = await middlewareManager .GetByIdsAsync(employees.Select(p => p.ID).ToList(), identityWorkId); Assert.True(result.Any()); var middlewareManagerOverdraft = new MiddlewareManager <Overdraft>(new BaseRecordManager <Overdraft>(), new OverdraftValidator()); var resultOverdraft = await middlewareManagerOverdraft.FindByExpressionAsync(p => p.InstanceID == instanceId && p.EmployeeID == employees.FirstOrDefault().ID, identityWorkId); Assert.True(resultOverdraft.Any()); var employeeId = employees.FirstOrDefault().ID; var newAmount = employees.FirstOrDefault().DailySalary; employees.FirstOrDefault().DailySalary = 5478; await middlewareManager.UpdateAsync(employees, identityWorkId); var middlewareHistoricEmployeeSalaryAdjustmentManager = new MiddlewareManager <HistoricEmployeeSalaryAdjustment>(new BaseRecordManager <HistoricEmployeeSalaryAdjustment>(), new HistoricEmployeeSalaryAdjustmentValidator()); var historicEmployee = await middlewareHistoricEmployeeSalaryAdjustmentManager.FindByExpressionAsync(p => p.EmployeeID == employeeId, identityWorkId);; Assert.True(historicEmployee.FirstOrDefault().DailySalary == newAmount); }
protected bool DoSync() { log.Info("Start Sync Task:" + TaskName); if (!NeedSync()) { return(true); } if (!UsingTransaction) { Sync(null); return(true); } var transactionOptions = new System.Transactions.TransactionOptions(); transactionOptions.Timeout = TimeSpan.FromMinutes(10); //set it to read uncommited transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted; using (var transactionScope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.RequiresNew, transactionOptions)) { Sync(transactionScope); } return(true); }
public async Task <List <Model.ScacCode> > GetScacCodes() { List <Model.ScacCode> scacCodes = new List <Model.ScacCode>(); var transactionOptions = new System.Transactions.TransactionOptions(); //set it to read uncommited transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; using (var t = new TransactionScope(TransactionScopeOption.Required, transactionOptions, TransactionScopeAsyncFlowOption.Enabled)) { var result = await Context.ScacCodes.ToListAsync(); scacCodes = result.Select(x => new Model.ScacCode() { Carrier = x.ScacCodeName, ScacCodeId = x.ScacCodeId }).ToList(); t.Complete(); t.Dispose(); } return(scacCodes); }
public void SaveThumbnail2(int id, string fileName, Func <System.IO.Stream, Task> copy) { var product = this.DB.Products.Where(a => a.ProductID == id).FirstOrDefault(); if (product == null) { throw new Exception("Product is not found"); } TransactionOptions topts = new System.Transactions.TransactionOptions(); topts.Timeout = TimeSpan.FromSeconds(60); topts.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (TransactionScope trxScope = new TransactionScope(TransactionScopeOption.Required, topts)) using (DbConnection conn = DBConnectionFactory.GetRIAppDemoConnection()) { string fldname = "ThumbNailPhoto"; BlobStream bstrm = new BlobStream(conn as SqlConnection, "[SalesLT].[Product]", fldname, string.Format("WHERE [ProductID]={0}", id)); bstrm.InitColumn(); bstrm.Open(); try { if (!copy(bstrm).Wait(10000)) { throw new Exception("Write stream timeout"); } } finally { bstrm.Close(); } trxScope.Complete(); } product.ThumbnailPhotoFileName = fileName; this.DB.SubmitChanges(); }
protected void btnSubmit_Click(object sender, EventArgs e) { var proxyHello = new TransactionSvc.Hello.HelloClient(); var proxyHi = new TransactionSvc.Hi.HiClient(); var proxyResult = new TransactionSvc.Result.ResultClient(); System.Transactions.TransactionOptions to = new System.Transactions.TransactionOptions(); // 设置事务的超时时间 to.Timeout = new TimeSpan(0, 0, 30); // 设置事务的隔离级别 to.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var ts = new System.Transactions.TransactionScope()) { try { proxyHello.WriteHello("webabcd"); proxyHello.Close(); proxyHi.WriteHi("webabcd"); proxyHi.Close(); ts.Complete(); lblErr.Text = "OK"; } catch (Exception ex) { lblErr.Text = ex.ToString(); } } GridView1.DataSource = proxyResult.GetResult(); GridView1.DataBind(); proxyHello.Close(); }
protected void btnSave_Click(object sender, EventArgs e) { int RoleID = 0; int.TryParse(hfR.Value, out RoleID); if (RoleID == 0) { string SC = "<script>alert('資料取得失敗');location.href = '/System/PowerM/RolePowerSetting.aspx';</script><style>body{display:none;}</style>"; Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "alert", SC, false); return; } string script = "<script>alert('儲存失敗');</script>"; if (hfV != null) { string jsonString = hfV.Value; List <RolePowerSettingPowerVM> list = new List <RolePowerSettingPowerVM>(); list = JsonConvert.DeserializeObject <List <RolePowerSettingPowerVM> >(jsonString); DataTable dt = new DataTable(); dt.Columns.Add("ID"); dt.Columns.Add("RoleID"); dt.Columns.Add("ModuleID"); dt.Columns.Add("PowerString"); foreach (var item in list.Where(item => item.PowerStringOut > 1)) { dt.Rows.Add(0, RoleID, item.mId, item.PowerStringOut); } System.Transactions.TransactionOptions option = new System.Transactions.TransactionOptions(); option.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; option.Timeout = new TimeSpan(0, 10, 0); using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(TransactionScopeOption.Required, option)) { using (SqlConnection sc = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnUser"].ToString())) { sc.Open(); using (SqlCommand cmd = new SqlCommand("dbo.usp_PowerM_xDeleteRoleModuleByRoleID", sc)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@RoleID", RoleID); cmd.ExecuteNonQuery(); using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sc)) { bulkCopy.BulkCopyTimeout = 60; bulkCopy.DestinationTableName = "dbo.R_RoleModule"; bulkCopy.WriteToServer(dt); } ts.Complete(); } } } script = "<script>alert('儲存成功');location.href='/System/PowerM/RolePowerSetting.aspx';</script><style>body{display:none;}</style>"; Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "alert", script, false); } Page.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "alert", script, false); }
private void swapButton_Click(object sender, EventArgs e) { string netidA = this.netidATextBox.Text; if (netidA == null) { MessageBox.Show("Enter student A's netid."); return; } int crnA = Convert.ToInt32(this.crnATextBox.Text); if (this.crnATextBox.Text == null) { MessageBox.Show("Enter student A's CRN."); return; } string netidB = this.netidBTextBox.Text; if (netidB == null) { MessageBox.Show("Enter student B's netid."); return; } int crnB = Convert.ToInt32(this.crnBTextBox.Text); if (this.crnBTextBox.Text == null) { MessageBox.Show("Enter student B's CRN."); return; } string msg = null; using (var db = new CoursemoDataContext()) { var TxOptions = new System.Transactions.TransactionOptions(); TxOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var Tx = new System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Required, TxOptions)) { try { //Check if student A exists if (delay_flag) { Delay(); } var aExists = from s in db.Students where s.Netid == netidA select s.Netid; if (!aExists.Any()) { msg = netidA + " does not exist."; throw new System.InvalidOperationException(msg); } //Check if student A is enrolled in crnA var aEnrolled = from r in db.Registrations where r.Netid == netidA where r.CRN == crnA select r; if (!aEnrolled.Any()) { msg = netidA + " is not enrolled in " + crnA.ToString() + "."; throw new System.InvalidOperationException(msg); } if (delay_flag) { Delay(); } //Check if student B exists var bExists = from s in db.Students where s.Netid == netidB select s.Netid; if (!bExists.Any()) { msg = netidB + " does not exist."; throw new System.InvalidOperationException(msg); } if (delay_flag) { Delay(); } //Check if student B is enrolled in crnB var bEnrolled = from r in db.Registrations where r.Netid == netidB where r.CRN == crnB select r; if (!bEnrolled.Any()) { msg = netidB + " is not enrolled in " + crnB.ToString() + "."; throw new System.InvalidOperationException(msg); } if (delay_flag) { Delay(); } //Clear out student a's waitlist entry for b's class var aWaiting = from w in db.Waitlists where w.Netid == netidA where w.CRN == crnB select w; db.Waitlists.DeleteAllOnSubmit(aWaiting); if (delay_flag) { Delay(); } //Clear out student b's waitlist entry for a's class var bWaiting = from w in db.Waitlists where w.Netid == netidB where w.CRN == crnA select w; db.Waitlists.DeleteAllOnSubmit(bWaiting); //Swap registrations if (delay_flag) { Delay(); } aEnrolled.First().CRN = crnB; if (delay_flag) { Delay(); } bEnrolled.First().CRN = crnA; //MessageBox.Show(netidA + " swapped course " + crnA.ToString() + " for " + crnB.ToString() + " with " + netidB); msg = netidA + " swapped course " + crnA.ToString() + " for " + crnB.ToString() + " with " + netidB; db.SubmitChanges(); Tx.Complete(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } MessageBox.Show(msg); }
//Display waitlist for this course private void coursesLB_SelectedIndexChanged(object sender, EventArgs e) { this.enrolledCourseLB.Items.Clear(); this.waitlistLB.Items.Clear(); Course course = getSelectedCourse(); if (course == null) { return; } using (var db = new CoursemoDataContext()) { var TxOptions = new System.Transactions.TransactionOptions(); TxOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var Tx = new System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Required, TxOptions)) { try { if (delay_flag) { Delay(); } var enrolled = (from r in db.Registrations where r.CRN == course.crn select r).ToList(); if (enrolled.Any()) { foreach (var en in enrolled) { this.enrolledCourseLB.Items.Add(en.Netid); } } else { this.enrolledCourseLB.Items.Add("No enrollments."); } if (delay_flag) { Delay(); } var waitlist = (from w in db.Waitlists where w.CRN == course.crn orderby w.RegTime select w).ToList(); if (waitlist.Any()) { foreach (var w in waitlist) { this.waitlistLB.Items.Add(w.Netid + " " + w.CRN + " " + w.RegTime.ToString()); } } else { this.waitlistLB.Items.Add("No waitlist..."); } Tx.Complete(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
//Get selected student and enrolled course //Delete entry in registrations table //Check waitlist for dropped course, enroll first in line private void dropCourseButton_Click(object sender, EventArgs e) { Student student = getSelectedStudent(); if (student == null) { MessageBox.Show("Select a student."); return; } if (this.registrationLB.SelectedItem == null) { MessageBox.Show("Select a registered course."); return; } int selectedCRN = Convert.ToInt32(this.registrationLB.SelectedItem.ToString().Split(' ')[0]); //MessageBox.Show(selectedCRN.ToString()); string msg = null; using (var db = new CoursemoDataContext()) { var TxOptions = new System.Transactions.TransactionOptions(); TxOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (var Tx = new System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Required, TxOptions)) { try { if (delay_flag) { Delay(); } db.Registrations.DeleteAllOnSubmit(from r in db.Registrations where r.CRN == selectedCRN where r.Netid == student.netid select r); //MessageBox.Show(student.netid + " dropped " + selectedCRN); msg = student.netid + " dropped " + selectedCRN; if (delay_flag) { Delay(); } var waiting = (from w in db.Waitlists where w.CRN == selectedCRN orderby w.RegTime select w).ToList(); //Is there a waitlist for this class? if (waiting.Any()) { if (delay_flag) { Delay(); } var front = students.Find( delegate(Student s) { return(s.netid == waiting[0].Netid); } ); //Enroll if (delay_flag) { Delay(); } Registration r = new Registration { Netid = front.netid, CRN = selectedCRN }; db.Registrations.InsertOnSubmit(r); //MessageBox.Show(front.netid + " enrolled in " + selectedCRN); //msg = front.netid + " enrolled in " + selectedCRN; //Remove enrolled student from waitlist if (delay_flag) { Delay(); } db.Waitlists.DeleteAllOnSubmit(from w in db.Waitlists where w.Netid == front.netid where w.CRN == selectedCRN select w); } db.SubmitChanges(); Tx.Complete(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } MessageBox.Show(msg); }