コード例 #1
0
 public async Task ImportAsync(ImportingJobDescriptor descriptor)
 {
     ShellScope.AddDeferredTask(async defferedTaskContext => {
         using (var tx = _transactionManager.BeginTransaction()) {
             var importTask = await this.CreateTaskAsync(descriptor);
             var context    = new ImportingTaskContext(defferedTaskContext.ServiceProvider, _environment.ContentRootFileProvider);
             await this.DoImportAsync(importTask, context);
             await tx.CommitAsync();
         }
     });
     await Task.CompletedTask;
 }
コード例 #2
0
        public void PeruseHistory(string ip, string user_id, string func_name, string project_id)
        {
            string user_name          = "Guest";
            string strSql             = "";
            ITransactionManager trans = m_objDB.TracationManager;

            try
            {
                trans.BeginTransaction();
                if (HttpContext.Current.Session["user_name"] != null)
                {
                    user_name = HttpContext.Current.Session["user_name"].ToString();
                    strSql    = "insert into peruse_history values ('" + ip + "','" + user_id.ToUpper() + "','" + user_name + "','" + func_name + "',sysdate,'" + project_id + "')";
                }
                else
                {
                    strSql = "insert into peruse_history values ('" + ip + "','" + user_id.ToUpper() + "', (select cname from ssouser.fwempinfo t where t.empno='" + user_id.ToUpper() + "'),'" + func_name + "',sysdate,'" + project_id + "')";
                }
                m_objDB.ExecutionSql(strSql);
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
            }
        }
コード例 #3
0
        public Transaction BeginTransaction(string transactionId = null)
        {
            ValidateTransactionSupport();
            ValidateState();

            return(TransactionManager.BeginTransaction(transactionId));
        }
コード例 #4
0
        public ServerResponse Permissions(string client, string role, [FromBody] PermissionInfo[] objs)
        {
            return(objs.Save(rpis =>
            {
                trans.BeginTransaction();
                repoRolePermission.DeleteBatch(o => o.ClientId == client && o.RoleId == role);

                if (rpis != null && rpis.Length > 0)
                {
                    var pts = rpis.Select(o => o.PermissionType).Distinct();
                    foreach (var pt in pts)
                    {
                        var prpis = rpis.Where(o => o.PermissionType == pt);
                        int maxIdx = prpis.Select(o => o.Position).Max();
                        char[] ps = new char[maxIdx + 1];
                        foreach (var rpi in prpis)
                        {
                            ps[rpi.Position] = rpi.HasPermitted ? '1' : '0';
                        }
                        var rp = new RolePermission()
                        {
                            RoleId = role,
                            PermissionType = pt,
                            ClientId = client,
                            Permissions = new string(ps)
                        };
                        repoRolePermission.Insert(rp);
                    }
                }
                trans.Commit();
                return true;
            }));
        }
コード例 #5
0
        /// <summary>
        ///     Occurs before the action method is invoked.
        ///     Begins transaction.
        /// </summary>
        /// <param name="actionContext">The action context.</param>
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            ITransactionManager transactionManager = GetTransactionManager(actionContext.Request);

            transactionManager.BeginTransaction(IsolationLevel);
            base.OnActionExecuting(actionContext);
        }
コード例 #6
0
        /// <inheritdoc />
        public ITransaction BeginTransaction(TransactionScopeOption scopeOption)
        {
            if (transactionManager == null)
            {
                throw new NotSupportedException("HTTP Transactions are only supported on Neo4j 2.0 and newer.");
            }

            return(transactionManager.BeginTransaction(scopeOption));
        }
コード例 #7
0
        /// <inheritdoc />
        public ITransaction BeginTransaction(TransactionScopeOption scopeOption, IEnumerable <string> bookmarks)
        {
            if (transactionManager == null)
            {
                throw new NotSupportedException("HTTP Transactions are only supported on Neo4j 2.0 and newer.");
            }

            return(transactionManager.BeginTransaction(scopeOption, bookmarks));
        }
コード例 #8
0
ファイル: Storage.cs プロジェクト: golovnyov/homework4
        public void Add(int key, object value)
        {
            try
            {
                m_transactionManager.BeginTransaction();

                m_bufferDictionary = new Dictionary <int, object>(m_mainDictionary);

                m_bufferDictionary.Add(key, value);

                m_transactionManager.CommitTransaction(Commit);
            }
            catch (System.Exception)
            {
                m_transactionManager.RollbackTransaction(Rollback);

                throw;
            }
        }
コード例 #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            try
            {
                _transactionManager.BeginTransaction();
                await next();

                _transactionManager.CommitTransaction();
            }
            catch (Exception ex)
            {
                _transactionManager.RollbackTransaction();
                throw ex;
            }
        }
コード例 #10
0
 public static bool SaveAll <T>(this IRepository <T> repository, ITransactionManager trans, IEnumerable <T> newItems, IEnumerable <T> modifiedItems, IEnumerable <T> deletedItems
                                , EntityEventHandler <T> insertingHandler = null, EntityEventHandler <T> insertedHandler = null
                                , EntityEventHandler <T> updatingHandler  = null, EntityEventHandler <T> updatedHandler  = null
                                , EntityEventHandler <T> deletingHandler  = null, EntityEventHandler <T> deletedHandler  = null)
     where T : class
 {
     try
     {
         trans.BeginTransaction();
         newItems.ForEach(o => repository.Insert(o, insertingHandler, insertedHandler));
         modifiedItems.ForEach(o => repository.Update(o, updatingHandler, updatedHandler));
         deletedItems.ForEach(o => repository.Delete(o, deletingHandler, deletedHandler));
         trans.Commit();
         return(true);
     }
     catch (Exception ex)
     {
         trans.Rollback();
         throw ex;
     }
 }
コード例 #11
0
 public void MoveItemsToHistory(DateTime endTime)
 {
     endTime = endTime.Date;
     try
     {
         trans.BeginTransaction();
         var items = repoTi.Query(o => o.ActionTime < endTime);
         foreach (var item in items)
         {
             var obj = new TimelineItemHistory()
             {
                 ItemId     = item.ItemId,
                 ClientId   = item.ClientId,
                 EventType  = item.EventType,
                 EventName  = item.EventName,
                 UserId     = item.UserId,
                 UserName   = item.UserName,
                 UserType   = item.UserType,
                 Title      = item.Title,
                 Decription = item.Decription,
                 ImageUrl   = item.ImageUrl,
                 DetailUrl  = item.DetailUrl,
                 LinkUrl    = item.LinkUrl,
                 UserUrl    = item.UserUrl,
                 SiteName   = item.SiteName,
                 SiteUrl    = item.SiteUrl,
                 ActionTime = item.ActionTime,
                 Keywords   = item.Keywords
             };
             repoTih.Insert(obj);
             repoTi.Delete(item);
         }
         trans.Commit();
     }
     catch (Exception ex)
     {
         trans.Rollback();
     }
 }
コード例 #12
0
 public bool SaveGroupUsers(string group, UserGroupUser[] objs)
 {
     try
     {
         trans.BeginTransaction();
         repoUgu.DeleteBatch(o => o.UserGroupId == group);
         if (objs != null)
         {
             foreach (var obj in objs)
             {
                 repoUgu.Insert(obj);
             }
         }
         trans.Commit();
         return(true);
     }
     catch (Exception ex)
     {
         trans.Rollback();
         throw ex;
     }
 }
コード例 #13
0
 public ServerResponse Roles(string id, [FromBody] UserRoleInfo[] roles)
 {
     return(roles.Save(rs =>
     {
         trans.BeginTransaction();
         repoUr.DeleteBatch(o => o.UserId == id);
         if (rs != null)
         {
             foreach (var ur in rs)
             {
                 if (ur.IsSelected)
                 {
                     repoUr.Insert(new UserRole()
                     {
                         UserId = id, RoleId = ur.RoleId
                     });
                 }
             }
         }
         trans.Commit();
         return true;
     }));
 }
コード例 #14
0
        /// <inheritdoc />
        /// <exception cref="T:System.InvalidOperationException"><see cref="ITransactionManager" /> is not registered in container.</exception>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var transactionAttribute = GetTransactionAttribute(context);
            ITransactionManager transactionManager = null;

            if (transactionAttribute != null)
            {
                transactionManager = context.HttpContext.RequestServices.GetRequiredService <ITransactionManager>();
                transactionManager.BeginTransaction(transactionAttribute.IsolationLevel);
            }

            var executedContext = await next().ConfigureAwait(false);

            if (transactionManager != null)
            {
                if (transactionManager is ISupportsTransactionStatus tranStatus)
                {
                    if (!tranStatus.IsActive)
                    {
                        _log.Debug("Transaction is already closed");
                        return;
                    }

                    if (executedContext.Exception != null ||
                        transactionAttribute.RollbackOnModelValidationError && context.ModelState.IsValid == false)
                    {
                        // don't use cancellation token to ensure transaction is rolled back on error
                        await transactionManager.RollbackTransactionAsync().ConfigureAwait(false);
                    }
                    else
                    {
                        await transactionManager.CommitTransactionAsync(context.HttpContext.RequestAborted).ConfigureAwait(false);
                    }
                }
            }
        }
コード例 #15
0
        public bool Save(Content obj)
        {
            if (AuthHelper.IsAuthenticated)
            {
                obj.ModifierId   = AuthHelper.CurrentSession.User.UserId;
                obj.ModifierName = AuthHelper.CurrentSession.User.Name();

                if (obj.Published)
                {
                    obj.PublisherId   = AuthHelper.CurrentSession.User.UserId;
                    obj.PublisherName = AuthHelper.CurrentSession.User.Name();
                    if (obj.PublishTime == null)
                    {
                        obj.PublishTime = DateTime.Now;
                    }
                }
            }
            if (obj.ModifiedTime == null)
            {
                obj.ModifiedTime = DateTime.Now;
            }

            try
            {
                trans.BeginTransaction();
                if (repoContent.Save(o => o.SiteId == obj.SiteId && o.ContentId == obj.ContentId, obj))
                {
                    if (obj.Published)
                    {
                        var dbObjs = repoContentCategory.Query(o => o.SiteId == obj.SiteId && o.ContentId == obj.ContentId).ToArray();
                        repoContentCategory.SaveAll(trans, dbObjs, obj.Categories,
                                                    (o, n) => o.SiteId == n.SiteId && o.ContentId == n.ContentId && o.CategoryId == n.CategoryId,
                                                    (r, o) =>
                        {
                            if (o.HotIndex > 0)
                            {
                                o.HotIndex = repoContentCategory.Query(cate => cate.SiteId == o.SiteId && cate.CategoryId == o.CategoryId).Select(cate => cate.HotIndex).Max();
                                if (o.HotIndex == null || o.HotIndex <= 0)
                                {
                                    o.HotIndex = 1;
                                }
                            }
                            if (o.TopIndex > 0)
                            {
                                o.TopIndex = repoContentCategory.Query(cate => cate.SiteId == o.SiteId && cate.CategoryId == o.CategoryId).Select(cate => cate.TopIndex).Max();
                                if (o.TopIndex == null || o.TopIndex <= 0)
                                {
                                    o.TopIndex = 1;
                                }
                            }
                            r.Insert(o);
                        },
                                                    (r, o, c) => { r.Update(c); },
                                                    (r, o) => { r.Delete(o); });
                    }
                    else
                    {
                        repoContentCategory.DeleteBatch(o => o.SiteId == obj.SiteId && o.ContentId == obj.ContentId);
                    }
                    if (obj.RelatedContents != null && obj.RelatedContents.Count > 0)
                    {
                        obj.RelatedContents.ForEach(r =>
                        {
                            if (r.RelatedContent != null)
                            {
                                var rc             = r.RelatedContent;
                                rc.SiteId          = obj.SiteId;
                                rc.CreateAsRelated = true;
                                if (string.IsNullOrEmpty(rc.CreatorId))
                                {
                                    rc.CreatorId = obj.CreatorId;
                                }
                                if (string.IsNullOrEmpty(rc.CreatorName))
                                {
                                    rc.CreatorName = obj.CreatorName;
                                }
                                if (rc.CreateTime == null)
                                {
                                    rc.CreateTime = obj.CreateTime;
                                }
                                if (rc.ShowOrder <= 0)
                                {
                                    rc.ShowOrder = repoContent.Query(o => o.SiteId == obj.SiteId && o.ContentType == obj.ContentType).Select(o => o.ShowOrder).Max();
                                }
                                repoContent.Save(o => o.SiteId == rc.SiteId && o.ContentId == rc.ContentId, rc);
                            }
                        });

                        var dbObjs = repoContentRelation.Query(o => o.SiteId == obj.SiteId && o.ContentId == obj.ContentId).ToArray();

                        repoContentRelation.SaveAll(trans, dbObjs, obj.RelatedContents,
                                                    (o, n) => o.SiteId == n.SiteId && o.ContentId == n.ContentId && o.RelatedContentId == n.RelatedContentId,
                                                    true, true);
                    }
                    else
                    {
                        repoContentRelation.DeleteBatch(o => o.SiteId == obj.SiteId && o.ContentId == obj.ContentId);
                    }
                }
                trans.Commit();
                return(true);
            }
            catch
            {
                trans.Rollback();
                return(false);
            }
        }
コード例 #16
0
 /// <inheritdoc />
 public ITransaction BeginTransaction(TransactionScopeOption scopeOption, IEnumerable <string> bookmarks, string database)
 {
     return(transactionManager.BeginTransaction(scopeOption, bookmarks, database));
 }
コード例 #17
0
 /// <summary>
 /// Begin a unit of work and return the associated <c>ITransaction</c> object.
 /// </summary>
 /// <returns>A transaction instance</returns>
 public ITransaction BeginTransaction()
 {
     transaction = transactionManager.BeginTransaction(this);
     //isCurrentTransaction = true;
     return(transaction);
 }
コード例 #18
0
ファイル: UnitOfWork.cs プロジェクト: danilosingh/Structure
 public void Begin(UnitOfWorkOptions options)
 {
     Options = options;
     transactionManager.BeginTransaction();
     Status = UnitOfWorkStatus.InProgress;
 }
コード例 #19
0
        ///-------------------------------------------------------------------------------------------------
        /// <summary>
        ///  Create a new command context. If there is no current transaction, a transaction is created
        ///  and will be terminated when the context will be disposed.
        /// </summary>
        /// <param name="transactionManager">
        ///  .
        /// </param>
        /// <param name="readOnly">
        ///  true to read only.
        /// </param>
        /// <param name="isolationLevel">
        ///  (Optional)
        /// </param>
        ///-------------------------------------------------------------------------------------------------
        public CommandContext(ITransactionManager transactionManager, bool readOnly = false, SessionIsolationLevel isolationLevel = SessionIsolationLevel.Unspecified)
        {
            DebugContract.Requires(transactionManager, "transactionManager");

            _transactionManager = transactionManager;
            _currentTransaction = _transactionManager.CurrentTransaction ?? (_transaction = transactionManager.BeginTransaction(isolationLevel, readOnly));

            // On s'assure qu' il existe une transaction courante

            if (_currentTransaction.SessionIsolationLevel != SessionIsolationLevel.Serializable)
            {
                _activeTransactionsWhenStarted = transactionManager.GetActiveTransactions();
            }

            // N° de la commande dans le contexte de la transaction courante
            CommandId = _currentTransaction.GetAnIncrementCurrentCommandId();
        }
コード例 #20
0
        public bool SaveFlow(BizFlow flow)
        {
            try
            {
                string flowId = flow.FlowId;
                IEnumerable <FlowState> states = flow.States;
                if (states == null)
                {
                    states = Enumerable.Empty <FlowState>();
                }
                IEnumerable <FlowOperation> operations = flow.Operations;
                if (operations == null)
                {
                    operations = Enumerable.Empty <FlowOperation>();
                }
                IEnumerable <FlowIncome> incomes = flow.Incomes;
                if (incomes == null)
                {
                    incomes = Enumerable.Empty <FlowIncome>();
                }
                IEnumerable <FlowOutcome> outcomes = flow.Outcomes;
                if (outcomes == null)
                {
                    outcomes = Enumerable.Empty <FlowOutcome>();
                }
                IEnumerable <NextBizFlow> nfs = flow.NextBizFlows;
                if (nfs == null)
                {
                    nfs = Enumerable.Empty <NextBizFlow>();
                }

                trans.BeginTransaction();

                // save states
                states.ForEach(o =>
                {
                    if (string.IsNullOrEmpty(o.StateId))
                    {
                        o.StateId = idGenerator.NewId();
                    }
                });

                var ostates = repoFlowState.Query(o => o.FlowId == flowId).ToArray();
                repoFlowState.SaveAll(trans, ostates, states, (o, c) => o.StateId == c.StateId, false);

                // save operations
                operations.ForEach(o =>
                {
                    if (string.IsNullOrEmpty(o.OperationId))
                    {
                        o.OperationId = idGenerator.NewId();
                    }
                });

                var oops = repoFlowOp.Query(o => o.FlowId == flowId).ToArray();
                repoFlowOp.SaveAll(trans, oops, operations, (o, c) => o.OperationId == c.OperationId, true);

                // save incomes
                incomes.ForEach(o =>
                {
                    if (string.IsNullOrEmpty(o.IncomeId))
                    {
                        o.IncomeId = idGenerator.NewId();
                    }
                });

                var oincomes = repoFlowIncome.Query(o => o.FlowId == flowId).ToArray();
                repoFlowIncome.SaveAll(trans, oincomes, incomes, (o, c) => o.IncomeId == c.IncomeId, true);

                // save outcomes
                outcomes.ForEach(o =>
                {
                    if (string.IsNullOrEmpty(o.OutcomeId))
                    {
                        o.OutcomeId = idGenerator.NewId();
                    }
                });

                var ooutcomes = repoFlowOutcome.Query(o => o.FlowId == flowId).ToArray();
                repoFlowOutcome.SaveAll(trans, ooutcomes, outcomes, (o, c) => o.OutcomeId == c.OutcomeId, true);

                // save next flows
                var onfs = repoNextFlow.Query(o => o.FlowId == flowId).ToArray();
                repoNextFlow.SaveAll(trans, onfs, nfs, (o, c) => o.FlowId == c.FlowId && o.NextFlowId == c.NextFlowId,
                                     (repo, o) => { repo.Insert(o); },
                                     null,
                                     (repo, o) => { repo.Delete(o); });

                // save state incomes outcomes operations
                List <FlowStateIncome>    newIncomes  = new List <FlowStateIncome>();
                List <FlowStateOutcome>   newOutcomes = new List <FlowStateOutcome>();
                List <FlowStateOperation> newOps      = new List <FlowStateOperation>();
                states.ForEach(o =>
                {
                    if (o.Incomes != null && o.Incomes.Count > 0)
                    {
                        newIncomes.AddRange(o.Incomes);
                    }
                    if (o.Outcomes != null && o.Outcomes.Count > 0)
                    {
                        newOutcomes.AddRange(o.Outcomes);
                    }
                    if (o.Operations != null && o.Operations.Count > 0)
                    {
                        newOps.AddRange(o.Operations);
                    }
                });
                newIncomes.ForEach(o =>
                {
                    if (string.IsNullOrEmpty(o.IncomeId))
                    {
                        o.IncomeId = idGenerator.NewId();
                    }
                });
                newOutcomes.ForEach(o =>
                {
                    if (string.IsNullOrEmpty(o.OutcomeId))
                    {
                        o.OutcomeId = idGenerator.NewId();
                    }
                });
                newOps.ForEach(o =>
                {
                    if (string.IsNullOrEmpty(o.OperationId))
                    {
                        o.OperationId = idGenerator.NewId();
                    }
                });

                var sincomes = repoStateIncome.Query(o => o.State.FlowId == flowId).ToArray();
                repoStateIncome.SaveAll(trans, sincomes, newIncomes, (o, c) => o.IncomeId == c.IncomeId && o.StateId == c.StateId, true);
                var soutcomes = repoStateOutcome.Query(o => o.State.FlowId == flowId).ToArray();
                repoStateOutcome.SaveAll(trans, soutcomes, newOutcomes, (o, c) => o.OutcomeId == c.OutcomeId && o.StateId == c.StateId, true);
                var ops = repoStateOp.Query(o => o.State.FlowId == flowId).ToArray();
                repoStateOp.SaveAll(trans, ops, newOps, (o, c) => o.OperationId == c.OperationId && o.StateId == c.StateId,
                                    (repo, o) => { repo.Insert(o); },
                                    null,
                                    (repo, o) => { repo.Delete(o); });

                var deleteStates = ostates.Where(o => !states.Any(it => it.StateId == o.StateId));
                deleteStates.ForEach(o => repoFlowState.Delete(o));

                trans.Commit();
                return(true);
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
        }
コード例 #21
0
ファイル: SonesGraphDB.cs プロジェクト: zhouweiaccp/sones
 public Int64 BeginTransaction(SecurityToken mySecurity, bool myLongrunning = false, IsolationLevel myIsolationLevel = IsolationLevel.Serializable)
 {
     return(_transactionManager.BeginTransaction(mySecurity, myLongrunning, myIsolationLevel));
 }
コード例 #22
0
        public IServerResponse <Session> SignOn(SignOnInfo signOnInfo)
        {
            var client    = GetClient(signOnInfo.ClientId);
            var encryptor = GetClientEncryptor(client);
            var hpwd      = pwdEncryptor.Encrypt(signOnInfo.Password);

            var obj = repoUser.Query(o => (o.Account == signOnInfo.AccountOrEmailOrMobile || o.Email == signOnInfo.AccountOrEmailOrMobile || o.Mobile == signOnInfo.AccountOrEmailOrMobile) &&
                                     o.Password == hpwd).FirstOrDefault();

            ServerResponse <Session> response = new ServerResponse <Session>();

            if (obj == null)
            {
                response.Status  = ResponseStatus.Failed;
                response.Message = DAF.SSO.Resources.Locale(o => o.AccountNotFound);
            }
            else
            {
                switch (obj.Status)
                {
                case DataStatus.Deleted:
                    response.Status  = ResponseStatus.Failed;
                    response.Message = DAF.SSO.Resources.Locale(o => o.AccountNotFound);
                    break;

                case DataStatus.Locked:
                    response.Status  = ResponseStatus.Failed;
                    response.Message = DAF.SSO.Resources.Locale(o => o.AccountLocked);
                    break;

                case DataStatus.ReadOnly:
                    response.Status  = ResponseStatus.Failed;
                    response.Message = DAF.SSO.Resources.Locale(o => o.AccountIsReadOnly);
                    break;

                case DataStatus.Normal:
                default:
                    response.Status = ResponseStatus.Success;
                    break;
                }
            }
            if (response.Status == ResponseStatus.Success)
            {
                try
                {
                    trans.BeginTransaction();
                    var serverSession = repoServerSession.Query(o => o.SessionId == signOnInfo.SessionId && o.CientId == client.ClientId && o.DeviceId == signOnInfo.DeviceId).FirstOrDefault();
                    if (serverSession == null)
                    {
                        serverSession = new ServerSession()
                        {
                            CientId               = client.ClientId,
                            SessionId             = signOnInfo.SessionId,
                            FromCientId           = null,
                            DeviceId              = signOnInfo.DeviceId,
                            DeviceInfo            = signOnInfo.DeviceInfo,
                            UserId                = obj.UserId,
                            AccessToken           = randomGenerator.Generate(config.TokenAllowedChars, config.TokenLength),
                            LastAccessTime        = DateTime.Now,
                            AccessTokenExpiryTime = DateTime.Now.AddMinutes(config.SessionExpiredTimeOutMunites)
                        };
                        repoServerSession.Insert(serverSession);
                    }
                    else
                    {
                        if (serverSession.AccessTokenExpiryTime < DateTime.Now)
                        {
                            serverSession.AccessToken = randomGenerator.Generate(config.TokenAllowedChars, config.TokenLength);
                        }
                        serverSession.LastAccessTime        = DateTime.Now;
                        serverSession.AccessTokenExpiryTime = DateTime.Now.AddMinutes(config.SessionExpiredTimeOutMunites);

                        repoServerSession.Update(serverSession);
                    }
                    trans.Commit();

                    response.Data = GetClientSession(client, obj, serverSession);
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    response.Status  = ResponseStatus.Failed;
                    response.Message = ex.Message;
                }
            }
            return(response);
        }
コード例 #23
0
        public static bool SaveAll <T>(this IRepository <T> repository, ITransactionManager trans, IEnumerable <T> original, IEnumerable <T> current, Func <T, T, bool> exists, Action <IRepository <T>, T> actionOriginalNotFound, Action <IRepository <T>, T, T> actionFound, Action <IRepository <T>, T> actionCurrentNotFound)
            where T : class
        {
            try
            {
                trans.BeginTransaction();
                if (original == null || original.Count() <= 0)
                {
                    if (current == null || current.Count() <= 0)
                    {
                        return(false);
                    }

                    if (actionOriginalNotFound != null)
                    {
                        foreach (T obj in current)
                        {
                            actionOriginalNotFound(repository, obj);
                        }
                    }
                    trans.Commit();
                    return(true);
                }
                else
                {
                    if (current == null || current.Count() <= 0)
                    {
                        if (actionCurrentNotFound != null)
                        {
                            foreach (T obj in original)
                            {
                                actionCurrentNotFound(repository, obj);
                            }
                        }
                        trans.Commit();
                        return(true);
                    }
                    else
                    {
                        if (actionOriginalNotFound != null)
                        {
                            var insertedObjs = current.Where(o => original.Any(c => exists(c, o)) == false);
                            foreach (var obj in insertedObjs)
                            {
                                actionOriginalNotFound(repository, obj);
                            }
                        }

                        if (actionFound != null)
                        {
                            var updatedObjs = current.Where(o => original.Any(c => exists(c, o)) == true);
                            foreach (var obj in updatedObjs)
                            {
                                actionFound(repository, original.First(c => exists(c, obj)), obj);
                            }
                        }

                        if (actionCurrentNotFound != null)
                        {
                            var deletedObjs = original.Where(o => current.Any(c => exists(c, o)) == false);
                            foreach (var obj in deletedObjs)
                            {
                                actionCurrentNotFound(repository, obj);
                            }
                        }
                        trans.Commit();
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
        }