コード例 #1
0
        static void ThreadMethod(object dependentTx)
        {
            DependentTransaction dTx = dependentTx as DependentTransaction;

            try
            {
                Transaction.Current = dTx;

                using (TransactionScope scope = new TransactionScope())
                {
                    Transaction.Current.TransactionCompleted += TransactionCompleted;

                    Utilities.DisplayTransactionInformation("Thread TX", Transaction.Current.TransactionInformation);
                    scope.Complete();
                }
            }
            catch (TransactionAbortedException ex)
            {
                Console.WriteLine("ThreadMethod - Transaction was aborted, {0}", ex.Message);
            }
            finally
            {
                if (dTx != null)
                {
                    dTx.Complete();
                }
            }
        }
コード例 #2
0
 private async Task AutoUpdateFeed(System.Timers.Timer timernew)
 {
     await Task.Factory.StartNew(() =>
     {
         var currentDatetime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"));
         var time            = currentDatetime.ToString("hh:mm tt");
         try
         {
             var feedMgr = IoC.Initialize().GetInstance <IFeedMgr>();
             using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new System.TimeSpan(0, 30, 0)))
             {
                 using (NewsContext _context = new NewsContext())
                 {
                     Transaction rootTr = Transaction.Current;
                     var itemFeeds      = _context.FeedNames;
                     var rssFeeds       = _context.NewsItems;
                     foreach (var itemUrl in itemFeeds)
                     {
                         DependentTransaction dt = rootTr.DependentClone(DependentCloneOption.RollbackIfNotComplete);
                         var rssData             = feedMgr.ParseFeedUrl(itemUrl.Url, false);
                         _newsFeedMgr.Save(rssData);
                         dt.Complete();
                     }
                     _context.Dispose();
                 }
                 scope.Complete();
             }
             timernew.Start();
         }
         catch (Exception ex)
         {
             throw ex;
         }
     });
 }
コード例 #3
0
ファイル: GenericWorkBatchService.cs プロジェクト: jjg0519/OA
        protected override void CommitWorkBatch(CommitWorkBatchCallback commitWorkBatchCallback)
        {
            TraceHelper.Trace();

            Transaction transactionToUse;

            if (Transaction.Current == null)
            {
                transactionToUse = new CommittableTransaction();
                WfLogHelper.WriteLog("CommitWorkBatch提交TransactionScope事务Transaction.Current==null");
            }
            else
            {
                transactionToUse = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
                WfLogHelper.WriteLog("CommitWorkBatch提交TransactionScope事务Transaction.Current!=null");
            }

            TransactionCreated(transactionToUse);

            try
            {
                using (TransactionScope txScope = new TransactionScope(transactionToUse))
                {
                    commitWorkBatchCallback();
                    txScope.Complete();
                    WfLogHelper.WriteLog("CommitWorkBatch提交TransactionScope事务Complete完成......");
                }

                CommittableTransaction committableTransaction = transactionToUse as CommittableTransaction;
                if (committableTransaction != null)
                {
                    committableTransaction.Commit();
                    WfLogHelper.WriteLog("CommitWorkBatch提交committableTransaction事务Complete完成......");
                }

                DependentTransaction dependentTransaction = transactionToUse as DependentTransaction;
                if (dependentTransaction != null)
                {
                    dependentTransaction.Complete();
                    WfLogHelper.WriteLog("CommitWorkBatch提交dependentTransaction事务Complete完成......");
                }

                WorkBatchCommitted(transactionToUse);
            }
            catch (Exception e)
            {
                transactionToUse.Rollback(e);

                WorkBatchRolledback(transactionToUse);

                throw;
            }
            finally
            {
                if (transactionToUse != null)
                {
                    transactionToUse.Dispose();
                }
            }
        }
コード例 #4
0
 // ........................................................................................................
 internal static void Complete(Transaction transaction, Exception error)
 {
     try
     {
         if (error == null)
         {
             CommittableTransaction commit = (transaction as CommittableTransaction);
             if (commit != null)
             {
                 commit.Commit();
             }
             else
             {
                 DependentTransaction complete = (transaction as DependentTransaction);
                 if (complete != null)
                 {
                     complete.Complete();
                 }
             }
         }
         else
         {
             transaction.Rollback();
         }
     }
     catch (TransactionException e)
     {
         DiagnosticUtility.TraceHandledException(e, TraceEventType.Error);
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TransactionBehavior.CreateFault(SR.GetString(SR.SFxTransactionAsyncAborted), FaultCodeConstants.Codes.TransactionAborted, true));
     }
 }
コード例 #5
0
        public void ThreadProc(object tsObject)
        {
            DependentTransaction dts = (DependentTransaction)tsObject;

            Debug.WriteLine(string.Format("{0} Opening dependent transaction", DateTime.Now));

            using (TransactionScope ts = new TransactionScope(dts))
            {
                Debug.WriteLine(string.Format("{0} Going to sleep", DateTime.Now));

                Thread.Sleep(10000);

                Debug.WriteLine(string.Format("{0} Completing dependent transaction", DateTime.Now));

                ts.Complete();

                Debug.WriteLine(string.Format("{0} Dependent transaction completed, setting event", DateTime.Now));

                _txCompleted.Set();
            }

            Debug.WriteLine(string.Format("{0} Completing outer transaction", DateTime.Now));

            dts.Complete();

            Debug.WriteLine(string.Format("{0} Thread Exiting", DateTime.Now));
        }
コード例 #6
0
        /// <summary>
        ///     Create a <see cref="UserClaim"/>.
        /// </summary>
        /// <param name="userId">The user Id.</param>
        /// <param name="claims">The claims.</param>
        /// <param name="transaction">The transaction.</param>
        /// <returns></returns>
        public async Task Create(Guid userId, IEnumerable <UserClaim> claims, DependentTransaction transaction = null)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentException("Invalid user Id", nameof(userId));
            }

            using (var tx = transaction != null
                ? new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)
                : new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                using (var db = new PRACTISEV1DB())
                {
                    foreach (var userClaim in claims)
                    {
                        await db.Administration.UserClaims
                        .Value(c => c.UserId, userId)
                        .Value(c => c.ClaimType, userClaim.ClaimType)
                        .Value(c => c.ClaimValue, userClaim.ClaimValue)
                        .InsertAsync();
                    }

                    tx.Complete();

                    if (transaction != null)
                    {
                        transaction.Complete();
                    }
                }
            }
        }
 internal static void Complete(Transaction transaction, Exception error)
 {
     try
     {
         if (error == null)
         {
             CommittableTransaction transaction2 = transaction as CommittableTransaction;
             if (transaction2 != null)
             {
                 transaction2.Commit();
             }
             else
             {
                 DependentTransaction transaction3 = transaction as DependentTransaction;
                 if (transaction3 != null)
                 {
                     transaction3.Complete();
                 }
             }
         }
         else
         {
             transaction.Rollback();
         }
     }
     catch (TransactionException exception)
     {
         DiagnosticUtility.ExceptionUtility.TraceHandledException(exception, TraceEventType.Error);
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(TransactionBehavior.CreateFault(System.ServiceModel.SR.GetString("SFxTransactionAsyncAborted"), "TransactionAborted", true));
     }
 }
コード例 #8
0
        /// <summary>
        ///     Delete a <see cref="UserClaim"/>.
        /// </summary>
        /// <param name="userClaim">The user claim.</param>
        /// <param name="transaction">The transaction.</param>
        /// <returns></returns>
        public async Task <bool> Delete(UserClaim userClaim, DependentTransaction transaction = null)
        {
            if (userClaim.UserId == Guid.Empty || string.IsNullOrEmpty(userClaim.ClaimType) || string.IsNullOrEmpty(userClaim.ClaimValue))
            {
                throw new InvalidOperationException("Invalid claim");
            }
            using (var tx = transaction != null
                ? new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)
                : new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                using (var db = new PRACTISEV1DB())
                {
                    var result = await db.Administration.UserClaims.Where(x =>
                                                                          x.UserId == userClaim.UserId && x.ClaimType == userClaim.ClaimType &&
                                                                          x.ClaimValue == userClaim.ClaimValue).DeleteAsync();

                    tx.Complete();

                    if (transaction != null)
                    {
                        transaction.Complete();
                    }

                    return(result == 1);
                }
            }
        }
コード例 #9
0
        private void OnBodyCompleted(NativeActivityContext context, System.Activities.ActivityInstance completedInstance)
        {
            TransactedReceiveData data = context.Properties.Find(TransactedReceiveData.TransactedReceiveDataExecutionPropertyName) as TransactedReceiveData;

            if (!this.isNested.Get(context))
            {
                CommittableTransaction initiatingTransaction = data.InitiatingTransaction as CommittableTransaction;
                if (initiatingTransaction != null)
                {
                    initiatingTransaction.BeginCommit(TransactionCommitAsyncCallback, initiatingTransaction);
                }
                else
                {
                    (data.InitiatingTransaction as DependentTransaction).Complete();
                }
            }
            else
            {
                DependentTransaction transaction3 = data.InitiatingTransaction as DependentTransaction;
                if (transaction3 != null)
                {
                    transaction3.Complete();
                }
            }
        }
コード例 #10
0
        private void AsyncTxAwareOnMessage(IMessage message)
        {
            awaitBatchProcessingStart.WaitOne();

            try
            {
                using (TransactionScope scoped = new TransactionScope(batchTxControl))
                    using (SqlConnection sqlConnection = new SqlConnection(createDbConnectionString))
                        using (SqlCommand sqlInsertCommand = new SqlCommand())
                        {
                            sqlConnection.Open();
                            sqlInsertCommand.Connection = sqlConnection;

                            ITextMessage textMessage = message as ITextMessage;
                            Assert.IsNotNull(message, "missing message");
                            sqlInsertCommand.CommandText =
                                string.Format("INSERT INTO {0} VALUES ({1})", testTable, Convert.ToInt32(textMessage.Text));
                            sqlInsertCommand.ExecuteNonQuery();
                            scoped.Complete();
                        }

                if (++batchSequence == MSG_COUNT)
                {
                    batchSequence = 0;
                    awaitBatchProcessingStart.Reset();
                    batchTxControl.Complete();
                }
            }
            catch (Exception e)
            {
                Tracer.Debug("TX;Error from TransactionScope: " + e.Message);
                Tracer.Debug(e.ToString());
            }
        }
コード例 #11
0
        /// <summary>
        ///     Update national Id.
        /// </summary>
        /// <param name="userId">The user Id.</param>
        /// <param name="nationalId">The national Id.</param>
        /// <param name="nationalIdVerificationDateUtc">The national Id verification date.</param>
        /// <param name="transaction">The transaction.</param>
        /// <returns></returns>
        public async Task <bool> UpdateNationalId(Guid userId, string nationalId, DateTime?nationalIdVerificationDateUtc, DependentTransaction transaction = null)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentException("Invalid user Id", nameof(userId));
            }
            if (string.IsNullOrEmpty(nationalId))
            {
                throw new ArgumentException("Invalid national Id", nameof(nationalId));
            }
            using (var tx = transaction != null
                ? new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)
                : new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                using (var db = new PRACTISEV1DB())
                {
                    var result = await db.Administration.Users.Where(x => x.Id == userId)
                                 .Set(u => u.NationalId, nationalId)
                                 .Set(u => u.NationalIdVerificationDateUtc, nationalIdVerificationDateUtc)
                                 .Set(u => u.ChangedOn, DateTime.UtcNow)
                                 .UpdateAsync();

                    tx.Complete();

                    if (transaction != null)
                    {
                        transaction.Complete();
                    }

                    return(result == 1);
                }
            }
        }
コード例 #12
0
        public void DependentTransactions()
        {
            Transactional <SimpleObject> tso = new Transactional <SimpleObject>(new SimpleObject());
            Guid id = Guid.NewGuid();

            using (TransactionScope scope = new TransactionScope())
            {
                tso.Value.TestInt    = 7;
                tso.Value.TestGuid   = id;
                tso.Value.TestString = "Testing";

                DependentTransaction dt = Transaction.Current.DependentClone(DependentCloneOption.RollbackIfNotComplete);

                Action assertAction = delegate()
                {
                    using (dt)
                        using (TransactionScope scopeTwo = new TransactionScope(dt))
                        {
                            Assert.AreEqual(7, tso.Value.TestInt);
                            Assert.AreEqual(id, tso.Value.TestGuid);
                            Assert.AreEqual("Testing", tso.Value.TestString);

                            scopeTwo.Complete();
                            dt.Complete();
                        }
                };

                IAsyncResult ar = assertAction.BeginInvoke(null, null);

                ar.AsyncWaitHandle.WaitOne();
                assertAction.EndInvoke(ar);

                scope.Complete();
            }
        }
コード例 #13
0
        public void Should_be_passable_to_another_action_queue()
        {
            var timer = Stopwatch.StartNew();

            Stopwatch inner = new Stopwatch();
            Stopwatch dep   = new Stopwatch();

            try
            {
                using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    inner.Start();

                    DependentTransaction dependentClone = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);

                    dependentClone.TransactionCompleted += (sender, args) =>
                    {
                        Trace.WriteLine("Completed");
                    };

                    //fiber.Add(() =>
                    {
                        dep.Start();
                        try
                        {
                            //ThreadUtil.Sleep(20.Milliseconds());

                            Trace.WriteLine("complieing");
                            dependentClone.Complete();
                            dep.Stop();
                            Trace.WriteLine("done");
                        }
                        catch (Exception ex)
                        {
                            dependentClone.Rollback(ex);
                        }
                        finally
                        {
                            dependentClone.Dispose();
                            Trace.WriteLine("clone disposed");
                        }
                    }                            //);

                    scope.Complete();
                    Trace.WriteLine("scope complete");
                }

                Trace.WriteLine("all done");
            }
            catch (Exception)
            {
            }

            inner.Stop();
            timer.Stop();

            Trace.WriteLine("Timer: " + (int)timer.ElapsedMilliseconds);
            Trace.WriteLine("Inner: " + (int)inner.ElapsedMilliseconds);
            Trace.WriteLine("Dep: " + (int)dep.ElapsedMilliseconds);
        }
コード例 #14
0
        /// <summary>
        ///     Create a <see cref="Administration.UserAddress"/>.
        /// </summary>
        /// <param name="userId">The user Id.</param>
        /// <param name="userAddress"></param>
        /// <param name="transaction">The transaction.</param>
        public async Task <Guid> Create(Guid userId, UserAddress userAddress, DependentTransaction transaction = null)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentException("Invalid user Id", nameof(userId));
            }
            if (userAddress.Id != Guid.Empty)
            {
                throw new InvalidOperationException("Id has to be empty guid");
            }
            if (userAddress.Address == null)
            {
                throw new InvalidOperationException("UserAddress is required");
            }
            using (var tx = transaction != null
                ? new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)
                : new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                using (var db = new PRACTISEV1DB())
                {
                    var id            = Guid.NewGuid();
                    var userAddressId = Guid.NewGuid();
                    var result        = await db.Utility.Addresses
                                        .Value(c => c.Id, id)
                                        .Value(c => c.Address1, userAddress.Address.Address1)
                                        .Value(c => c.Address2, userAddress.Address.Address2)
                                        .Value(c => c.AddressTypeId, userAddress.Address.AddressTypeId)
                                        .Value(c => c.City, userAddress.Address.City)
                                        .Value(c => c.County, userAddress.Address.County)
                                        .Value(c => c.CountryId, userAddress.Address.CountryId)
                                        .Value(u => u.State, userAddress.Address.State)
                                        .Value(u => u.Zip, userAddress.Address.Zip)
                                        .Value(u => u.CreatedOn, DateTime.UtcNow)
                                        .Value(u => u.ChangedOn, DateTime.UtcNow)
                                        .InsertAsync();

                    if (result == 1)
                    {
                        await db.Administration.UserAddresses
                        .Value(c => c.Id, userAddressId)
                        .Value(c => c.UserId, userId)
                        .Value(c => c.AddressId, id)
                        .Value(c => c.Preffered, userAddress.Preffered)
                        .InsertAsync();
                    }

                    tx.Complete();

                    if (transaction != null)
                    {
                        transaction.Complete();
                    }

                    return(userAddressId);
                }
            }
        }
コード例 #15
0
        /// <summary>
        ///     Create a <see cref="User"/>.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="transaction">The transaction.</param>
        /// <returns></returns>
        public async Task <Guid> Create(User user, DependentTransaction transaction = null)
        {
            if (user.Id != Guid.Empty)
            {
                throw new InvalidOperationException("Id has to be empty guid");
            }

            using (var tx = transaction != null
                ? new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)
                : new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                using (var db = new PRACTISEV1DB())
                {
                    var id     = Guid.NewGuid();
                    var result = await db.Administration.Users
                                 .Value(c => c.Id, id)
                                 .Value(c => c.UserName, user.UserName)
                                 .Value(c => c.Email, user.Email)
                                 .Value(c => c.PasswordHash, user.PasswordHash)
                                 .Value(c => c.SecurityStamp, Guid.NewGuid().ToString())
                                 .Value(c => c.PhoneNumber, user.PhoneNumber)
                                 .Value(c => c.MobileNumber, user.MobileNumber)
                                 .Value(c => c.NationalId, user.NationalId)
                                 .Value(c => c.EmailConfirmed, true)
                                 .Value(c => c.PhoneNumberConfirmed, true)
                                 .Value(c => c.MobileNumberConfirmed, true)
                                 .Value(c => c.LockoutEnabled, false)
                                 .Value(c => c.AccessFailedCount, 0)
                                 .Value(c => c.TwoFactorEnabled, false)
                                 .Value(c => c.CreatedOn, DateTime.UtcNow)
                                 .InsertAsync();

                    // Create user profile
                    if (user.Profile != null)
                    {
                        await Create(id, user.Profile, Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete));
                    }

                    // Create user claim
                    if (user.Claims != null && user.Claims.Any())
                    {
                        await Create(id, user.Claims, Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete));
                    }

                    tx.Complete();

                    if (transaction != null)
                    {
                        transaction.Complete();
                    }

                    return(result == 1 ? id : Guid.Empty);
                }
            }
        }
コード例 #16
0
        static void TxThread(object obj)
        {
            Thread.Sleep(3000);
            DependentTransaction tx = obj as DependentTransaction;

            Utilities.DisplayTransactionInformation("Dependent Transaction",
                                                    tx.TransactionInformation);
            tx.Complete();

            Utilities.DisplayTransactionInformation("Dependent TX Complete",
                                                    tx.TransactionInformation);
        }
コード例 #17
0
        static async Task UsingDependentTransactionAsync(DependentTransaction dtx)
        {
            dtx.TransactionCompleted += (sender, e) =>
                                        DisplayTransactionInformation("Depdendent TX completed", e.Transaction.TransactionInformation);

            DisplayTransactionInformation("Dependent Tx", dtx.TransactionInformation);

            await Task.Delay(2000);

            dtx.Complete();
            DisplayTransactionInformation("Dependent Tx send complete", dtx.TransactionInformation);
        }
コード例 #18
0
        /// <summary>
        ///     Update a <see cref="Administration.UserAddress"/>.
        /// </summary>
        /// <param name="userAddress">The user address.</param>
        /// <param name="transaction">The transaction.</param>
        /// <returns></returns>
        public async Task <bool> Update(UserAddress userAddress, DependentTransaction transaction = null)
        {
            if (userAddress.Id == Guid.Empty)
            {
                throw new InvalidOperationException("Invalid Id");
            }
            if (userAddress.Address == null)
            {
                throw new ArgumentException("Invalid address");
            }
            if (userAddress.Address.Id == Guid.Empty)
            {
                throw new ArgumentException("Invalid address Id");
            }
            using (var tx = transaction != null
                ? new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)
                : new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                using (var db = new PRACTISEV1DB())
                {
                    var result = await db.Administration.UserAddresses.Where(x => x.Id == userAddress.Id)
                                 .Set(u => u.Preffered, userAddress.Preffered)
                                 .UpdateAsync();

                    // Update the address
                    await db.Utility.Addresses.Where(x => x.Id == userAddress.Address.Id)
                    .Set(u => u.Address1, userAddress.Address.Address1)
                    .Set(u => u.Address2, userAddress.Address.Address2)
                    .Set(u => u.AddressTypeId, userAddress.Address.AddressTypeId)
                    .Set(u => u.City, userAddress.Address.City)
                    .Set(u => u.County, userAddress.Address.County)
                    .Set(u => u.CountryId, userAddress.Address.CountryId)
                    .Set(u => u.State, userAddress.Address.State)
                    .Set(u => u.Zip, userAddress.Address.Zip)
                    .Set(u => u.ChangedOn, DateTime.UtcNow)
                    .UpdateAsync();

                    tx.Complete();

                    if (transaction != null)
                    {
                        transaction.Complete();
                    }

                    return(result == 1);
                }
            }
        }
コード例 #19
0
ファイル: SqlDBHelper.cs プロジェクト: zhengbo1994/SPText
        public static void CommitThread(object co)
        {
            DependentTransaction commit = co as DependentTransaction;
            SqlConnection        conn2  = new SqlConnection("data source=.;Initial Catalog=DataMedicine;Integrated Security=SSPI");

            conn2.Open();
            conn2.EnlistTransaction(commit as DependentTransaction);
            DisplayTransactioninfo.Display(commit);
            SqlCommand command = new SqlCommand("insert into test values(111)", conn2);

            try
            {
                command.ExecuteNonQuery();
                commit.Complete();
            }
            catch (Exception err) { Console.WriteLine(err); commit.Rollback(); }
        }
コード例 #20
0
        virtual internal protected void CommitWorkBatch(CommitWorkBatchCallback commitWorkBatchCallback)
        {
            Transaction tx = null;

            if (null == Transaction.Current)
            {
                tx = new CommittableTransaction();
            }
            else
            {
                tx = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
            }

            try
            {
                using (TransactionScope ts = new TransactionScope(tx))
                {
                    commitWorkBatchCallback();
                    ts.Complete();
                }

                CommittableTransaction committableTransaction = tx as CommittableTransaction;
                if (committableTransaction != null)
                {
                    committableTransaction.Commit();
                }

                DependentTransaction dependentTransaction = tx as DependentTransaction;
                if (dependentTransaction != null)
                {
                    dependentTransaction.Complete();
                }
            }
            catch (Exception e)
            {
                tx.Rollback(e);
                throw;
            }
            finally
            {
                if (tx != null)
                {
                    tx.Dispose();
                }
            }
        }
コード例 #21
0
        private void InsertHistory(DependentTransaction dt,
                                   SalesOrderDetail salesDetail)
        {
            try
            {
                using (AdventureWorksDataContext dc =
                           new AdventureWorksDataContext())
                {
                    //use the dependent transaction if there is one,
                    //or suppress a transaction
                    using (TransactionScope scope = (dt != null ?
                                                     new TransactionScope(dt) :
                                                     new TransactionScope(TransactionScopeOption.Suppress)))
                    {
                        var historyRow = new TransactionHistory();
                        historyRow.ProductID        = salesDetail.ProductID;
                        historyRow.ModifiedDate     = DateTime.Now;
                        historyRow.Quantity         = salesDetail.OrderQty;
                        historyRow.TransactionDate  = salesDetail.ModifiedDate;
                        historyRow.TransactionType  = 'S';
                        historyRow.ReferenceOrderID = salesDetail.SalesOrderID;
                        historyRow.ReferenceOrderLineID
                            = salesDetail.SalesOrderDetailID;

                        dc.TransactionHistories.InsertOnSubmit(historyRow);
                        dc.SubmitChanges();
                        Console.WriteLine(
                            "Product {0}: Added history for Qty of {1} ",
                            salesDetail.ProductID, salesDetail.OrderQty);

                        scope.Complete();
                    }
                }
            }
            finally
            {
                //the DependentTransaction must be completed otherwise
                //the ambient transaction will block on complete
                if (dt != null)
                {
                    dt.Complete();
                    dt.Dispose();
                }
            }
        }
コード例 #22
0
 public void ThreadMethod(object transaction) 
 { 
     DependentTransaction dependentTransaction = transaction as DependentTransaction;
     Debug.Assert(dependentTransaction != null);
     try
     {
         using(TransactionScope ts = new TransactionScope(dependentTransaction))
         {
             /* Perform transactional work here */ 
             ts.Complete();
         }
     }
     finally
     {
         dependentTransaction.Complete(); 
         dependentTransaction.Dispose(); 
     }
 }
コード例 #23
0
        private void UpdateInventory(DependentTransaction dt,
                                     SalesOrderDetail salesDetail)
        {
            try
            {
                using (AdventureWorksDataContext dc =
                           new AdventureWorksDataContext())
                {
                    //use the dependent transaction if there is one,
                    //or suppress the creation of a new transaction
                    using (TransactionScope scope = (dt != null ?
                                                     new TransactionScope(dt) :
                                                     new TransactionScope(TransactionScopeOption.Suppress)))
                    {
                        var inventoryRow =
                            (from pi in dc.ProductInventories
                             where pi.ProductID == salesDetail.ProductID &&
                             pi.LocationID == 7       //finished goods storage
                             select pi).SingleOrDefault();
                        if (inventoryRow != null)
                        {
                            inventoryRow.Quantity    -= salesDetail.OrderQty;
                            inventoryRow.ModifiedDate = DateTime.Now;
                            Console.WriteLine(
                                "Product {0}: Reduced by {1}",
                                inventoryRow.ProductID, salesDetail.OrderQty);
                            dc.SubmitChanges();
                        }

                        scope.Complete();
                    }
                }
            }
            finally
            {
                //the DependentTransaction must be completed otherwise
                //the ambient transaction will block on complete
                if (dt != null)
                {
                    dt.Complete();
                    dt.Dispose();
                }
            }
        }
        protected internal virtual void CommitWorkBatch(CommitWorkBatchCallback commitWorkBatchCallback)
        {
            Transaction transactionToUse = null;

            if (null == Transaction.Current)
            {
                transactionToUse = new CommittableTransaction();
            }
            else
            {
                transactionToUse = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
            }
            try
            {
                using (TransactionScope scope = new TransactionScope(transactionToUse))
                {
                    commitWorkBatchCallback();
                    scope.Complete();
                }
                CommittableTransaction transaction2 = transactionToUse as CommittableTransaction;
                if (transaction2 != null)
                {
                    transaction2.Commit();
                }
                DependentTransaction transaction3 = transactionToUse as DependentTransaction;
                if (transaction3 != null)
                {
                    transaction3.Complete();
                }
            }
            catch (Exception exception)
            {
                transactionToUse.Rollback(exception);
                throw;
            }
            finally
            {
                if (transactionToUse != null)
                {
                    transactionToUse.Dispose();
                }
            }
        }
コード例 #25
0
        public static void SendUsingDependentTransaction(Job job, long index, IBus bus, DependentTransaction dependentTransaction)
        {
            try
            {
                using (TransactionScope ts = new TransactionScope(dependentTransaction))
                {
                    // if (index == 15)
                    //    throw new Exception("Blah Blah");

                    bus.Send(job);

                    ts.Complete();
                }
            }
            finally
            {
                dependentTransaction.Complete();
                dependentTransaction.Dispose();
            }
        }
コード例 #26
0
        private static void WorkerThread(object transaction)
        {
            //Create a DependentTransaction from the object passed to the WorkerThread
            DependentTransaction dTx = (DependentTransaction)transaction;

            //Sleep for 1 second to force the worker thread to delay
            Thread.Sleep(1000);

            //Pass the DependentTransaction to the scope, so that work done in the scope becomes part of the transaction passed to the worker thread
            using (TransactionScope ts = new TransactionScope(dTx))
            {
                //Perform transactional work here.

                //Call complete on the transaction scope
                ts.Complete();
            }

            //Call complete on the dependent transaction
            dTx.Complete();
        }
コード例 #27
0
        /// <summary>
        ///     Create a <see cref="UserProfile"/>.
        /// </summary>
        /// <param name="userId">The user Id.</param>
        /// <param name="userProfile">The user profile.</param>
        /// <param name="transaction">The transaction.</param>
        /// <returns></returns>
        public async Task <Guid> Create(Guid userId, UserProfile userProfile, DependentTransaction transaction = null)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentException("Invalid user Id", nameof(userId));
            }

            using (var tx = transaction != null
                ? new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)
                : new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                using (var db = new PRACTISEV1DB())
                {
                    await db.Administration.UserProfiles
                    .Value(c => c.UserId, userId)
                    .Value(c => c.LastName, userProfile.LastName)
                    .Value(c => c.FirstName, userProfile.FirstName)
                    .Value(c => c.UserTypeId, userProfile.UserTypeId)
                    .Value(c => c.GenderId, userProfile.GenderId)
                    .Value(c => c.CountryId, userProfile.CountryId)
                    .Value(u => u.Title, userProfile.Title)
                    .Value(u => u.Suffix, userProfile.Suffix)
                    .Value(u => u.Prefix, userProfile.Prefix)
                    .Value(u => u.PrefferedName, userProfile.PrefferedName)
                    .Value(u => u.Dob, userProfile.Dob)
                    .Value(u => u.Organization, userProfile.Organization)
                    .Value(u => u.Department, userProfile.Department)
                    .Value(c => c.PictureUrl, userProfile.PictureUrl)
                    .InsertAsync();

                    tx.Complete();

                    if (transaction != null)
                    {
                        transaction.Complete();
                    }

                    return(userId);
                }
            }
        }
コード例 #28
0
        /// <summary>
        ///     Update a <see cref="UserProfile"/>.
        /// </summary>
        /// <param name="userProfile">The user profile.</param>
        /// <param name="transaction">The transaction.</param>
        /// <returns></returns>
        public async Task <bool> Update(UserProfile userProfile, DependentTransaction transaction = null)
        {
            if (userProfile.UserId == Guid.Empty)
            {
                throw new InvalidOperationException("Invalid user Id");
            }
            using (var tx = transaction != null
                ? new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)
                : new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                using (var db = new PRACTISEV1DB())
                {
                    var result = await db.Administration.UserProfiles.Where(x => x.UserId == userProfile.UserId)
                                 .Set(u => u.LastName, userProfile.LastName)
                                 .Set(u => u.FirstName, userProfile.FirstName)
                                 .Set(u => u.UserTypeId, userProfile.UserTypeId)
                                 .Set(u => u.GenderId, userProfile.GenderId)
                                 .Set(u => u.CountryId, userProfile.CountryId)
                                 .Set(u => u.Title, userProfile.Title)
                                 .Set(u => u.Suffix, userProfile.Suffix)
                                 .Set(u => u.Prefix, userProfile.Prefix)
                                 .Set(u => u.PrefferedName, userProfile.PrefferedName)
                                 .Set(u => u.Dob, userProfile.Dob)
                                 .Set(u => u.Organization, userProfile.Organization)
                                 .Set(u => u.Department, userProfile.Department)
                                 .Set(u => u.PictureUrl, userProfile.PictureUrl)
                                 .UpdateAsync();

                    tx.Complete();

                    if (transaction != null)
                    {
                        transaction.Complete();
                    }

                    return(result == 1);
                }
            }
        }
コード例 #29
0
ファイル: Program.cs プロジェクト: liuhonglei/WCFStudy
        private static void InvokeInTransaction(Action action)
        {
            Transaction            originalTransaction  = Transaction.Current;
            CommittableTransaction transaction          = null;
            DependentTransaction   dependentTransaction = null;

            if (null == Transaction.Current)
            {
                transaction         = new CommittableTransaction();
                Transaction.Current = transaction;
            }
            else
            {
                dependentTransaction = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
                Transaction.Current  = dependentTransaction;
            }
            try
            {
                action();
                if (null != transaction)
                {
                    transaction.Commit();
                }
                if (null != dependentTransaction)
                {
                    dependentTransaction.Complete();
                }
            }
            catch (Exception ex)
            {
                Transaction.Current.Rollback(ex);
                throw;
            }
            finally {
                Transaction transaction2 = Transaction.Current;
                Transaction.Current = originalTransaction;
                transaction2.Dispose();
            }
        }
コード例 #30
0
        /// <summary>
        ///     Update a <see cref="User"/>.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="transaction">Thr transaction.</param>
        /// <returns></returns>
        public async Task <bool> Update(User user, DependentTransaction transaction = null)
        {
            if (user.Id == Guid.Empty)
            {
                throw new InvalidOperationException("Invalid user Id");
            }
            using (var tx = transaction != null
                ? new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled)
                : new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                using (var db = new PRACTISEV1DB())
                {
                    var result = await db.Administration.Users.Where(x => x.Id == user.Id)
                                 .Set(u => u.Email, user.Email)
                                 .Set(u => u.PhoneNumber, user.PhoneNumber)
                                 .Set(u => u.MobileNumber, user.MobileNumber)
                                 .Set(u => u.ChangedOn, DateTime.UtcNow)
                                 .UpdateAsync();

                    // Update user profile
                    if (user.Profile != null && user.Profile.UserId != Guid.Empty)
                    {
                        await Update(user.Profile, Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete));
                    }

                    tx.Complete();

                    if (transaction != null)
                    {
                        transaction.Complete();
                    }

                    return(result == 1);
                }
            }
        }