private void ExecuteProcess() { // create the session process var sessionProcess = _container.Get<ISynchronize>("Session", new IParameter[0]); var speakerProcess = _container.Get<ISynchronize>("Speaker", new IParameter[0]); using (var scope = new TransactionScope()) { // synchronize speakrs (should go first since session has a dependancy here) Logger.Current.LogInformation("Synchronizing Speakers"); var speakerChanges = speakerProcess.Synchronize(); // now do the session data Logger.Current.LogInformation("Synchronizing Sessions"); var sessionChanges = sessionProcess.Synchronize(); // collect the changes and save them Logger.Current.LogInformation("Saving Delta Information"); var allChanges = speakerChanges.Concat(sessionChanges).ToList(); if (allChanges.Count > 0) { var repository = _container.Get<IChangeRepository>(); repository.SaveRange(allChanges); } // complete the transaction Logger.Current.LogInformation("Completing the Procss"); scope.Complete(); } }
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); } }
/// <summary> /// 删除设备参数数据 /// </summary> /// <param name="strCode"></param> /// <returns></returns> public CommonResult <bool> DelDevParameterByCode(string strCode) { var result = new CommonResult <bool>(); try { var dbSession = new DBService <DeviceParameter>().DbSession; using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope()) { var model = dbSession.GetQueryable(t => t.DevpCode == strCode).FirstOrDefault(); if (result.IsSuccess) { dbSession.Delete(model); ts.Complete(); result.Data = true; } } } catch (Exception ex) { Utils.Logger.Error(ex.Message); throw ex; } return(result); }
//private static readonly String sPublishQueuePath = ".\\private$\\BankTransferQueueTransacted"; //private static void EnsureMessageQueuesExists() //{ // // Create the transacted MSMQ queue if necessary. // if (!MessageQueue.Exists(sPublishQueuePath)) // MessageQueue.Create(sPublishQueuePath, true); //} private static void CreateDummyEntities() { using (TransactionScope lScope = new TransactionScope()) using (BankEntityModelContainer lContainer = new BankEntityModelContainer()) { if (lContainer.Accounts.Count() == 0) { Customer lVideoStore = new Customer(); Account lVSAccount = new Account() { AccountNumber = 123, Balance = 0 }; lVideoStore.Accounts.Add(lVSAccount); Customer lCustomer = new Customer(); Account lCustAccount = new Account() { AccountNumber = 456, Balance = 20 }; lCustomer.Accounts.Add(lCustAccount); lContainer.Customers.AddObject(lVideoStore); lContainer.Customers.AddObject(lCustomer); lContainer.SaveChanges(); lScope.Complete(); } } }
public DistributedTransactionCoordinator(IsolationLevel isolationLevel) { TransactionOptions options = new TransactionOptions(); options.IsolationLevel = isolationLevel; this.transactionScope = new TransactionScope(TransactionScopeOption.Required, options); }
public void CopyTestWithDb() { string sourceFileName = @"c:\tmp\System.IO.Transactions.TxF\TestFiles\TestFile.source"; string destFileName = @"c:\tmp\System.IO.Transactions.TxF\TestFiles\TestFile.dest"; System.Data.SqlServerCe.SqlCeConnection cnDb = new System.Data.SqlServerCe.SqlCeConnection(@"Data Source=C:\tmp\System.IO.Transactions.TxF\System.IO.Transactions.TxF.Test\DatabaseTest.sdf"); System.Data.SqlServerCe.SqlCeCommand cmDb = new System.Data.SqlServerCe.SqlCeCommand("INSERT INTO TestTbl (Col_1) VALUES (GETDATE());", cnDb); bool overwrite = true; using (cnDb) { cnDb.Open(); using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope()) { try { File.Copy(sourceFileName, destFileName, overwrite); cmDb.ExecuteNonQuery(); ts.Complete(); } catch (Exception) { throw; } finally { } } } }
public void MovePackageToStaging(Package iPackage) { if (iPackage == null) { throw new Exception("Le package est null"); } var thePackage = GetPackageById(iPackage.PackageId, GranularityEnum.Full); using (var ts = new System.Transactions.TransactionScope()) { //UpdatePackageStatus UpdatePackageStatus(thePackage, PackageStatusEnum.Staging); //Passage en staging des tâches foreach (var mainTaskItem in thePackage.MainTasks) { MoveMainTaskToStaging(mainTaskItem.MainTaskId); } //Création de la trace de déploiement var newDeployement = new EquinoxeExtend.Shared.Object.Release.Deployement(); newDeployement.DeployementDate = DateTime.Now; newDeployement.DeployementId = -1; newDeployement.EnvironmentDestination = EnvironmentEnum.Staging; newDeployement.PackageId = thePackage.PackageId; AddDeployement(newDeployement); ts.Complete(); } }
public async Task Should_use_connection_and_not_escalate_to_DTC() { Guid?transactionId = null; await Scenario.Define <MyContext>() .WithEndpoint <AnEndpoint>(c => c.When(async bus => { using (var completedScope = new System.Transactions.TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { using (var connection = new SqlConnection(ConnectionString)) { await connection.OpenAsync().ConfigureAwait(false); var sendOptions = new SendOptions(); sendOptions.UseCustomSqlConnection(connection); await bus.Send(new CommandFromCompletedScope(), sendOptions); var publishOptions = new PublishOptions(); publishOptions.UseCustomSqlConnection(connection); await bus.Publish(new EventFromCompletedScope(), publishOptions); } transactionId = Transaction.Current.TransactionInformation.DistributedIdentifier; completedScope.Complete(); } })) .Done(c => c.SendFromCompletedScopeReceived && c.PublishFromCompletedScopeReceived) .Run(TimeSpan.FromMinutes(1)); Assert.AreEqual(Guid.Empty, transactionId); }
public void RegisterCustomer(string name, CustomerType customerType) { try { using (var transaction = new TransactionScope()) { Customer customer = new Customer(); customer.Name = name; customer.Type = customerType; customer.Agreements.Add( new Agreement { Number = agreementManagementService.GenerateAgreementNumber(), CreatedOn = DateTime.Now, Customer = customer }); repository.Save(customer); repository.Commit(); transaction.Complete(); } } catch (Exception ex) { throw new RegistrationException(string.Format("Failed to register customer with name '{0}' and type {1}.", name, customerType), ex); } }
/// <summary> /// 导入数据 /// </summary> /// <param name="list"></param> /// <returns></returns> public string ImportProCateData(List <ProductEntity> list) { string msg = ""; try { foreach (ProductEntity entity in list) { entity.IncludeAll(); } List <ProductEntity> all = this.Product.GetList(); if (all == null) { all = new List <ProductEntity>(); } List <int> ids = (from i in all select i.ID).ToList(); using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope()) { this.Product.Delete(ids); //先删除在添加 this.Product.Add(list); ts.Complete(); } CacheHelper.Remove(CacheKey.JOOSHOW_PRODUCT_CACHE); } catch (Exception ex) { msg = ex.Message; log.Info(msg); } return(msg); }
public void addClickCount(string _code) { try { var r = DB.tblAdvertisements.Single(p => p.Code == _code); using (TransactionScope ts = new TransactionScope()) { if (r != null) { r.ClickCount += 1; DB.SubmitChanges(); ts.Complete(); } } } catch (Exception e) { log.writeLog(DBHelper.strPathLogFile, e.Message + CommonConstants.NEWLINE + e.Source + CommonConstants.NEWLINE + e.StackTrace + CommonConstants.NEWLINE + e.HelpLink); } }
/// <summary> /// To Save Settlement Of Accounts /// </summary> /// <param name="settlementOfAcct"></param> /// <returns></returns> public int SaveSettlementOfAccounts(SettlementOfAccountsDTO settlementOfAcct) { settlementofaccount settlementOfAcctEntity = new settlementofaccount(); using (TransactionScope transactionScope = new TransactionScope()) { AutoMapper.Mapper.Map(settlementOfAcct, settlementOfAcctEntity); ESalesUnityContainer.Container.Resolve<IGenericRepository<settlementofaccount>>().Save(settlementOfAcctEntity); BookingService bookingService = new BookingService(); BookingDTO bookingDetail = bookingService.GetBookingDetailByBookingId(settlementOfAcct.Account_Booking_Id, true); //Set money receipt issued status flag to true and save booking details in database bookingDetail.Booking_AccountSettled = true; bookingDetail.Booking_AccountSettledDate = DateTime.Now.Date; // Added by ansharma on 26-Sep-2012 bookingService.SaveAndUpdateBookingDetail(bookingDetail); transactionScope.Complete(); } //return value return settlementOfAcctEntity.Account_Id; }
public void CanQueryDtcForUncommittedItem() { using (GetNewServer()) using (var store = new DocumentStore { Url = "http://localhost:8080" }.Initialize()) { for (int i = 0; i < 150; i++) { string id; using (var tx = new TransactionScope()) { System.Transactions.Transaction.Current.EnlistDurable(ManyDocumentsViaDTC.DummyEnlistmentNotification.Id, new ManyDocumentsViaDTC.DummyEnlistmentNotification(), EnlistmentOptions.None); using (var session = store.OpenSession()) { var entity = new User(); session.Store(entity); session.SaveChanges(); id = entity.Id; } tx.Complete(); } using (var session = store.OpenSession()) { session.Advanced.AllowNonAuthoritiveInformation = false; var user = session.Load<User>(id); Assert.NotNull(user); } } } }
public void MessageQueuedForReceive_EventIsRaised() { using (var sender = SetupSender()) using (var receiver = SetupReciever()) { receiver.MessageQueuedForReceive += RecordMessageEvent; using (var tx = new TransactionScope()) { sender.Send( new Uri("file://localhost/h"), new MessagePayload { Data = new byte[] { 1, 2, 4, 5 } }); tx.Complete(); } while (_messageEventCount == 0) Thread.Sleep(100); receiver.MessageQueuedForReceive -= RecordMessageEvent; } Assert.NotNull(_messageEventArgs); Assert.Equal("h", _messageEventArgs.Message.Queue); }
public void LeaveRulesCreate(LeaveRulesDTOs Record) { try { using (var scope = new System.Transactions.TransactionScope()) { LeaveRule test = _unitOfWork.LeaveRuleRepository.Create(LeaveRulesMapper.LeaveRuleDtoToLeaveRules(Record)); int count = Record.LeaveRuleDetailsColection.Count(); for (int i = 0; i < count; i++) { LeaverulesDetailsDtos data = new LeaverulesDetailsDtos(); data.LeaveRuleId = test.LeaveRuleId; data.LeaveTypeId = Record.LeaveRuleDetailsColection[i].LeaveTypeId; if (Record.LeaveRuleDetailsColection[i].LeaveDays == null) { data.LeaveDays = 0; } data.LeaveDays = Record.LeaveRuleDetailsColection[i].LeaveDays; LeaveRuleDetail insertdata = LeaveRuleDetailsMapper.LeaveRulesdetailDtoToLeaveRuleDetails(data); _unitOfWork.LeaveRuleDetailRepository.Create(insertdata); } scope.Complete(); } } catch (TransactionAbortedException ex) { throw new Exception(ex.Message); } catch (ApplicationException ex) { throw new Exception(ex.Message); } }
public void Insert(LogTrackInfo e) { //不使用Transaction , 以正確的記錄發生那些Track事件 using (System.Transactions.TransactionScope Ts = new System.Transactions.TransactionScope(TransactionScopeOption.Suppress)) { //設定連結字串 Database db = base.GetDatabase(); StringBuilder sbCommand = new StringBuilder(); sbCommand.Append("INSERT INTO Track_Log "); sbCommand.Append(" (ModifyFromIP, ModifyUser, ModifyMode, ModifyTable, ModifyKeyValue ,ModifyBefore , ModifyAfter) "); sbCommand.Append("VALUES "); sbCommand.Append(" (@ModifyFromIP, @ModifyUser, @ModifyMode, @ModifyTable, @ModifyKeyValue, @ModifyBefore, @ModifyAfter) "); DbCommand dbCommand = db.GetSqlStringCommand(sbCommand.ToString()); db.AddInParameter(dbCommand, "@ModifyFromIP", DbType.String, e.ModifyFromIP); db.AddInParameter(dbCommand, "@ModifyUser", DbType.String, e.ModifyUser); db.AddInParameter(dbCommand, "@ModifyMode", DbType.String, e.ModifyMode); db.AddInParameter(dbCommand, "@ModifyTable", DbType.String, e.ModifyTable); db.AddInParameter(dbCommand, "@ModifyKeyValue", DbType.String, e.ModifyKeyValue); db.AddInParameter(dbCommand, "@ModifyKeyValue", DbType.String, e.ModifyBefore); db.AddInParameter(dbCommand, "@ModifyKeyValue", DbType.String, e.ModifyAfter); try { db.ExecuteNonQuery(dbCommand); } catch { throw; } } }
public ActionResult deleteGetReturn(int id) { if (id < 0) { return(RedirectToAction("ReturnPurchaseList", new { @message = "Không tồn tại phiếu nhận hàng trả này." })); } var ctx = new SmsContext(); var infor = ctx.TRA_HANG.Find(id); if (infor == null || infor.ACTIVE != "A") { return(RedirectToAction("ReturnPurchaseList", new { @message = "Không tồn tại phiếu nhận hàng trả này." })); } using (var transaction = new System.Transactions.TransactionScope()) { try { if (infor.MA_KHACH_HANG != null) { var debitHist = ctx.KHACH_HANG_DEBIT_HIST.Where(u => u.ACTIVE == "A" && u.MA_PHIEU_TRA == id).FirstOrDefault(); var customer = ctx.KHACH_HANG.Find(infor.MA_KHACH_HANG); if (debitHist != null) { if (customer.NO_GOI_DAU == 0) { customer.NGAY_PHAT_SINH_NO = DateTime.Now; } customer.NO_GOI_DAU = customer.NO_GOI_DAU + (decimal)debitHist.PHAT_SINH; customer.UPDATE_AT = DateTime.Now; customer.UPDATE_BY = Convert.ToInt32(Session["UserId"]); debitHist.ACTIVE = "I"; debitHist.UPDATE_AT = DateTime.Now; debitHist.UPDATE_BY = Convert.ToInt32(Session["UserId"]); } } infor.ACTIVE = "I"; infor.UPDATE_AT = DateTime.Now; infor.UPDATE_BY = Convert.ToInt32(Session["UserId"]); var details = ctx.CHI_TIET_TRA_HANG.Where(u => u.ACTIVE == "A" && u.MA_TRA_HANG == id).ToList <CHI_TIET_TRA_HANG>(); foreach (var detail in details) { detail.ACTIVE = "I"; detail.UPDATE_AT = DateTime.Now; detail.UPDATE_BY = Convert.ToInt32(Session["UserId"]); } ctx.SaveChanges(); transaction.Complete(); ctx.Dispose(); return(RedirectToAction("ReturnPurchaseList", new { @inforMessage = "Xóa phiếu trả hàng thành công." })); } catch (Exception ex) { Transaction.Current.Rollback(); Console.Write(ex.ToString()); ctx.Dispose(); return(RedirectToAction("ReturnPurchaseList", new { @message = "Xóa phiếu trả hàng thất bại." })); } } }
public void NestedTransactionScope_is_NOT_distributed_when_only_single_connection_opened() { var cs = TransactionTestHelper.DefaultConnectionString; using (var txOuter = new TransactionScope()) { using (SqlConnection c1 = new SqlConnection(cs)) { c1.Open(); Assert.IsTrue(Transaction.Current != null); Assert.IsFalse(Transaction.Current.IsDistributed()); } using (var txInner = new TransactionScope()) { using (SqlConnection c2 = new SqlConnection(cs)) { c2.Open(); Assert.IsTrue(Transaction.Current != null); Assert.IsFalse(Transaction.Current.IsDistributed()); } Assert.IsTrue(Transaction.Current != null); Assert.IsFalse(Transaction.Current.IsDistributed()); } } }
public void ExpenseCzar_Should_Generate() { int staffid = BusinessUser.Current == null ? -1 : Convert.ToInt32(BusinessUser.Current.UserKey); staffid = BusinessUser.Current == null ? -1 : Convert.ToInt32(BusinessUser.Current.UserKey); //var isolation = IsolationLevel.ReadUncommitted; using (var transaction = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(1, 1, 1))) { var generationDao = DataAccessFactory.Create<GenericDao>(); TestDao testDao = new TestDao(generationDao); int queueId = new ReportGenerationQueueBuilder() .WithGenerationDao(DataAccessFactory.CreateWithSameContext<GenerationDao>(generationDao)) .WithPeriod(201101) .WithReforecastQuarterName("Q0") .WithReportId(testDao.GetReportIdByName("Andre's Unit Test01")) .Build(); AbstractReportGenerator reportGenerator = ReportGeneratorFactory.GetReportGenerator(queueId); Assert.AreEqual(reportGenerator.GetType(), typeof(ExpenseCzarReportGenerator), "expected the report to use the expense czar generator"); reportGenerator.GenerateReport(); transaction.Dispose(); } }
public void Save(params ContentType[] contentTypes) { using (var ts = new TransactionScope()) using (var dataContext = new ContentDataContext(connectionString)) { var loadOptions = new DataLoadOptions(); loadOptions.LoadWith<ContentTypeItem>(ct => ct.ContentActionItems); dataContext.LoadOptions = loadOptions; var contentTypeItems = dataContext.ContentTypeItems.ToList(); var itemsToDelete = from data in contentTypeItems where !contentTypes.Any(t => t.Type == data.Type && t.ControllerName == data.ControllerName) select data; var itemsToUpdate = (from data in contentTypeItems let type = contentTypes.SingleOrDefault(t => t.Type == data.Type && t.ControllerName == data.ControllerName) where type != null select new { data, type }).ToList(); var itemsToInsert = (from type in contentTypes where !contentTypeItems.Any(t => t.Type == type.Type && t.ControllerName == type.ControllerName) select CreateContentTypeItem(type)).ToList(); itemsToUpdate.ForEach(i => UpdateContentTypeItem(i.data, i.type, dataContext)); dataContext.ContentTypeItems.DeleteAllOnSubmit(itemsToDelete); dataContext.ContentTypeItems.InsertAllOnSubmit(itemsToInsert); dataContext.SubmitChanges(); ts.Complete(); } }
public void RabbitMQBinding_TransactionalDispatching_ExceptionIfTransactionalChannelUsedOutOfTheTransactionScope() { IOneWayService channel = _channelFactory.CreateChannel(); Data data = new Data { Id = 1, Name = "Rabbit" }; A.CallTo(() => _errorProcessorFake.Say(A<Data>._)).DoesNothing(); A.CallTo(() => _processorFake.Say(A<Data>.Ignored)).Invokes(() => _ev.Set()); using (TransactionScope transaction = new TransactionScope(TransactionScopeOption.RequiresNew)) { channel.Say(data); // Complete the transaction transaction.Complete(); } bool wait = _ev.Wait(TimeSpan.FromSeconds(10)); Assert.IsTrue(wait, "Service were not being invoked"); // Same channel instance can't be used outsode transaction scope channel.Say(new Data()); Assert.Fail("Same channel instance can't be used outsode transaction scope"); }
public bool Delete(long id, out string errorMess) { using (var scope = new System.Transactions.TransactionScope()) { try { var x = context.Orders.Where(n => n.ID == id).SingleOrDefault(); if (x.Status == 0) { errorMess = "Đơn hàng này chưa thanh toán, Hãy thanh toán trước khi xóa đơn hàng!"; return(false); } var lst = (from a in context.OrderDetails where a.OrderID == id select a).ToList(); foreach (var item in lst) { context.OrderDetails.Remove(item); } var order = context.Orders.Find(id); context.Orders.Remove(order); context.SaveChanges(); scope.Complete(); errorMess = "Thanh toán xong!"; return(true); } catch (Exception ex) { errorMess = "Lỗi: " + ex; return(false); } } }
public bool createOrder(Order model, List <OrderDetail> lstItem) { using (var scope = new System.Transactions.TransactionScope()) { try { var order = new Order(); order.CustomerID = model.CustomerID; order.CreateDate = model.CreateDate; order.ShipName = model.ShipName; order.ShipMobile = model.ShipMobile; order.ShipEmail = model.ShipEmail; order.ShipAddress = model.ShipAddress; order.Status = model.Status; order.CustomerID = model.CustomerID; context.Orders.Add(order); context.SaveChanges(); foreach (var item in lstItem) { item.OrderID = order.ID; context.OrderDetails.Add(item); } context.SaveChanges(); scope.Complete(); return(true); } catch { return(false); } } }
public bool Success(long orderID) { using (var scope = new System.Transactions.TransactionScope()) { try { var order = context.Orders.Find(orderID); var lstDetail = context.OrderDetails.Where(n => n.OrderID == order.ID).ToList(); foreach (var item in lstDetail) { var quantityPay = item.Quantity; var product = context.Products.Where(n => n.ID == item.ProductID).SingleOrDefault(); product.Quantity = (product.Quantity - quantityPay); } order.Status = 1; context.SaveChanges(); scope.Complete(); return(true); } catch (Exception ex) { return(false); } } }
/// <summary>批量导入DataTable /// 批量导入DataTable /// </summary> /// <param name="dt">DataTable数据表</param> /// <param name="tableName">表名</param> /// <param name="dtColum">数据列集合</param> /// <return>Boolean值:true成功,false失败</return> public static Boolean InsertTable(DataTable dt, string tableName, DataColumnCollection dtColum) { using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(TransactionScopeOption.Required)) { using (SqlBulkCopy sqlBC = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["ApacheConnection"].ConnectionString, SqlBulkCopyOptions.KeepIdentity)) { sqlBC.BatchSize = 1000; sqlBC.BulkCopyTimeout = 30; sqlBC.DestinationTableName = tableName; for (int i = 0; i < dtColum.Count; i++) { sqlBC.ColumnMappings.Add(dtColum[i].ColumnName, dtColum[i].ColumnName); } try { //批量写入 sqlBC.WriteToServer(dt); scope.Complete(); return(true); } catch (Exception ex) { throw ex; } } } }
public static void HandleError(MsmqPoisonMessageException error) { ProcessorQueue processorQueue = (ProcessorQueue)error.Data["processorQueue"]; MessageQueue poisonQueue = new System.Messaging.MessageQueue(processorQueue.PoisonQueue); MessageQueue errorQueue = new System.Messaging.MessageQueue(processorQueue.ErrorQueue); using (TransactionScope txScope = new TransactionScope(TransactionScopeOption.RequiresNew)) { try { // Send the message to the poison and error message queues. poisonQueue.Send((IWorkflowMessage)error.Data["message"], MessageQueueTransactionType.Automatic); errorQueue.Send((WorkflowErrorMessage)error.Data["errorMessage"], MessageQueueTransactionType.Automatic); txScope.Complete(); } catch (InvalidOperationException) { } finally { poisonQueue.Dispose(); errorQueue.Dispose(); } } }
//記錄Exp資訊 public void LogExpInf() { //記錄狀態為Exception this.ErrFlag = false; //寫入Log //不使用Transaction , 以正確的記錄發生那些Error using (System.Transactions.TransactionScope Ts = new System.Transactions.TransactionScope(TransactionScopeOption.Suppress)) { //設定連結字串 Database db = this.GetDatabase(); StringBuilder sbCommand = new StringBuilder(); sbCommand.Append("INSERT INTO ExpLog (ClassName, MethodName, ErrMsg, UDate) "); sbCommand.Append("VALUES (@ClassName,@MethodName,@ErrMsg, getdate()) "); DbCommand dbCommand = db.GetSqlStringCommand(sbCommand.ToString()); db.AddInParameter(dbCommand, "@ClassName", DbType.String, this.GetType().FullName.ToString()); db.AddInParameter(dbCommand, "@MethodName", DbType.String, this.ErrMethodName); db.AddInParameter(dbCommand, "@ErrMsg", DbType.String, this.ErrMsg); try { db.ExecuteNonQuery(dbCommand); } catch { throw; } } }
/// <summary> /// add number /// </summary> /// <param name="_code"></param> /// <param name="_newVal"></param> public void add(string _code, string _newVal) { LTDHDataContext DB = new LTDHDataContext(@strPathDB); try { using (TransactionScope ts = new TransactionScope()) { var r = DB.tblStatistics.Single(p => p.Code == _code); long oldVal = long.Parse(r.Value); long newVal = long.Parse(_newVal); if (oldVal > 0 || newVal > 0) { oldVal += newVal; } r.Value = oldVal.ToString(); DB.SubmitChanges(); ts.Complete(); } } catch (Exception e) { log.writeLog(DBHelper.strPathLogFile, e.Message + CommonConstants.NEWLINE + e.Source + CommonConstants.NEWLINE + e.StackTrace + CommonConstants.NEWLINE + e.HelpLink); } }
private void Handle(IReadOnlyCollection<IAggregateCommand> commands) { var aggregateRootTypes = commands.Select(x => x.AggregateRootType).ToArray(); var actors = _aggregateActorFactory.Create(aggregateRootTypes); // TODO: Can agreggate actors be executed in parallel? See https://github.com/2gis/nuclear-river/issues/76 foreach (var actor in actors) { var actorName = actor.GetType().GetFriendlyName(); using (var transaction = new TransactionScope( TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TimeSpan.Zero })) { using (Probe.Create($"ETL2 {actorName}")) { actor.ExecuteCommands(commands); } transaction.Complete(); } } _telemetryPublisher.Publish<StatisticsProcessedOperationCountIdentity>(commands.Count); }
public Package CreatePackage(IPackage nugetPackage, User currentUser) { ValidateNuGetPackage(nugetPackage); var packageRegistration = CreateOrGetPackageRegistration(currentUser, nugetPackage); var package = CreatePackageFromNuGetPackage(packageRegistration, nugetPackage); packageRegistration.Packages.Add(package); using (var tx = new TransactionScope()) { using (var stream = nugetPackage.GetStream()) { UpdateIsLatest(packageRegistration); packageRegistrationRepo.CommitChanges(); packageFileSvc.SavePackageFile(package, stream); tx.Complete(); } } if (package.Status != PackageStatusType.Approved && package.Status != PackageStatusType.Exempted) NotifyForModeration(package, comments: string.Empty); NotifyIndexingService(); return package; }
public void MessageSent_EventIsRaised() { using (var receiver = ObjectMother.QueueManager(TEST_QUEUE_2, 23457)) { receiver.Start(); using (var tx = new TransactionScope()) { _sender.Send( new Uri("lq.tcp://localhost:23457/h"), new MessagePayload { Data = new byte[] {1, 2, 4, 5} }); tx.Complete(); } _sender.WaitForAllMessagesToBeSent(); } var log = _logger.DebugMessages.OfType<MessagesSent>().FirstOrDefault(); log.ShouldNotBeNull(); "localhost".ShouldEqual(log.Destination.Host); 23457.ShouldEqual(log.Destination.Port); "h".ShouldEqual(log.Messages[0].Queue); }
private static void list_video() { using (TransactionScope transactionScope = new TransactionScope()) { SqlConnection sqlConnection = connect_database(); using (SqlCommand command = new SqlCommand()) { command.Connection = sqlConnection; command.CommandType = System.Data.CommandType.Text; command.CommandText = String.Format("SELECT PkId,Id,Description FROM {0}", table_name); try { SqlDataReader reader = command.ExecuteReader(); Console.WriteLine("\n List Video in Database"); Console.WriteLine("=============================="); while (reader.Read()) { Console.WriteLine("ID: {0}, Name : {1}, Identifier : {2}", reader.GetValue(0), reader.GetValue(2), reader.GetValue(1)); } Console.WriteLine("============================== \n"); } catch (Exception e) { Console.WriteLine("{0}", e); } } disconnect_database(sqlConnection); transactionScope.Complete(); } }
public void CreateAccount(String accountName, int customerID, int roleID) { Customer customer = _repository.Get<Customer>(customerID); if (customer == null) { throw new AccountServicesException("No customer found for the ID: " + customerID); } Role role = _repository.Get<Role>(roleID); if (role == null) { throw new AccountServicesException("No role found for the ID: " + roleID); } Account account = new Account(); account.Name = accountName; customer.RelatedAccounts.Add(account, role); account.RelatedCustomers.Add(customer, role); using (TransactionScope scope = new TransactionScope()) { _repository.Save<Account>(account); _repository.SaveOrUpdate<Customer>(customer); scope.Complete(); } }
public void Wrapper(Action method) { using (var scope = new TransactionScope()) { var retries = 3; var succeeded = false; while (!succeeded) { try { method(); scope.Complete(); succeeded = true; } catch (Exception ex) { if (retries >= 0) retries--; else { if (!Exceptions.Handle(ex)) throw; } } } } }
public void Init() { using (var transaction = new TransactionScope(TransactionScopeOption.Suppress)) using (var session = subscriptionStorageSessionProvider.OpenStatelessSession()) using (var tx = session.BeginTransaction(System.Data.IsolationLevel.ReadCommitted)) { var v2XSubscriptions = session.QueryOver<Subscription>() .Where(s => s.TypeName == null) .List(); if (v2XSubscriptions.Count == 0) return; Logger.DebugFormat("Found {0} v2X subscriptions going to upgrade", v2XSubscriptions.Count); foreach (var v2XSubscription in v2XSubscriptions) { var mt = new MessageType(v2XSubscription.MessageType); v2XSubscription.Version = mt.Version.ToString(); v2XSubscription.TypeName = mt.TypeName; session.Update(v2XSubscription); } tx.Commit(); transaction.Complete(); Logger.InfoFormat("{0} v2X subscriptions upgraded", v2XSubscriptions.Count); } }
public override void Run(Object fixture) { using (TransactionScope transactionScope = new TransactionScope()) { this.TestCase.Run(fixture); } }
public void Raven_dtc_bug() { new MessageQueue(QueueAddress, QueueAccessMode.ReceiveAndAdmin) .Purge(); using (var tx = new TransactionScope()) { using (var session = store.OpenSession()) { session.Store(new GatewayMessage()); session.SaveChanges(); } using (var q = new MessageQueue(QueueAddress, QueueAccessMode.Send)) { var toSend = new Message { BodyStream = new MemoryStream(new byte[8]) }; //sending a message to a msmq queue causes raven to promote the tx q.Send(toSend, MessageQueueTransactionType.Automatic); } //when we complete raven commits it tx but the DTC tx is never commited and eventually times out tx.Complete(); } Thread.Sleep(1000); Assert.AreEqual(1,new MessageQueue(QueueAddress, QueueAccessMode.ReceiveAndAdmin) .GetAllMessages().Length); }
public void When_using_DTC_HiLo_knows_to_create_isolated_DTC_transaction() { object scalar1, scalar2; using (var session = sessions.OpenSession()) using (var command = session.Connection.CreateCommand()) { command.CommandText = "select next_hi from hibernate_unique_key with (updlock, rowlock)"; scalar1 = command.ExecuteScalar(); } using (var tx = new TransactionScope()) { var generator = sessions.GetIdentifierGenerator(typeof(Person).FullName); Assert.That(generator, Is.InstanceOf<TableHiLoGenerator>()); using(var session = sessions.OpenSession()) { var id = generator.Generate((ISessionImplementor) session, new Person()); } // intentionally dispose without committing tx.Dispose(); } using (var session = sessions.OpenSession()) using (var command = session.Connection.CreateCommand()) { command.CommandText = "select next_hi from hibernate_unique_key with (updlock, rowlock)"; scalar2 = command.ExecuteScalar(); } Assert.AreNotEqual(scalar1, scalar2,"HiLo must run with in its own transaction"); }
public void GetSession_WhenInDifferentTransaction_ThenDifferentSessionAreUsed() { this.pooledPooledSessionFactoryMock.EnqueueNewSessions(2); ISession session1; ISession session2; using (var tx1 = new TransactionScope()) { session1 = this.testee.GetSession(); this.testee.Release(session1); using (var tx2 = new TransactionScope(TransactionScopeOption.RequiresNew)) { session2 = this.testee.GetSession(); this.testee.Release(session2); tx2.Complete(); } tx1.Complete(); } session1.Should().NotBeSameAs(session2); }
public void Confirm(string tradeNo) { ExceptionHelper.ThrowIfNullOrWhiteSpace(tradeNo, "tradeNo"); tradeNo = tradeNo.Trim(); var entity = _TradeRepository.Entities.FirstOrDefault(t => t.tradeNo == tradeNo); if (!entity.isPaied) { entity.isPaied = true; entity.paied = DateTime.Now; _TradeRepository.SaveChanges(); } if (!entity.buySuccess) { using (var scope = new System.Transactions.TransactionScope()) { entity.buySuccess = true; entity.successed = DateTime.Now; _TradeRepository.SaveChanges(); var tradeExtension = Newtonsoft.Json.JsonConvert.DeserializeObject <TradeExtension>(entity.extension); OpenService(tradeExtension.timeSpan, tradeNo); scope.Complete(); } } }
public IEnumerable<Feature> GetFeatures() { IEnumerable<Feature> features = null; using (var scope = new TransactionScope(TransactionScopeOption.Suppress)) { features = GetQuery().ToList(); } return features; }
public void CreateConstraint_PreventsDuplicates() { var clientFactory = Fluently.Configure("http://localhost:7474/db/data/").CreateSessionFactory(); var endpoint = clientFactory.Create(); var uniqueLabel = "anotherUniqueLabel"; try { endpoint.CreateConstraint(uniqueLabel, "name"); using (var trans = new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.FromDays(1))) { var txEndpoint = clientFactory.Create(); txEndpoint.CreateNode(new { name = "fred", age = 33 }, uniqueLabel); txEndpoint.CreateNode(new { name = "fred", age = 33 }, uniqueLabel); } } catch(Exception ex) { Assert.IsTrue(ex is CypherResponseException); } finally { endpoint.DropConstraint(uniqueLabel, "name"); } }
void DoWork(IReceiveMessages messageQueue) { try { using (var tx = new TransactionScope()) { var ctx = new AmbientTransactionContext(); var receivedTransportMessage = messageQueue.ReceiveMessage(ctx); if (receivedTransportMessage == null) return; try { SendMessage(receivedTransportMessage); tx.Complete(); } catch (Exception e) { log.Error(e, "Could not send message {0} to destination URI {1} - waiting 1 sec before retrying", receivedTransportMessage.Id, destinationUri); Thread.Sleep(TimeSpan.FromSeconds(1)); } } } catch (Exception e) { log.Error("Unhandled exception during receive operation", e); } }
public ActionResult Index(int?page) { DateTime dt = DateTime.Now; DateTime endTime = dt.AddDays(1 - Convert.ToInt32(dt.DayOfWeek.ToString("d"))); NameValueCollection q = new NameValueCollection(); q.Add("CreatedAtStart", endTime.AddDays(-1).ToString("yyyy/MM/dd 10:00")); q.Add("CreatedAtEnd", DateTime.Now.AddHours(1).ToString("yyyy/MM/dd HH:00")); InspectOriginQueryModel query = new InspectOriginQueryModel(q); IPagedList <InspectOrigin> inspects = null; using (var txn = new System.Transactions.TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted })) { using (IUnitOfWork unitOfWork = new TskDataDataContext(DbUtil.ConnectionString)) { int currentPageIndex = page.HasValue ? (page.Value <= 0 ? 0 : page.Value - 1) : 0; IInspectOriginRep inspectOriginRep = new InspectOriginRep(unitOfWork); inspects = inspectOriginRep.Queryable(query.CreatedAtStart, query.CreatedAtEnd).ToPagedList(currentPageIndex, int.Parse(Resources.PageSize)); } } ViewBag.Query = query; return(View(inspects)); }
public void Save() { using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope()) { context.SaveChanges(); scope.Complete(); } }
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 disposeTransactionScope() { if (_transactionScope != null) { _transactionScope.Dispose(); _transactionScope = null; } }
public void UseTransaction(System.Action <DbContext> func) { using (var scope = new System.Transactions.TransactionScope()) { func(this); scope.Complete(); } }
public ActionResult XuatHuy(ExportModelXuatHuy model) { var ctx = new SmsContext(); using (var transaction = new System.Transactions.TransactionScope()) { try { var infor = ctx.XUAT_KHO.Create(); infor.MA_KHO_XUAT = model.Infor.MA_KHO_XUAT; infor.NGAY_XUAT = model.Infor.NGAY_XUAT; infor.MA_NHAN_VIEN_XUAT = Convert.ToInt32(Session["UserId"]); infor.CREATE_AT = DateTime.Now; infor.CREATE_BY = Convert.ToInt32(Session["UserId"]); infor.UPDATE_AT = DateTime.Now; infor.UPDATE_BY = Convert.ToInt32(Session["UserId"]); infor.ACTIVE = "A"; infor.GHI_CHU = model.Infor.GHI_CHU; infor.LY_DO_XUAT = 1; // nhập mua hàng ctx.XUAT_KHO.Add(infor); ctx.SaveChanges(); CHI_TIET_XUAT_KHO exportDetail; foreach (var detail in model.Detail) { if (detail.DEL_FLG != 1 && detail.MA_SAN_PHAM != null && !string.IsNullOrEmpty(detail.MA_SAN_PHAM.ToString())) { exportDetail = ctx.CHI_TIET_XUAT_KHO.Create(); exportDetail.ACTIVE = "A"; exportDetail.MA_SAN_PHAM = detail.MA_SAN_PHAM; exportDetail.SO_LUONG_TEMP = detail.SO_LUONG_TEMP; exportDetail.HE_SO = detail.HE_SO; exportDetail.SO_LUONG = detail.SO_LUONG_TEMP * detail.HE_SO; exportDetail.MA_DON_VI = detail.MA_DON_VI; exportDetail.MA_XUAT_KHO = infor.MA_XUAT_KHO; exportDetail.CREATE_AT = DateTime.Now; exportDetail.CREATE_BY = Convert.ToInt32(Session["UserId"]); exportDetail.UPDATE_AT = DateTime.Now; exportDetail.UPDATE_BY = Convert.ToInt32(Session["UserId"]); exportDetail.GIA_VON = detail.GIA_VON / detail.HE_SO; ctx.CHI_TIET_XUAT_KHO.Add(exportDetail); ctx.SaveChanges(); } } transaction.Complete(); ctx.Dispose(); return(RedirectToAction("ExportCancelList", new { @inforMessage = "Xuất hủy thành công." })); } catch (Exception) { Transaction.Current.Rollback(); ctx.Dispose(); return(RedirectToAction("ExportCancelList", new { @message = "Xuất hủy thất bại, vui lòng liên hệ admin." })); } } }
public void DeleteTest() { using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope()) { string path = "c:\\tmp\\TestFolder"; Directory.Delete(path, false); ts.Complete(); } }
public async Task Process(IncomingStepContext context, Func <Task> next) { using (var scope = new System.Transactions.TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { await next(); scope.Complete(); } }
public void GetDirectoryTest() { using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope()) { string pathDirectory = @"c:\tmp\"; Directory actual; actual = Directory.GetDirectory(pathDirectory); } }
public override int SaveChanges() { const EntityState entitiesToTrack = EntityState.Added | EntityState.Modified | EntityState.Deleted; ObjectContext.DetectChanges(); var elementsToSave = ObjectContext .ObjectStateManager .GetObjectStateEntries(entitiesToTrack).Select(ose => new Tuple <ObjectStateEntry, EntityState, bool>(ose, ose.State, ose.IsRelationship)) .ToList(); //http://stackoverflow.com/questions/6028626/ef-code-first-dbcontext-and-transactions //http://petermeinl.wordpress.com/2011/03/13/avoiding-unwanted-escalation-to-distributed-transactions/ using (var transactopnScope = new System.Transactions.TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted })) { try { elementsToSave.ForEach(InterceptBefore); var result = base.SaveChanges(); elementsToSave.ForEach(InterceptAfter); var resultAfter = base.SaveChanges(); transactopnScope.Complete(); return(result); } catch (DbEntityValidationException e) { //http://stackoverflow.com/questions/7795300/validation-failed-for-one-or-more-entities-see-entityvalidationerrors-propert var errormessage = new StringBuilder(); foreach (var eve in e.EntityValidationErrors) { errormessage.AppendFormat( "Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); errormessage.AppendLine(); foreach (var ve in eve.ValidationErrors) { errormessage.AppendFormat("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); errormessage.AppendLine(); } } throw new Exception(errormessage.ToString()); } catch (InvalidOperationException e) { //todo: need to understand why this happens. return(0); } } //Debug.WriteLine(((AuditTrailChangeInterceptor) Interceptors.Single(i => i is AuditTrailChangeInterceptor)).AuditDump()); }
private bool putCoins(XCGameManaDeviceStoreType deviceStoreType, string xcGameDBName, string mobile, int balance, int coins, int icCardId, string segment, string deviceId, int deviceIdentityId, out int lastBalance, out string errMsg) { errMsg = string.Empty; lastBalance = 0; //提币数据库操作 if (deviceStoreType == XCGameManaDeviceStoreType.Store) { XCCloudService.BLL.IBLL.XCGame.Iflw_485_coinService coinService = BLLContainer.Resolve <XCCloudService.BLL.IBLL.XCGame.Iflw_485_coinService>(xcGameDBName); XCCloudService.BLL.IBLL.XCGame.IMemberService memberService = BLLContainer.Resolve <XCCloudService.BLL.IBLL.XCGame.IMemberService>(xcGameDBName); var memberModel = memberService.GetModels(p => p.Mobile.Equals(mobile, StringComparison.OrdinalIgnoreCase)).FirstOrDefault <XCCloudService.Model.XCGame.t_member>(); memberModel.Balance = Convert.ToInt32(memberModel.Balance) - coins; lastBalance = (int)(memberModel.Balance); XCCloudService.Model.XCGame.flw_485_coin coinModel = new Model.XCGame.flw_485_coin(); coinModel.Balance = Convert.ToInt32(memberModel.Balance) - coins; coinModel.ICCardID = icCardId; coinModel.Segment = segment; coinModel.HeadAddress = ""; coinModel.Coins = coins; coinModel.CoinType = "3"; coinModel.RealTime = System.DateTime.Now; coinModel.SN = 0; using (var transactionScope = new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew)) { coinService.Add(coinModel); memberService.Update(memberModel); transactionScope.Complete(); } return(true); } else if (deviceStoreType == XCGameManaDeviceStoreType.Merch) { XCCloudService.BLL.IBLL.XCCloudRS232.Iflw_485_coinService coinService = BLLContainer.Resolve <XCCloudService.BLL.IBLL.XCCloudRS232.Iflw_485_coinService>(xcGameDBName); XCCloudService.BLL.IBLL.XCCloudRS232.IMemberService memberService = BLLContainer.Resolve <XCCloudService.BLL.IBLL.XCCloudRS232.IMemberService>(xcGameDBName); var memberModel = memberService.GetModels(p => p.Mobile.Equals(mobile, StringComparison.OrdinalIgnoreCase)).FirstOrDefault <XCCloudService.Model.XCCloudRS232.t_member>(); memberModel.Balance = Convert.ToInt32(memberModel.Balance) - coins; lastBalance = (int)(memberModel.Balance); XCCloudService.Model.XCCloudRS232.flw_485_coin coinModel = new XCCloudService.Model.XCCloudRS232.flw_485_coin(); coinModel.Balance = Convert.ToInt32(memberModel.Balance) - coins; coinModel.ICCardID = icCardId; coinModel.DeviceID = deviceIdentityId; coinModel.Coins = coins; coinModel.CoinType = 3; using (var transactionScope = new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew)) { coinService.Add(coinModel); memberService.Update(memberModel); transactionScope.Complete(); } return(true); } else { return(false); } }
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(); } } }
public void CreateSymbolicLinkTest() { using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope()) { string pathSymbolicLinkDirectory = @"c:\tmp\TestFiles_SL"; string pathDirector = @"c:\Progetti\WIN\System.IO.Transactions.TxF\TestFiles\"; Directory.CreateSymbolicLink(pathSymbolicLinkDirectory, pathDirector); ts.Complete(); } }
/// <summary> /// 使用事物 在事物里面的代码都是走master /// </summary> /// <param name="func"></param> public void UseTransaction(System.Func <DbContext, bool> func) { using (var scope = new System.Transactions.TransactionScope()) { if (func(this)) { scope.Complete(); } } }
protected override object DoOperation(AUObjectOperationContext context) { using (System.Transactions.TransactionScope ts = TransactionScopeFactory.Create()) { bool changeRelationToSchemaDemanded = true; bool changeRelationToUnitDemanded = true; //当不是删除操作,且需要修改关系时 if (this.Data.Status == SchemaObjectStatus.Normal && (OverrideExistedRelation || this.relationExists == false)) { SchemaRelationObjectAdapter.Instance.Update(this.targetRelation); } else if (this.Data.Status == SchemaObjectStatus.Deleted && (OverrideExistedRelation || this.relationExists)) { if (oldRelationToChildren.Any(m => m.Status == SchemaObjectStatus.Normal)) { throw new AUObjectValidationException("管理单元存在子对象,不能进行删除操作"); } SchemaRelationObjectAdapter.Instance.UpdateStatus(this.targetRelation, SchemaObjectStatus.Deleted); } if (oldRelationToSchema != null && this.targetRelation.ParentID == this.oldRelationToSchema.ParentID) { changeRelationToSchemaDemanded = false; } if (oldRelationToUnit != null && this.targetRelation.ParentID == this.oldRelationToUnit.ParentID) { changeRelationToUnitDemanded = false; } if (changeRelationToSchemaDemanded && this.oldRelationToSchema != null && this.oldRelationToSchema.Status == SchemaObjectStatus.Normal) { SchemaRelationObjectAdapter.Instance.UpdateStatus(this.oldRelationToSchema, SchemaObjectStatus.Deleted); } if (changeRelationToUnitDemanded && this.oldRelationToUnit != null && this.oldRelationToUnit.Status == SchemaObjectStatus.Normal) { SchemaRelationObjectAdapter.Instance.UpdateStatus(this.oldRelationToUnit, SchemaObjectStatus.Deleted); } SchemaObjectAdapter.Instance.Update(Data); this.DoRelativeDataOperation(context); if (this.aclContainer != null) { DBTimePointActionContext.Current.DoActions(() => SCAclAdapter.Instance.Update(this.aclContainer)); } ts.Complete(); } return(this.TargetRelation); }
public ActionResult EditCancelTicket(EditCancelTicketModel model) { var ctx = new SmsContext(); using (var transaction = new System.Transactions.TransactionScope()) { try { var infor = ctx.XUAT_KHO.Find(model.Infor.MA_XUAT_KHO); if (infor == null || infor.ACTIVE != "A") { return(RedirectToAction("ExportCancelList", new { @message = "Phiếu xuất hủy này không tồn tại, vui lòng liên hệ admin." })); } infor.MA_KHO_XUAT = model.Infor.MA_KHO_XUAT; infor.NGAY_XUAT = model.Infor.NGAY_XUAT; infor.UPDATE_AT = DateTime.Now; infor.UPDATE_BY = Convert.ToInt32(Session["UserId"]); infor.GHI_CHU = model.Infor.GHI_CHU; infor.LY_DO_XUAT = 1; ctx.SaveChanges(); ctx.CHI_TIET_XUAT_KHO.RemoveRange(ctx.CHI_TIET_XUAT_KHO.Where(u => u.MA_XUAT_KHO == model.Infor.MA_XUAT_KHO)); CHI_TIET_XUAT_KHO exportDetail; foreach (var detail in model.Detail) { if (detail.DEL_FLG != 1 && detail.MA_SAN_PHAM != null && !string.IsNullOrWhiteSpace(detail.MA_SAN_PHAM.ToString())) { exportDetail = ctx.CHI_TIET_XUAT_KHO.Create(); exportDetail.ACTIVE = "A"; exportDetail.MA_SAN_PHAM = detail.MA_SAN_PHAM; exportDetail.SO_LUONG_TEMP = detail.SO_LUONG_TEMP; exportDetail.HE_SO = detail.HE_SO; exportDetail.SO_LUONG = detail.SO_LUONG_TEMP * detail.HE_SO; exportDetail.MA_DON_VI = detail.MA_DON_VI; exportDetail.MA_XUAT_KHO = infor.MA_XUAT_KHO; exportDetail.CREATE_AT = DateTime.Now; exportDetail.CREATE_BY = Convert.ToInt32(Session["UserId"]); exportDetail.UPDATE_AT = DateTime.Now; exportDetail.UPDATE_BY = Convert.ToInt32(Session["UserId"]); ctx.CHI_TIET_XUAT_KHO.Add(exportDetail); ctx.SaveChanges(); } } transaction.Complete(); ctx.Dispose(); return(RedirectToAction("ExportCancelList", new { @inforMessage = "Sửa phiếu xuất hủy thành công." })); } catch (Exception) { Transaction.Current.Rollback(); ctx.Dispose(); return(RedirectToAction("ExportCancelList", new { @message = "Sửa phiếu xuất hủy thất bại, vui lòng liên hệ admin." })); } } }
/// <summary> /// 删除指定流程步骤数据 /// </summary> /// <param name="nId">步骤编码</param> /// <param name="nOpStaffId">操作员工编码</param> /// <param name="strOpStaffName">操作员工姓名</param> /// <param name="strErrText">出错信息</param> /// <returns></returns> public bool DeleteApproveFlowStep(long nId, long nOpStaffId, string strOpStaffName, out string strErrText) { try { using (TransactionScope transScope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(2, 0, 0))) { using (FlowDAO dao = new FlowDAO()) { //删除步骤数据 if (!dao.DeleteApproveFlowStep(nId, nOpStaffId, strOpStaffName, out strErrText)) { return false; } //删除原条件数据 if (!dao.DeleteApproveFlowStepConditions(nId, nOpStaffId, strOpStaffName, out strErrText)) { return false; } } transScope.Complete(); } return true; } catch (Exception e) { strErrText = e.Message; return false; } }