コード例 #1
0
        protected override int OnInsert(DataDictionary <Folder> data, string scope, object state)
        {
            using (var transaction = new Transactions.Transaction())
            {
                //调用基类同名方法
                var count = base.OnInsert(data, scope, state);

                if (count < 1)
                {
                    return(count);
                }

                //获取新增的文件夹用户集,并尝试插入该用户集
                data.TryGet(p => p.Users, (key, users) =>
                {
                    if (users == null)
                    {
                        return;
                    }

                    this.DataAccess.InsertMany(users);
                });

                //提交事务
                transaction.Commit();

                //返回主表插入的记录数
                return(count);
            }
        }
コード例 #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="tran"></param>
        /// <param name="tableName"></param>
        public TextSearchTable(Transactions.Transaction tran, string tableName)
        {
            if (tran == null || String.IsNullOrEmpty(tableName))
            {
                throw new Exception("DBreeze.TextSearch.TextSearchTable constructor: transaction or tableName is not supplied");
            }

            this._tran      = tran;
            this._tableName = tableName;
        }
コード例 #3
0
ファイル: DGraph.cs プロジェクト: zendbit/DBreeze
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="tran"></param>
        /// <param name="tableName"></param>
        public DGraph(Transactions.Transaction tran, string tableName)
        {
            if (tran == null)
            {
                throw new Exception("DGraph. Transaction is not instantiated");
            }
            if (String.IsNullOrEmpty(tableName))
            {
                throw new Exception("DGraph. tableName is not supplied");
            }

            this.tran      = tran;
            this.tableName = tableName;
        }
コード例 #4
0
ファイル: DataSession.cs プロジェクト: Zongsoft/Framework
        public DataSession(IDataSource source, Zongsoft.Transactions.Transaction ambient = null)
        {
            _source  = source ?? throw new ArgumentNullException(nameof(source));
            _ambient = ambient;

            _semaphore = new AutoResetEvent(true);
            _commands  = new ConcurrentBag <IDbCommand>();

            if (_ambient != null)
            {
                _ambient.Enlist(new Enlistment(this));
            }

            this.ShareConnectionSupported = source.Features.Support(Feature.MultipleActiveResultSets);
        }
コード例 #5
0
        // Public Methods (1) 

        public override void Execute()
        {
            Transactions.Transaction t;
            Transactions.Processes.AuthenticateUser process;

            process = new Transactions.Processes.AuthenticateUser(_db, _sessionMgr, _username, _password, _request.Database.Server.Timeout,
                                                                  _request.Database.Server.Timeout, _request.Database.Server.BufferSize, _request.Database.Server.BufferSize);
            t = new Transactions.Transaction(process);

            AttachSubscriber(process, _request.OnActionChanged);
            AttachSubscriber(process, _request.OnAuthorizationDenied);
            AttachSubscriber(process, _request.OnComplete);
            AttachSubscriber(process, _request.OnError);
            AttachSubscriber(process, _request.OnProgress);
            AttachSubscriber(process, _request.OnTimeout);

            t.Execute();
        }
コード例 #6
0
        public override void Execute()
        {
            Transactions.Transaction t;
            Transactions.Processes.DetermineIfInstalled process;

            process = new Transactions.Processes.DetermineIfInstalled(_request.Database, _request.Database.Server.Timeout,
                                                                      _request.Database.Server.Timeout, _request.Database.Server.BufferSize, _request.Database.Server.BufferSize);
            t = new Transactions.Transaction(process);

            AttachSubscriber(process, _request.OnActionChanged);
            AttachSubscriber(process, _request.OnAuthorizationDenied);
            AttachSubscriber(process, _request.OnComplete);
            AttachSubscriber(process, _request.OnError);
            AttachSubscriber(process, _request.OnProgress);
            AttachSubscriber(process, _request.OnTimeout);

            t.Execute();
        }
コード例 #7
0
        public override void Execute()
        {
            Transactions.Transaction           t;
            Transactions.Processes.CreateGroup process;

            process = new Transactions.Processes.CreateGroup(_request.Database, _group, _request.RequestingPartyType, _request.Session, _request.Database.Server.Timeout,
                                                             _request.Database.Server.Timeout, _request.Database.Server.BufferSize, _request.Database.Server.BufferSize);
            t = new Transactions.Transaction(process);

            AttachSubscriber(process, _request.OnActionChanged);
            AttachSubscriber(process, _request.OnAuthorizationDenied);
            AttachSubscriber(process, _request.OnComplete);
            AttachSubscriber(process, _request.OnError);
            AttachSubscriber(process, _request.OnProgress);
            AttachSubscriber(process, _request.OnTimeout);

            t.Execute();
        }
コード例 #8
0
        public override void Execute()
        {
            Transactions.Transaction t;
            Transactions.Processes.ModifyResourceUsageRightsTemplate process;

            process = new Transactions.Processes.ModifyResourceUsageRightsTemplate(_request.Database, _usageRights,
                                                                                   _request.RequestingPartyType, _request.Session, _request.Database.Server.Timeout,
                                                                                   _request.Database.Server.Timeout, _request.Database.Server.BufferSize, _request.Database.Server.BufferSize);
            t = new Transactions.Transaction(process);

            AttachSubscriber(process, _request.OnActionChanged);
            AttachSubscriber(process, _request.OnAuthorizationDenied);
            AttachSubscriber(process, _request.OnComplete);
            AttachSubscriber(process, _request.OnError);
            AttachSubscriber(process, _request.OnProgress);
            AttachSubscriber(process, _request.OnTimeout);

            t.Execute();
        }
コード例 #9
0
        protected override int OnUpdate(DataDictionary <Folder> data, ICondition condition, string scope, object state)
        {
            using (var transaction = new Transactions.Transaction())
            {
                //调用基类同名方法
                var count = base.OnUpdate(data, condition, scope, state);

                if (count < 1)
                {
                    return(count);
                }

                //获取新增的文件夹用户集,并尝试插入该用户集
                data.TryGet(p => p.Users, (key, users) =>
                {
                    if (users == null)
                    {
                        return;
                    }

                    var folderId = data.Get(p => p.FolderId);

                    //首先清除该文件夹的所有用户集
                    this.DataAccess.Delete <Folder.FolderUser>(Condition.Equal("FolderId", folderId));

                    //新增该文件夹的用户集
                    this.DataAccess.InsertMany(users.Where(p => p.FolderId == folderId));
                });

                //提交事务
                transaction.Commit();

                //返回主表插入的记录数
                return(count);
            }
        }
コード例 #10
0
        internal bool TryGetConnection(DbConnection owningConnection, TaskCompletionSource <DbConnectionInternal> retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, out DbConnectionInternal connection)
        {
            Debug.Assert(null != owningConnection, "null owningConnection?");

            DbConnectionPoolGroup poolGroup;
            DbConnectionPool      connectionPool;

            connection = null;

            // SQLBU 431251:
            //  Work around race condition with clearing the pool between GetConnectionPool obtaining pool
            //  and GetConnection on the pool checking the pool state.  Clearing the pool in this window
            //  will switch the pool into the ShuttingDown state, and GetConnection will return null.
            //  There is probably a better solution involving locking the pool/group, but that entails a major
            //  re-design of the connection pooling synchronization, so is post-poned for now.

            // VSDD 674236: use retriesLeft to prevent CPU spikes with incremental sleep
            // start with one msec, double the time every retry
            // max time is: 1 + 2 + 4 + ... + 2^(retries-1) == 2^retries -1 == 1023ms (for 10 retries)
            int retriesLeft = 10;
            int timeBetweenRetriesMilliseconds = 1;

            do
            {
                poolGroup = GetConnectionPoolGroup(owningConnection);
                // Doing this on the callers thread is important because it looks up the WindowsIdentity from the thread.
                connectionPool = GetConnectionPool(owningConnection, poolGroup);
                if (null == connectionPool)
                {
                    // If GetConnectionPool returns null, we can be certain that
                    // this connection should not be pooled via DbConnectionPool
                    // or have a disabled pool entry.
                    poolGroup = GetConnectionPoolGroup(owningConnection); // previous entry have been disabled

                    if (retry != null)
                    {
                        Task <DbConnectionInternal> newTask;
                        CancellationTokenSource     cancellationTokenSource = new CancellationTokenSource();
                        lock (s_pendingOpenNonPooled) {
                            // look for an available task slot (completed or empty)
                            int idx;
                            for (idx = 0; idx < s_pendingOpenNonPooled.Length; idx++)
                            {
                                Task task = s_pendingOpenNonPooled[idx];
                                if (task == null)
                                {
                                    s_pendingOpenNonPooled[idx] = GetCompletedTask();
                                    break;
                                }
                                else if (task.IsCompleted)
                                {
                                    break;
                                }
                            }

                            // if didn't find one, pick the next one in round-robbin fashion
                            if (idx == s_pendingOpenNonPooled.Length)
                            {
                                idx = s_pendingOpenNonPooledNext++ % s_pendingOpenNonPooled.Length;
                            }

                            // now that we have an antecedent task, schedule our work when it is completed.
                            // If it is a new slot or a compelted task, this continuation will start right away.
                            //


                            newTask = s_pendingOpenNonPooled[idx].ContinueWith((_) => {
                                Transactions.Transaction originalTransaction = ADP.GetCurrentTransaction();
                                try
                                {
                                    ADP.SetCurrentTransaction(retry.Task.AsyncState as Transactions.Transaction);
                                    var newConnection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
                                    if ((oldConnection != null) && (oldConnection.State == ConnectionState.Open))
                                    {
                                        oldConnection.PrepareForReplaceConnection();
                                        oldConnection.Dispose();
                                    }
                                    return(newConnection);
                                } finally {
                                    ADP.SetCurrentTransaction(originalTransaction);
                                }
                            }, cancellationTokenSource.Token, TaskContinuationOptions.LongRunning, TaskScheduler.Default);

                            // Place this new task in the slot so any future work will be queued behind it
                            s_pendingOpenNonPooled[idx] = newTask;
                        }

                        // Set up the timeout (if needed)
                        if (owningConnection.ConnectionTimeout > 0)
                        {
                            int connectionTimeoutMilliseconds = owningConnection.ConnectionTimeout * 1000;
                            cancellationTokenSource.CancelAfter(connectionTimeoutMilliseconds);
                        }

                        // once the task is done, propagate the final results to the original caller
                        newTask.ContinueWith((task) => {
                            cancellationTokenSource.Dispose();
                            if (task.IsCanceled)
                            {
                                retry.TrySetException(ADP.ExceptionWithStackTrace(ADP.NonPooledOpenTimeout()));
                            }
                            else if (task.IsFaulted)
                            {
                                retry.TrySetException(task.Exception.InnerException);
                            }
                            else
                            {
                                if (retry.TrySetResult(task.Result))
                                {
                                    PerformanceCounters.NumberOfNonPooledConnections.Increment();
                                }
                                else
                                {
                                    // The outer TaskCompletionSource was already completed
                                    // Which means that we don't know if someone has messed with the outer connection in the middle of creation
                                    // So the best thing to do now is to destroy the newly created connection
                                    task.Result.DoomThisConnection();
                                    task.Result.Dispose();
                                }
                            }
                        }, TaskScheduler.Default);

                        return(false);
                    }

                    connection = CreateNonPooledConnection(owningConnection, poolGroup, userOptions);
                    PerformanceCounters.NumberOfNonPooledConnections.Increment();
                }
                else
                {
                    if (owningConnection.ForceNewConnection)
                    {
                        Debug.Assert(!(oldConnection is DbConnectionClosed), "Force new connection, but there is no old connection");
                        connection = connectionPool.ReplaceConnection(owningConnection, userOptions, oldConnection);
                    }
                    else
                    {
                        if (!connectionPool.TryGetConnection(owningConnection, retry, userOptions, out connection))
                        {
                            return(false);
                        }
                    }

                    if (connection == null)
                    {
                        // connection creation failed on semaphore waiting or if max pool reached
                        if (connectionPool.IsRunning)
                        {
                            // If GetConnection failed while the pool is running, the pool timeout occurred.
                            Bid.Trace("<prov.DbConnectionFactory.GetConnection|RES|CPOOL> %d#, GetConnection failed because a pool timeout occurred.\n", ObjectID);
                            throw ADP.PooledOpenTimeout();
                        }
                        else
                        {
                            // We've hit the race condition, where the pool was shut down after we got it from the group.
                            // Yield time slice to allow shut down activities to complete and a new, running pool to be instantiated
                            //  before retrying.
                            Threading.Thread.Sleep(timeBetweenRetriesMilliseconds);
                            timeBetweenRetriesMilliseconds *= 2; // double the wait time for next iteration
                        }
                    }
                }
            } while (connection == null && retriesLeft-- > 0);

            if (connection == null)
            {
                // exhausted all retries or timed out - give up
                Bid.Trace("<prov.DbConnectionFactory.GetConnection|RES|CPOOL> %d#, GetConnection failed because a pool timeout occurred and all retries were exhausted.\n", ObjectID);
                throw ADP.PooledOpenTimeout();
            }

            return(true);
        }
コード例 #11
0
        protected void OnStop()
        {
            var stack = _stack;

            if (stack == null || stack.Count == 0)
            {
                return;
            }

            var reason = _isAborted != 0 ? StateStopReason.Abortion : StateStopReason.Normal;

            //激发“Stopping”事件
            this.OnStopping(new StateStopEventArgs(reason));

            Transactions.Transaction transaction = null;

            try
            {
                if (reason == StateStopReason.Normal && _options.AffiliateTransactionEnabled)
                {
                    transaction = Transactions.Transaction.Current;

                    if (transaction == null)
                    {
                        transaction = new Transactions.Transaction();
                    }
                }

                //将执行栈转换为数组
                var frames = stack.ToArray();

                for (var index = frames.Length - 1; index >= 0; index--)
                {
                    var frame = frames[index];
                    IDictionary <string, object> parameters = null;

                    if (frame.HasParameters)
                    {
                        parameters = frame.Parameters;
                    }

                    //如果上下文绑定了回调委托则调用该回调方法
                    if (frame.StoppingThunk != null)
                    {
                        var result = frame.StoppingThunk.DynamicInvoke(frame, reason);

                        if (result != null && result.GetType() == typeof(bool) && (bool)result)
                        {
                            continue;
                        }
                    }

                    //将目标状态持久化
                    frame.InnerDestination.Diagram.SetState(frame.InnerDestination, parameters);

                    //如果上下文绑定了回调委托则调用该回调方法
                    if (frame.StoppedThunk != null)
                    {
                        frame.StoppedThunk.DynamicInvoke(frame, reason);
                    }
                }

                if (reason == StateStopReason.Normal && _options.AffiliateTransactionEnabled)
                {
                    if (transaction != null)
                    {
                        transaction.Commit();
                    }
                }
            }
            finally
            {
                if (transaction != null)
                {
                    transaction.Dispose();
                }
            }

            //激发“Stopped”事件
            this.OnStopped(new StateStopEventArgs(reason));
        }
コード例 #12
0
 public IOInputContinue(Transactions.Transaction transaction) : base(transaction)
 {
 }
コード例 #13
0
 protected ContinueBase(Transactions.Transaction transaction)
 {
     Transaction = transaction;
 }
コード例 #14
0
 public OutputVoidContinueExecute(Transactions.Transaction transaction) : base(transaction)
 {
 }
コード例 #15
0
        public override void Execute()
        {
            Logger.Storage.Debug("Initializing engine...");
            ((Providers.EngineBase)_request.Engine).RegisterOnInitialized(_onInitialized);
            _ignoringInitializationComplete = false;
            _request.Engine.SetState(true, false);
            _dsms = new Dictionary <IDatabase, Security.DatabaseSessionManager>();

            for (int i = 0; i < _databases.Count; i++)
            {
                Transactions.Transaction            t;
                Transactions.Processes.GetAllGroups process;

                process = new Transactions.Processes.GetAllGroups(_databases[i],
                                                                  _request.RequestingPartyType, Security.Session.MakeSecurityOverride(), 15000,
                                                                  15000, 8194, 8194);
                t = new Transactions.Transaction(process);

                AttachSubscriber(process, _request.OnActionChanged);
                AttachSubscriber(process, _request.OnAuthorizationDenied);
                AttachSubscriber(process, _request.OnComplete);
                AttachSubscriber(process, _request.OnError);
                AttachSubscriber(process, _request.OnProgress);
                AttachSubscriber(process, _request.OnTimeout);

                //process.OnActionChanged += delegate(Transactions.Processes.Base sender, Transactions.Tasks.Base task, EngineActionType actionType, bool willSendProgress)
                //{
                //};
                process.OnAuthorizationDenied += delegate(Transactions.Processes.Base sender, Transactions.Tasks.Base task)
                {
                    Logger.Storage.Error("Authorization failed while running GetAllGroups on Database '" + sender.Database.Name + "'.");
                    ((Providers.EngineBase)_request.Engine).TriggerOnInitialized(false, "Authorization failed.", null);
                };
                process.OnComplete += delegate(Transactions.Processes.Base sender, ICommandReply reply, object result)
                {
                    lock (_dsms)
                    {
                        _dsms.Add(sender.Database, new Security.DatabaseSessionManager(_request.Engine,
                                                                                       sender.Database, ((Transactions.Processes.GetAllGroups)sender).Groups));
                        if (_dsms.Count == _databases.Count)
                        {
                            _request.Engine.SetState(false, true);
                            Logger.Storage.Debug("Engine initialized.");
                            _sessionMgr.Initialize(_request.Engine, _dsms);
                            ((Providers.EngineBase)_request.Engine).TriggerOnInitialized(true, "Initialization successful.", null);
                        }
                    }
                    Logger.Storage.Debug("All groups for the database named " + sender.Database.Name + " have been loaded.");
                };
                process.OnError += delegate(Transactions.Processes.Base sender, Transactions.Tasks.Base task, string message, Exception exception)
                {
                    Logger.Storage.Error("An error occurred while running GetAllGroups on Database '" + sender.Database.Name + "', message: " + message, exception);
                    ((Providers.EngineBase)_request.Engine).TriggerOnInitialized(false, message, exception);
                };
                //process.OnProgress += delegate(Transactions.Processes.Base sender, Transactions.Tasks.Base task, OpenDMS.Networking.Http.DirectionType direction, int packetSize, decimal sendPercentComplete, decimal receivePercentComplete)
                //{
                //};
                //process.OnTaskComplete += delegate(Transactions.Processes.Base sender, Transactions.Tasks.Base task)
                //{
                //};
                process.OnTimeout += delegate(Transactions.Processes.Base sender, Transactions.Tasks.Base task)
                {
                    Logger.Storage.Error("A timeout occurred while running GetAllGroups on Database '" + sender.Database.Name + "'.");
                    ((Providers.EngineBase)_request.Engine).TriggerOnInitialized(false, "Timeout", null);
                };

                t.Execute();
            }
        }