当前位置: 首页>>代码示例>>C#>>正文


C# Transactions.TransactionScope类代码示例

本文整理汇总了C#中System.Transactions.TransactionScope的典型用法代码示例。如果您正苦于以下问题:C# TransactionScope类的具体用法?C# TransactionScope怎么用?C# TransactionScope使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


TransactionScope类属于System.Transactions命名空间,在下文中一共展示了TransactionScope类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ExecuteProcess

        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();
            }
        }
开发者ID:xximjasonxx,项目名称:Codemash,代码行数:30,代码来源:PollerWorkerRole.cs

示例2: GuardarAsignaciones

        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);
            }
        }
开发者ID:steel-framing,项目名称:metal-forming,代码行数:33,代码来源:OrdenVentaBL.cs

示例3: GetFeatures

 public IEnumerable<Feature> GetFeatures() {
     IEnumerable<Feature> features = null;
     using (var scope = new TransactionScope(TransactionScopeOption.Suppress)) {
         features = GetQuery().ToList();
     }
     return features;
 } 
开发者ID:CloudMetal,项目名称:Liveo.Deployment,代码行数:7,代码来源:LiveoFeatureService.cs

示例4: GetSession_WhenInDifferentTransaction_ThenDifferentSessionAreUsed

        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);
        }
开发者ID:afyles,项目名称:NServiceBus,代码行数:25,代码来源:DtcTransactionSessionFactoryTest.cs

示例5: CreatePackage

        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;
        }
开发者ID:PatOShea,项目名称:chocolatey.org,代码行数:26,代码来源:PackageService.cs

示例6: add

 /// <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);
     }
 }
开发者ID:vuchannguyen,项目名称:ducnghia,代码行数:35,代码来源:Statistics.cs

示例7: RabbitMQBinding_TransactionalDispatching_ExceptionIfTransactionalChannelUsedOutOfTheTransactionScope

        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");
        }
开发者ID:ronybot,项目名称:MessageBus,代码行数:30,代码来源:TransactionalOneWayTest.cs

示例8: Raven_dtc_bug

        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);
        }
开发者ID:afyles,项目名称:NServiceBus,代码行数:30,代码来源:When_acking_an_existing_message.cs

示例9: CreateAccount

        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();
            }
        }
开发者ID:al-main,项目名称:CloudyBank,代码行数:26,代码来源:AccountServices.cs

示例10: HandleError

        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();
                }
            }
        }
开发者ID:invertedsoftware,项目名称:Inverted-Software-Workflow-Engine,代码行数:26,代码来源:QueueOperationsHandler.cs

示例11: NestedTransactionScope_is_NOT_distributed_when_only_single_connection_opened

        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());
                }
            }
        }
开发者ID:yaoyel,项目名称:Finework,代码行数:26,代码来源:TransactionTests.cs

示例12: DoWork

        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);
            }
        }
开发者ID:JanRou,项目名称:Rebus,代码行数:31,代码来源:OutboundService.cs

示例13: Init

        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);
            }
        }
开发者ID:afyles,项目名称:NServiceBus,代码行数:29,代码来源:SubscriptionStorage.cs

示例14: When_using_DTC_HiLo_knows_to_create_isolated_DTC_transaction

		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");
		}
开发者ID:juanplopes,项目名称:nhibernate,代码行数:34,代码来源:Fixture.cs

示例15: RegisterCustomer

        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);
            }                                
        }
开发者ID:RytisCapas,项目名称:InventoryManagement,代码行数:29,代码来源:RegistrationService.cs


注:本文中的System.Transactions.TransactionScope类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。