public async Task <ObjectResponse <GetCartViewModel> > Create(AddCartModel model)
        {
            _addCartCommand.Model = model;

            using (_transactionManager.Begin())
            {
                var result = await _addCartCommand.Execute();

                _transactionManager.Commit();

                if (_addCartCommand.Validations?.Any() == true)
                {
                    return(new ObjectResponse <GetCartViewModel>
                    {
                        Validations = _addCartCommand.Validations,
                        Success = false
                    });
                }

                return(new ObjectResponse <GetCartViewModel>
                {
                    Data = result,
                    Success = true
                });
            }
        }
Ejemplo n.º 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();
            }
        }
Ejemplo n.º 3
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;
            }));
        }
Ejemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="action"></param>
        /// <returns>如果延迟执行,返回true</returns>
        private void ProcessAction(ScheduledAction action)
        {
            if (this._transactionStatus == TransactionStatus.Delay)
            {
                _actions.Add(action);//若处于延迟模式的事务中,那么将该操作暂存
                return;
            }

            if (this._transactionStatus == TransactionStatus.Timely)
            {
                //若已经开启全局事务,直接执行
                _actions.Add(action); //直接执行也要加入到actions集合中
                ExecuteAction(action);
                return;
            }

            if (this._transactionStatus == TransactionStatus.None)
            {
                //没有开启事务,立即执行
                using (ITransactionManager manager = GetTransactionManager())
                {
                    manager.Begin();
                    ExecuteAction(action);
                    //提交事务
                    RaisePreCommit(action);
                    manager.Commit();
                    RaiseCommitted(action);
                }
                return;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     Commit a transaction
        /// </summary>
        /// <param name="transactionId">Transaction identifier that was specified in <see cref="IStompClient.BeginTransaction" />.</param>
        /// <exception cref="NotFoundException">No transaction have been started with that identifier.</exception>
        public void CommitTransaction(string transactionId)
        {
            if (transactionId == null)
            {
                throw new ArgumentNullException("transactionId");
            }

            _transactionManager.Commit(transactionId);
        }
Ejemplo n.º 6
0
        public void Commit()
        {
            if (!this.IsInTransaction)
            {
                throw new NotBeginTransactionException(Strings.NotOpenTransaction);
            }
            else
            {
                _transactionCount--;
                if (_transactionCount == 0)
                {
                    if (IsCommiting)
                    {
                        throw new RepeatedCommitException(Strings.TransactionRepeatedCommit);
                    }

                    IsCommiting = true;

                    try
                    {
                        if (_transactionStatus == TransactionStatus.Delay)
                        {
                            _transactionStatus = TransactionStatus.Timely; //开启即时事务
                            using (ITransactionManager manager = GetTransactionManager())
                            {
                                manager.Begin();
                                ExecuteActionQueue();
                                RaisePreCommitQueue();

                                manager.Commit();

                                RaiseCommittedQueue();
                            }
                        }
                        else if (_transactionStatus == TransactionStatus.Timely)
                        {
                            ExecuteActionQueue();
                            RaisePreCommitQueue();

                            _timelyManager.Commit();

                            RaiseCommittedQueue();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                    finally
                    {
                        Clear();
                        IsCommiting = false;
                    }
                }
            }
        }
        public void MultipleTransactionTest()
        {
            ITransactionManager tm = bf.CurrentConversation.TransactionManager;

            tm.Begin();
            MockEntity mo1 = new MockEntity();

            mo1.Save();
            tm.Commit();

            tm.Begin();
            MockEntity mo2 = new MockEntity();

            mo2.Save();
            tm.Commit();

            tm.Begin();
            Assert.IsNotNull(MockEntityDAO.Instance.Get(mo1.Id));
            Assert.IsNotNull(MockEntityDAO.Instance.Get(mo2.Id));

            tm.Commit();

            TearDown();
        }
        /// <summary>
        /// Handles the System.Web.HttpApplication.EndRequest event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnEndRequest(Object sender, EventArgs e)
        {
            HttpApplication     application = (HttpApplication)sender;
            HttpContext         context     = application.Context;
            ITransactionManager mgr         = ConnectionScope.Current.TransactionManager;

            if (mgr != null && mgr.IsOpen)
            {
                if (context.Error != null)
                {
                    mgr.Rollback();
                }
                else
                {
                    mgr.Commit();
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Handles the System.Web.HttpApplication.EndRequest event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnEndRequest(Object sender, EventArgs e)
        {
            HttpApplication     application = (HttpApplication)sender;
            HttpContext         context     = application.Context;
            ITransactionManager mgr         = context.Items[ManagerKey] as TransactionManager;

            if (mgr != null && mgr.IsOpen)
            {
                context.Items[ManagerKey] = null;

                if (context.Error != null)
                {
                    mgr.Rollback();
                }
                else
                {
                    mgr.Commit();
                }
            }
        }
Ejemplo n.º 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;
     }
 }
Ejemplo n.º 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();
     }
 }
Ejemplo n.º 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;
     }
 }
        public async Task Add(string imageName, IFormFile file, string savePath)
        {
            var extention = Path.GetExtension(file.FileName);
            var fileName  = Path.Combine(savePath, imageName + extention);

            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            using (var stream = new FileStream(fileName, FileMode.Create))
            {
                await file.CopyToAsync(stream).ConfigureAwait(false);
            }

            using var transaction = this.TransactionManager.BeginTransaction();
            var entity = this.CreateEntity(fileName, imageName);

            await this.DbRepository.Create(entity).ConfigureAwait(false);

            await TransactionManager.Commit(transaction).ConfigureAwait(false);
        }
Ejemplo n.º 14
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;
     }));
 }
Ejemplo n.º 15
0
        public T2 Invoke <T1, T2>(T1 input, Func <T1, T2> func)
            where T1 : class
            where T2 : class
        {
            try
            {
                _transactionManager.Initialize();

                var output = func.Invoke(input);

                _transactionManager.Commit();

                return(output);
            }
            catch
            {
                _transactionManager.Rollback();
                throw;
            }
            finally
            {
                _transactionManager.Dispose();
            }
        }
Ejemplo n.º 16
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);
            }
        }
Ejemplo n.º 17
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);
        }
Ejemplo n.º 18
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;
            }
        }
Ejemplo n.º 19
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;
            }
        }