コード例 #1
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);
                }
            }
        }
コード例 #2
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();
                    }
                }
            }
        }
コード例 #3
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();
            }
        }
コード例 #4
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);
        }
コード例 #5
0
ファイル: ParallelActivity.cs プロジェクト: safrrhmn/Amnesia
            public ActivityThread(SessionTracker tracker, Amnesia.SessionTracker.ActivityInfo activity, DependentTransaction transaction)
            {
                this.tracker     = tracker;
                this.transaction = transaction;

                tracker.ParallelDependentActivityStarted(activity);
            }
コード例 #6
0
        /// <summary>
        ///     Update password.
        /// </summary>
        /// <param name="userId">The user Id.</param>
        /// <param name="passwordHash">The password hash.</param>
        /// <param name="transaction">The transaction.</param>
        public async Task <bool> UpdatePassword(Guid userId, string passwordHash, DependentTransaction transaction = null)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentException("Invalid user Id", nameof(userId));
            }
            if (string.IsNullOrEmpty(passwordHash))
            {
                throw new ArgumentException("Invalid password hash", nameof(passwordHash));
            }
            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.PasswordHash, passwordHash)
                                 .Set(u => u.ChangedOn, DateTime.UtcNow)
                                 .UpdateAsync();

                    tx.Complete();

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

                    return(result == 1);
                }
            }
        }
コード例 #7
0
 internal void CreateDependentClone()
 {
     if ((this.dependentClone == null) && (this.Clone != null))
     {
         this.dependentClone = this.Clone.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
     }
 }
 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));
     }
 }
コード例 #9
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();
                }
            }
        }
コード例 #10
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;
         }
     });
 }
コード例 #11
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));
     }
 }
コード例 #12
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();
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// Initializes a new instance of the <Typ>LearningStoreTransactionScope</Typ> class.  LearningStore
        /// jobs executed within the scope use the specified transaction.
        /// </summary>
        /// <param name="transaction">Transaction used by LearningStore operations within the scope.</param>
        /// <exception cref="ArgumentNullException"><paramref name="transaction"/> is a null reference.</exception>
        /// <exception cref="InvalidOperationException">A transaction already exists in this scope (i.e.,
        ///     this scope is nested inside another).</exception>
        /// <remarks>
        /// See <Typ>LearningStoreTransactionScope</Typ> for more information.
        /// </remarks>
        public LearningStoreTransactionScope(Transaction transaction)
        {
            // Check parameters
            if (transaction == null)
            {
                throw new ArgumentNullException("transaction");
            }

            // Fail if there's already a scope
            if (s_currentScope != null)
            {
                throw new InvalidOperationException(LearningStoreStrings.TransactionAlreadyExists);
            }

            m_scopeThread = Thread.CurrentThread;

            // Use the transaction passed to us
            m_dependentTransaction = transaction.DependentClone(DependentCloneOption.RollbackIfNotComplete);
            m_transaction          = transaction;
            m_createdConnections   = new Dictionary <string, SqlConnection>();
            m_connections          = m_createdConnections;

            // Enter the scope
            s_currentScope = this;
        }
コード例 #14
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));
        }
コード例 #15
0
        public void A_transaction_should_be_dependent_upon_the_worker_thread_committing()
        {
            Thread thx = new Thread(ThreadProc);

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

            using (TransactionScope ts = new TransactionScope())
            {
                DependentTransaction dts = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);

                Debug.WriteLine(string.Format("{0} Starting thread", DateTime.Now));

                thx.Start(dts);

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

                ts.Complete();

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

            Debug.WriteLine(string.Format("{0} Verifying transaction not yet complete", DateTime.Now));


            Assert.That(_txCompleted.WaitOne(0, false), Is.True, "It seems that the original thread blocks until the dependent transaction is completed.");
        }
コード例 #16
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();
                }
            }
        }
コード例 #17
0
        /// <summary>
        /// 开始下一步操作
        /// </summary>
        /// <typeparam name="S">IEnlistmentNotification接口实现</typeparam>
        /// <param name="level">IsolationLevel事务的隔离级别(对全局事务处理设置)</param>
        /// <param name="source">下一步操作的自定义数据管理器</param>
        public void Next <S>(IsolationLevel level, S source)
            where S : class, IEnlistmentNotification, new()
        {
            Transaction tran = _tranStack.Peek();//获取事务栈的顶端事务

            if (tran == null)
            {
                tran = Transaction.Current;//主事务
            }
            DependentTransaction depentran = tran.DependentClone(DependentCloneOption.BlockCommitUntilComplete);

            //将本次事务处理的资源管理器压入资源栈中
            depentran.EnlistVolatile(source, EnlistmentOptions.None);
            _tranStack.Push(depentran);
            _resourceStack.Push(source);
            //切换环境事务场景
            Transaction.Current = depentran;
            if (NextEvent != null)
            {
                if (NextEvent.GetInvocationList().Length > 0)
                {
                    NextEvent(Transaction.Current);
                }
            }
        }
コード例 #18
0
 void CompleteClonedTransaction()
 {
     if (this.clonedTransaction != null)
     {
         this.clonedTransaction.Complete();
         this.clonedTransaction = null;
     }
 }
コード例 #19
0
            public AssociateKeysAsyncResult(PersistenceContext persistenceContext, ICollection <InstanceKey> associatedKeys, TimeSpan timeout, bool applicationKeys, AsyncCallback callback, object state) : base(callback, state)
            {
                this.persistenceContext = persistenceContext;
                this.applicationKeys    = applicationKeys;
                this.keysToAssociate    = associatedKeys;
                this.timeoutHelper      = new TimeoutHelper(timeout);
                base.OnCompleting       = new Action <AsyncResult, Exception>(this.OnFinishOperation);
                bool flag = false;

                try
                {
                    this.persistenceContext.StartOperation();
                    this.persistenceContext.ThrowIfCompleted();
                    this.persistenceContext.ThrowIfNotVisible();
                    Transaction current = Transaction.Current;
                    if (current != null)
                    {
                        this.transaction = current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
                    }
                    IAsyncResult result = persistenceContext.BeginEnlist(this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleEndEnlist), this);
                    if (base.SyncContinue(result))
                    {
                        base.Complete(true);
                    }
                    flag = true;
                }
                catch (InstancePersistenceException)
                {
                    this.persistenceContext.Fault();
                    throw;
                }
                catch (OperationCanceledException exception)
                {
                    throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new CommunicationObjectAbortedException(System.ServiceModel.Activities.SR.HandleFreedInDirectory, exception));
                }
                catch (TimeoutException)
                {
                    this.persistenceContext.Fault();
                    throw;
                }
                finally
                {
                    if (!flag)
                    {
                        try
                        {
                            if (this.transaction != null)
                            {
                                this.transaction.Complete();
                            }
                        }
                        finally
                        {
                            this.persistenceContext.FinishOperation();
                        }
                    }
                }
            }
コード例 #20
0
        internal TransactionWaitAsyncResult(Transaction transaction, PersistenceContext persistenceContext, TimeSpan timeout, AsyncCallback callback, object state)
            : base(callback, state)
        {
            bool completeSelf = false;
            TransactionException exception = null;

            this.PersistenceContext = persistenceContext;
            this.thisLock           = new object();

            if (null != transaction)
            {
                // We want an "blocking" dependent transaction because we want to ensure the transaction
                // does not commit successfully while we are still waiting in the queue for the PC transaction
                // lock.
                this.dependentTransaction = transaction.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
            }
            else
            {
                this.dependentTransaction = null;
            }

            // Put a lock around this and Complete() in case the transaction we are queueing up behind
            // finishes and we end up calling Complete() before we actually finish constructing this
            // object by creating the DependentClone and setting up the IOThreadTimer.
            lock (ThisLock)
            {
                if (persistenceContext.QueueForTransactionLock(transaction, this))
                {
                    // If we were given a transaction in our constructor, we need to
                    // create a volatile enlistment on it and complete the
                    // dependent clone that we created. This will allow the transaction to commit
                    // successfully when the time comes.
                    if (null != transaction)
                    {
                        // We are not going async, so we need to complete our dependent clone now.
                        this.dependentTransaction.Complete();

                        exception = this.CreateVolatileEnlistment(transaction);
                    }
                    completeSelf = true;
                }
                else
                {
                    // If the timeout value is not TimeSpan.MaxValue, start a timer.
                    if (timeout != TimeSpan.MaxValue)
                    {
                        this.timer = new IOThreadTimer(TimeoutCallbackAction, this, true);
                        this.timer.Set(timeout);
                    }
                }
            }

            // We didn't want to call Complete while holding the lock.
            if (completeSelf)
            {
                base.Complete(true, exception);
            }
        }
コード例 #21
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);
                }
            }
        }
コード例 #22
0
 public void TrackStoreUnlock(DependentTransaction dependentTransaction)
 {
     this.BoundToLock   = false;
     this.IsHandleFreed = true;
     if (dependentTransaction != null)
     {
         dependentTransaction.TransactionCompleted += new TransactionCompletedEventHandler(this.TransactedUnlockCompleted);
     }
 }
コード例 #23
0
        /// <summary>
        /// Persist the provided <paramref name="eventData"/> into each SQL Server in <see cref="WritableConnectionStrings"/>.
        /// A single <see cref="TransactionScope"/> wraps all SQL servers, so all must complete successfully, or they will ALL roll back.
        /// </summary>
        /// <param name="eventData">The <see cref="EventData"/> to persist.</param>
        protected override void PersistEvent(EventData eventData)
        {
            try
            {
                using (TransactionScope scope = new TransactionScope())
                {
                    IList <Task> persistTasks = new List <Task>();
                    foreach (string connectionString in WritableConnectionStrings)
                    {
                        // Do not remove this variable copying or the parallel task stuff will bork.
                        var safeConnectionString            = connectionString;
                        DependentTransaction subTransaction = Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
                        Task task = Task.Factory.StartNewSafely
                                    (
                            (subTransactionObject) =>
                        {
                            var subTrx = (DependentTransaction)subTransactionObject;
                            //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(subTrx))
                            {
                                using (SqlEventStoreDataContext dbDataContext = new SqlEventStoreDataContext(safeConnectionString))
                                    Add(dbDataContext, eventData);

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

                            //Call complete on the dependent transaction
                            subTrx.Complete();
                        },
                            subTransaction
                                    );
                        persistTasks.Add(task);
                    }

                    bool anyFailed = Task.Factory.ContinueWhenAll(persistTasks.ToArray(), tasks =>
                    {
                        return(tasks.Any(task => task.IsFaulted));
                    }).Result;
                    if (anyFailed)
                    {
                        throw new AggregateException("Persisting data to the SQL event store failed. Check the logs for more details.");
                    }
                    scope.Complete();
                }
            }
            catch (TransactionException exception)
            {
                Logger.LogError("There was an issue with the SQL transaction persisting data to the SQL event store.", exception: exception);
                throw;
            }
            catch (Exception exception)
            {
                Logger.LogError("There was an issue persisting data to the SQL event store.", exception: exception);
                throw;
            }
        }
コード例 #24
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);
                }
            }
        }
コード例 #25
0
        public SqlCommandAsyncResult(SqlCommand sqlCommand, string connectionString, DependentTransaction dependentTransaction, TimeSpan timeout, int retryCount, int maximumRetries, AsyncCallback callback, object state) : base(callback, state)
        {
            long num = Math.Min(timeout.Ticks, MaximumOpenTimeout.Ticks);

            this.sqlCommand           = sqlCommand;
            this.connectionString     = connectionString;
            this.dependentTransaction = dependentTransaction;
            this.timeoutHelper        = new TimeoutHelper(TimeSpan.FromTicks(num));
            this.retryCount           = retryCount;
            this.maximumRetries       = maximumRetries;
        }
コード例 #26
0
        public FileTransaction(string name, DependentTransaction inner, uint stackDepth, ITransactionOptions creationOptions,
                               Action onDispose)
        {
            Contract.Requires(inner != null);
            Contract.Requires(creationOptions != null);

            _Inner = new Transaction(inner, stackDepth, creationOptions, onDispose, NullLogger.Instance);

            _Name = name;
            InnerBegin();
        }
コード例 #27
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);
        }
コード例 #28
0
 public PersistenceScope(bool saveStateInOperationTransaction, DependentTransaction clonedTransaction)
 {
     if (!saveStateInOperationTransaction)
     {
         this.scope = new TransactionScope(TransactionScopeOption.Suppress);
     }
     else if (clonedTransaction != null)
     {
         this.clonedTransaction = clonedTransaction;
         this.scope             = new TransactionScope(clonedTransaction);
     }
 }
コード例 #29
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);
        }
コード例 #30
0
 public void TrackStoreLock(Guid instanceId, long instanceVersion, DependentTransaction dependentTransaction)
 {
     this.BoundToLock     = true;
     this.InstanceId      = instanceId;
     this.InstanceVersion = instanceVersion;
     if (dependentTransaction != null)
     {
         dependentTransaction.TransactionCompleted += new TransactionCompletedEventHandler(this.TransactionCompleted);
     }
     else
     {
         this.IsSafeToUnlock = true;
     }
 }
コード例 #31
0
        private static void TestCase_PSPENonMsdtcWithClones(
            bool commit,
            bool promote,
            TransactionStatus spcResponse,
            int abortingBeforePSPE = 0,
            int abortingAfterPSPE = 0,
            int blockingBeforePSPE = 0,
            int blockingAfterPSPE = 0,
            int abortingAfterPromote = 0,
            int blockingAfterPromote = 0)
        {
            string testCaseDescription = string.Format(
                "TestCase_PSPENonMsdtcWithClones commit={0}; promote={1}; spcResponse= {2}; abortingBeforePSPE={3}; abortingAfterPSPE={4}; blockingBeforePSPE={5}; blockingAfterPSPE={6}; abortingAfterPromote={7}; blockingAfterPromote={8}",
                commit,
                promote,
                spcResponse,
                abortingBeforePSPE,
                abortingAfterPSPE,
                blockingBeforePSPE,
                blockingAfterPSPE,
                abortingAfterPromote,
                blockingAfterPromote);

            Trace("**** " + testCaseDescription + " ****");

            // It doesn't make sense to have "AfterPromote" enlistments if we aren't going to promote the transaction.
            if (!promote)
            {
                if ((abortingAfterPromote > 0) || (blockingAfterPromote > 0))
                {
                    Trace("Not promoting - Resetting abortingAfterPromote and blockingAfterPromote to 0.");
                    abortingAfterPromote = 0;
                    blockingAfterPromote = 0;
                }
            }

            AutoResetEvent completedEvent = new AutoResetEvent(false);

            IPromotableSinglePhaseNotification enlistment = null;

            int numClones = abortingBeforePSPE + abortingAfterPSPE + blockingBeforePSPE + blockingAfterPSPE + abortingAfterPromote + blockingAfterPromote;


            DependentTransaction[] clones = new DependentTransaction[numClones];

            try
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    if (abortingBeforePSPE > 0)
                    {
                        for (int i = 0; i < abortingBeforePSPE; i++)
                        {
                            clones[i] = CreateDependentClone(/*blocking=*/false);
                        }
                    }

                    if (blockingBeforePSPE > 0)
                    {
                        for (int i = 0; i < blockingBeforePSPE; i++)
                        {
                            clones[abortingBeforePSPE + i] = CreateDependentClone(/*blocking=*/true);
                        }
                    }

                    enlistment = CreatePSPEEnlistment(NonMsdtcPromoterTests.PromoterType1,
                        NonMsdtcPromoterTests.PromotedToken1,
                        completedEvent,
                        /*nonMSDTC = */ true,
                        /*tx = */ null,
                        spcResponse,
                        /*expectRejection=*/ false
                        );

                    if (abortingAfterPSPE > 0)
                    {
                        for (int i = 0; i < abortingAfterPSPE; i++)
                        {
                            clones[abortingBeforePSPE + blockingBeforePSPE + i] = CreateDependentClone(/*blocking=*/false);
                        }
                    }

                    if (blockingAfterPSPE > 0)
                    {
                        for (int i = 0; i < blockingAfterPSPE; i++)
                        {
                            clones[abortingBeforePSPE + blockingBeforePSPE + abortingAfterPSPE + i] = CreateDependentClone(/*blocking=*/true);
                        }
                    }

                    if (promote)
                    {
                        Promote(testCaseDescription, NonMsdtcPromoterTests.PromotedToken1);

                        if (abortingAfterPromote > 0)
                        {
                            for (int i = 0; i < abortingAfterPromote; i++)
                            {
                                clones[abortingBeforePSPE + blockingBeforePSPE + abortingAfterPSPE + blockingAfterPSPE + i] = CreateDependentClone(/*blocking=*/false);
                            }
                        }

                        if (blockingAfterPromote > 0)
                        {
                            for (int i = 0; i < blockingAfterPromote; i++)
                            {
                                clones[abortingBeforePSPE + blockingBeforePSPE + abortingAfterPSPE + blockingAfterPSPE + abortingAfterPromote + i] = CreateDependentClone(/*blocking=*/true);
                            }
                        }
                    }

                    // Complete all the clones
                    for (int i = 0; i < numClones; i++)
                    {
                        clones[i].Complete();
                    }

                    if (commit)
                    {
                        ts.Complete();
                    }
                }
            }
            catch (Exception ex)
            {
                TransactionAbortedException abortedEx = ex as TransactionAbortedException;
                if ((abortedEx != null) && (spcResponse != TransactionStatus.Aborted))
                {
                    TestFailed(testCaseDescription, "The transaction aborted unexpectedly");
                    return;
                }

                TransactionInDoubtException indoubtEx = ex as TransactionInDoubtException;
                if ((indoubtEx != null) && (spcResponse != TransactionStatus.InDoubt))
                {
                    TestFailed(testCaseDescription, "The transaction was indoubt unexpectedly");
                    return;
                }

                if (spcResponse == TransactionStatus.Committed)
                {
                    Trace(string.Format("Caught unexpected exception {0}:{1}", ex.GetType().ToString(), ex.ToString()));
                    return;
                }
            }

            TestPassed();
        }