• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Transactions.TransactionScope类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: MessageQueuedForReceive_EventIsRaised

        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);
        }
开发者ID:BclEx,项目名称:rhino-esb,代码行数:28,代码来源:RaisingReceivedEvents.cs


示例17: Run

 public override void Run(Object fixture)
 {
     using (TransactionScope transactionScope = new TransactionScope())
     {
         this.TestCase.Run(fixture);
     }
 }
开发者ID:sayedjalilhassan,项目名称:LearningPlatform,代码行数:7,代码来源:RollbackAttribute.cs


示例18: Wrapper

 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;
                 }
             }
         }
     }
 }
开发者ID:hurricanepkt,项目名称:AOPinNET,代码行数:27,代码来源:TransactionManager2.cs


示例19: CreateDummyEntities

        //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();
                }
            }
        }
开发者ID:fengyu25,项目名称:comp5348,代码行数:33,代码来源:Program.cs


示例20: MessageSent_EventIsRaised

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



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Web.HtmlString类代码示例发布时间:2022-05-26
下一篇:
C# Transactions.TransactionOptions类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap