/// <summary>
        /// 删除操作
        /// </summary>
        public void DoDelete()
        {
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    // 删除所有授权(这里应当使用存储过程--暂时使用 表关联功能)
                    DynamicPermission[] dps = DynamicPermission.FindAllByProperty("AuthID", this.DynamicAuthID);
                    foreach (DynamicPermission tdp in dps)
                    {
                        tdp.DoDelete();
                    }

                    base.Delete();

                    trans.VoteCommit();
                }
                catch (Exception ex)
                {
                    trans.VoteRollBack();

                    throw ex;
                }
            }
        }
Example #2
0
 public static void CreateSchema(IEngineContext context)
 {
     AR.CreateSchema();
     AR.ConfigurationSource.GetAllConfigurationKeys().ForAll(key => {
         var config = AR.ConfigurationSource.GetConfiguration(key);
         config.Assemblies.ForAll(a => {
             var initializers = a.GetTypes().Where(t => !t.IsInterface && typeof(IDefaultFixtureProvider).IsAssignableFrom(t));
             initializers.ForAll(i => {
                 var initializer = Activator.CreateInstance(i) as IDefaultFixtureProvider;
                 if (initializer == null)
                 {
                     return;
                 }
                 using (var transaction = new TransactionScope()) {
                     try {
                         initializer.CreateDefaultFixture();
                         transaction.VoteCommit();
                     }
                     catch {
                         transaction.VoteRollBack();
                         throw;
                     }
                 }
             });
         });
     });
 }
Example #3
0
        public int CriptografarSenhas()
        {
            Criptografia cript     = new Criptografia();
            int          registros = 0;

            using (TransactionScope scopo = new TransactionScope())
            {
                try
                {
                    Pessoa[] pessoas = Pessoa.FindAll();

                    foreach (Pessoa pes in pessoas)
                    {
                        if (!string.IsNullOrEmpty(pes.Senha))
                        {
                            pes.Senha = cript.criptografarSenhaSHA1(pes.Senha);
                            pes.Save();
                        }
                    }
                    registros = pessoas.Length;
                    scopo.VoteCommit();
                }
                catch (Exception ex)
                {
                    scopo.VoteRollBack();
                }
            }

            return(registros);
        }
        public static void GrantDAuthsToRoles(IList <DynamicAuth> auths, IList <string> roleIDs, IList <string> operations, string tag, string granterID, string granterName)
        {
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    IList <DynamicPermission> dps = GrantDAuths(auths, roleIDs, operations, DynamicPermissionCatalog.SysCatalogEnum.SYS_ROLE.ToString(), tag, granterID, granterName);
                    SysRole[] rols = SysRole.FindAll(Expression.In("RoleID", roleIDs.ToList()));

                    foreach (DynamicPermission tdp in dps)
                    {
                        IEnumerable <SysRole> roles = rols.Where(tent => tent.RoleID == tdp.Data);

                        if (roles.Count() > 0)
                        {
                            SysRole trole = roles.First();

                            tdp.Name = trole.Name;
                            tdp.Tag  = trole.Type.ToString();
                        }

                        tdp.Update();
                    }

                    trans.VoteCommit();
                }
                catch (Exception ex)
                {
                    trans.VoteRollBack();
                    throw ex;
                }
            }
        }
Example #5
0
        /// <summary>
        /// 修改应用(同时修改类型为1,对应权限的名称)
        /// </summary>
        public void DoUpdate()
        {
            this.DoValidate();

            SysAuth[] auths = this.GetRelatedAuth();

            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    this.UpdateAndFlush();

                    if (auths.Length > 0)
                    {
                        foreach (SysAuth auth in auths)
                        {
                            auth.UpdateByApplication(this);
                        }
                    }
                    else
                    {
                        SysAuth auth = new SysAuth();
                        auth.CreateByApplication(this);
                    }

                    trans.VoteCommit();
                }
                catch (Exception ex)
                {
                    trans.VoteRollBack();

                    throw ex;
                }
            }
        }
        /// <summary>
        /// 分配组给用户
        /// </summary>
        public static void GrantGroupToUser(ICollection ids, string userID)
        {
            ICollection <SysGroup> tGrps = GetGroupByIDs(ids);

            using (new SessionScope())
            {
                SysUser user = SysUser.Find(userID);

                using (TransactionScope trans = new TransactionScope())
                {
                    try
                    {
                        foreach (SysGroup grp in tGrps)
                        {
                            user.Group.Add(grp);
                        }

                        trans.VoteCommit();
                    }
                    catch (Exception ex)
                    {
                        trans.VoteRollBack();

                        throw ex;
                    }
                }
            }
        }
        public void Resend_archive_with_files_in_folder()
        {
            var file      = "price_in_dir.zip";
            var priceFile = "price.txt";

            source.SourceType = PriceSourceType.Lan;
            source.PricePath  = file;
            source.ExtrMask   = priceFile;
            source.Save();

            PriceDownloadLog downloadLog;

            using (var scope = new TransactionScope(OnDispose.Rollback)) {
                downloadLog = new PriceDownloadLog {
                    Addition     = String.Empty,
                    ArchFileName = file,
                    ExtrFileName = priceFile,
                    Host         = Environment.MachineName,
                    LogTime      = DateTime.Now,
                    PriceItemId  = priceItem.Id,
                    ResultCode   = 2
                };
                downloadLog.Save();
                scope.VoteCommit();
            }
            var priceSrcPath  = Path.Combine(DataDirectory, file);
            var priceDestPath = Path.Combine(Settings.Default.HistoryPath, downloadLog.Id + Path.GetExtension(file));

            File.Copy(priceSrcPath, priceDestPath, true);
            WcfCallResendPrice(downloadLog.Id);
            Assert.That(PriceItemList.list.FirstOrDefault(i => i.PriceItemId == priceItem.Id), Is.Not.Null, "Прайса нет в очереди на формализацию");
        }
Example #8
0
        protected override void DoWork(TreeNode treeNode)
        {
            IContentProvider contentProvider = treeNode as IContentProvider;

            if (null == contentProvider)
            {
                return;
            }

            views.NodeWapper folder = contentProvider.Content as views.NodeWapper;
            if (null == folder)
            {
                return;
            }

            try
            {
                using (IDbSession session = _sessionFactory.NewSession())
                    using (TransactionScope transactionScope = new TransactionScope(session))
                    {
                        session.Delete("DeleteContact", folder.Id);
                        transactionScope.VoteCommit();
                    }

                treeNode.Remove();
            }
            catch (Exception exception)
            {
                Utils.ShowMsgBox(exception);
            }
        }
        public static void GrantDAuthsToGroups(IList <DynamicAuth> auths, IList <string> groupIDs, IList <string> operations, string tag, string granterID, string granterName)
        {
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    IList <DynamicPermission> dps = GrantDAuths(auths, groupIDs, operations, DynamicPermissionCatalog.SysCatalogEnum.SYS_GROUP.ToString(), tag, granterID, granterName);
                    SysGroup[] grps = SysGroup.FindAll(Expression.In("GroupID", groupIDs.ToList()));

                    foreach (DynamicPermission tdp in dps)
                    {
                        IEnumerable <SysGroup> tgrps = grps.Where(tent => tent.GroupID == tdp.Data);

                        if (tgrps.Count() > 0)
                        {
                            SysGroup tgrp = tgrps.First();

                            tdp.Name = tgrp.Name;
                            tdp.Tag  = tgrp.Type.ToString();
                        }

                        tdp.Update();
                    }

                    trans.VoteCommit();
                }
                catch (Exception ex)
                {
                    trans.VoteRollBack();
                    throw ex;
                }
            }
        }
Example #10
0
        /// <summary>
        /// 删除应用(同时删除类型为1, 对应的权限)
        /// </summary>
        public void DoDelete()
        {
            SysAuth[] auths = this.GetRelatedAuth();

            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    foreach (SysAuth auth in auths)
                    {
                        auth.DoDelete();
                    }

                    this.Delete();

                    trans.VoteCommit();
                }
                catch (Exception ex)
                {
                    trans.VoteRollBack();

                    throw ex;
                }
            }
        }
Example #11
0
        public int popularTabelaTramitacaoUnidade()
        {
            List <string> listaProcessos = getProcessosComAndamentoTramitar();
            int           registros      = 0;

            using (TransactionScope scopo = new TransactionScope())
            {
                try
                {
                    inserirProcessosSemAndamentoTramitar();
                    foreach (string id in listaProcessos)
                    {
                        List <structTUEAndamento> listaAndamentosProcesso = getAndamentosTramitarProcesso(id);
                        registros += listaAndamentosProcesso.Count;
                        TramitacaoUnidadeExercicio objTUE;
                        foreach (structTUEAndamento obj in listaAndamentosProcesso)
                        {
                            objTUE = new TramitacaoUnidadeExercicio();
                            objTUE.UnidadeExercicio   = UnidadeExercicio.Find(Convert.ToInt32(obj.unidade));
                            objTUE.Processo           = Processo.Find(Convert.ToInt32(obj.processo));
                            objTUE.DataEntradaUnidade = Convert.ToDateTime(obj.datatramitacao);
                            objTUE.Save();
                        }
                    }

                    scopo.VoteCommit();
                }
                catch
                {
                    scopo.VoteRollBack();
                }
            }

            return(registros);
        }
 public override void ImportDocument(DocumentReceiveLog log, string filename)
 {
     using (var transaction = new TransactionScope(OnDispose.Rollback)) {
         log.Save();
         transaction.VoteCommit();
     }
 }
        public void ExplicitFlushInsideSecondTransactionProblem()
        {
            var comp1 = new Company("comp1");
            var comp2 = new Company("comp2");

            using (new SessionScope())
            {
                comp1.Create();
                comp2.Create();
            }

            using (new SessionScope(FlushAction.Never))
            {
                using (var tx = new TransactionScope(ondispose: OnDispose.Rollback))
                {
                    var comp2a = Company.Find(comp2.Id);
                    comp2a.Name = "changed";
                    tx.VoteCommit();
                }

                using (var scope = new TransactionScope(ondispose: OnDispose.Rollback))
                {
                    var changedCompanies = AR.FindAllByProperty <Company>("Name", "changed");
                    Assert.AreEqual(1, changedCompanies.Count());
                    var e2a = changedCompanies.First();
                    e2a.Delete();

                    scope.Flush();

                    Assert.AreEqual(0, AR.FindAllByProperty <Company>("Name", "changed").Count());
                }
            }
        }
Example #14
0
        public void CanIntegrateNHibernateAndActiveRecord()
        {
            ActiveRecordStarter.ModelsValidated += delegate
            {
                new ActiveRecordModelBuilder().CreateDummyModelFor(typeof(NHibernateClass));
            };
            ActiveRecordStarter.Initialize(
                GetConfigSource(),
                typeof(ActiveRecordClass),
                typeof(NHibernateClass));

            Recreate();

            using (TransactionScope tx = new TransactionScope())
            {
                ActiveRecordClass ar = new ActiveRecordClass();
                ar.Friend = new NHibernateClass();
                ActiveRecordMediator.Save(ar.Friend);
                ActiveRecordMediator.Save(ar);
                tx.VoteCommit();
            }

            using (TransactionScope tx = new TransactionScope())
            {
                ActiveRecordClass first = ActiveRecordMediator <ActiveRecordClass> .FindFirst();

                Assert.IsNotNull(first);
                Assert.IsNotNull(first.Friend);
            }
        }
		public void CanIntegrateNHibernateAndActiveRecord()
		{
			ActiveRecordStarter.ModelsValidated += delegate
			{
				new ActiveRecordModelBuilder().CreateDummyModelFor(typeof(NHibernateClass));
			};
			ActiveRecordStarter.Initialize(
				GetConfigSource(),
				typeof(ActiveRecordClass),
				typeof(NHibernateClass));

			Recreate();

			using (TransactionScope tx = new TransactionScope())
			{
				ActiveRecordClass ar = new ActiveRecordClass();
				ar.Friend = new NHibernateClass();
				ActiveRecordMediator.Save(ar.Friend);
				ActiveRecordMediator.Save(ar);
				tx.VoteCommit();
			}

			using (TransactionScope tx = new TransactionScope())
			{
				ActiveRecordClass first = ActiveRecordMediator<ActiveRecordClass>.FindFirst();
				Assert.IsNotNull(first);
				Assert.IsNotNull(first.Friend);
			}
		}
Example #16
0
        public void Process()
        {
            using (new SessionScope(FlushAction.Never)) {
                var payers = ActiveRecordLinq.AsQueryable <Payer>()
                             .Where(p => p.SendPaymentNotification && p.Balance < 0)
                             .ToList();
                var usersForNotification = payers.SelectMany(p => p.Users)
                                           .Where(u => u.Client != null && u.Enabled && u.Client.Enabled && !u.Accounting.IsFree);
                foreach (var user in usersForNotification)
                {
                    Cacellation.ThrowIfCancellationRequested();
                    var message = UserMessage.Find(user.Id);
                    message.ShowMessageCount = 1;
                    if (IsFirstNotification())
                    {
                        message.Message = FirstNotificationText;
                    }
                    else
                    {
                        message.Message = SecondNotificationText;
                    }

                    using (var scope = new TransactionScope(OnDispose.Rollback)) {
                        message.Save();
                        scope.VoteCommit();
                    }
                }
            }
        }
        public override void ImportDocument(DocumentReceiveLog log, string filename)
        {
            var dsDocument = new DataSet();

            dsDocument.ReadXml(filename);
            var providerDocumentId = dsDocument.Tables["Header"].Rows[0][HeaderTable.colInvNum].ToString();

            using (new SessionScope()) {
                var doc = Document.Queryable.FirstOrDefault(d => d.FirmCode == log.Supplier.Id &&
                                                            d.ClientCode == log.ClientCode &&
                                                            d.ProviderDocumentId == providerDocumentId &&
                                                            d.DocumentType == log.DocumentType);
                if (doc != null)
                {
                    throw new Exception(String.Format(
                                            "Дублирующийся документ с аттрибутами: FirmCode = {0}, ClientCode = {1}, DocumentType = {2}, ProviderDocumentId = {3}",
                                            log.Supplier.Id,
                                            log.ClientCode,
                                            log.DocumentType,
                                            providerDocumentId));
                }
                doc = new Document(log)
                {
                    ProviderDocumentId = providerDocumentId
                };
                using (var transaction = new TransactionScope(OnDispose.Rollback)) {
                    log.Save();
                    doc.Save();
                    transaction.VoteCommit();
                }
            }
        }
        public DatabaseVersion Upgrade(string oldDbFile)
        {
            using (var scope = new TransactionScope())
            {
                Log.WriteInfo("DatabaseUpdater20To30. OldFile={0}", oldDbFile);
                if (File.Exists(oldDbFile))
                {
                    Log.WriteInfo("File exists. Start converting db from 2.0.0.0 to 3.0.0.0");
                    SqlCeConnection oldConnection = new SqlCeConnection(string.Format("Data Source={0};", oldDbFile));
                    Log.WriteInfo("Start migration");
                    oldConnection.Open();
                    Log.WriteInfo("Connection opened");
                    SqlCeCommand cmd = new SqlCeCommand();
                    cmd.Connection  = oldConnection;
                    cmd.CommandText = "ALTER TABLE A6WEntry ADD   MyTraining_id uniqueidentifier";
                }

                Log.WriteInfo("Set database version to 3.0.0.0");
                DatabaseVersion version = new DatabaseVersion("3.0.0.0");
                version.Create();
                scope.VoteCommit();
                Log.WriteInfo("DatabaseUpdater20To30. Everything is ok");
                return(version);
            }
        }
Example #19
0
 public static void StartSession(Action <ISession> action)
 {
     using (var scope = new TransactionScope(OnDispose.Rollback)) {
         WithSession(action);
         scope.VoteCommit();
     }
 }
        /// <summary>
        /// 删除操作
        /// </summary>
        public void DoDelete()
        {
            // 同时删除相关权限
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    DynamicAuth[] auths = DynamicAuth.FindAllByProperty("CatalogCode", this.Code);
                    foreach (DynamicAuth tauth in auths)
                    {
                        tauth.DoDelete();
                    }

                    base.Delete();

                    trans.VoteCommit();
                }
                catch (Exception ex)
                {
                    trans.VoteRollBack();

                    throw ex;
                }
            }
        }
Example #21
0
        /// <summary>
        /// 删除操作
        /// </summary>
        public void DoDelete()
        {
            // 同时删除相关授权
            using (TransactionScope trans = new TransactionScope())
            {
                try
                {
                    DynamicPermission[] permissions = DynamicPermission.FindAllByProperty("CatalogCode", this.Code);
                    foreach (DynamicPermission tpermission in permissions)
                    {
                        tpermission.DoDelete();
                    }

                    base.Delete();

                    trans.VoteCommit();
                }
                catch (Exception ex)
                {
                    trans.VoteRollBack();

                    throw ex;
                }
            }
        }
        /// <summary>
        /// 从用户回收角色
        /// </summary>
        public static void RevokeRoleFromUser(ICollection ids, string userID)
        {
            IList list = GetRolList(ids);

            using (new SessionScope())
            {
                SysUser user = SysUser.Find(userID);

                using (TransactionScope trans = new TransactionScope())
                {
                    try
                    {
                        IEnumerable <SysRole> trole = user.Role.Where(ent => list.Contains(ent.RoleID));
                        while (trole.Count() > 0)
                        {
                            user.Role.Remove(trole.First());
                        }

                        trans.VoteCommit();
                    }
                    catch (Exception ex)
                    {
                        trans.VoteRollBack();

                        throw ex;
                    }
                }
            }
        }
        /// <summary>
        /// 分配角色给组
        /// </summary>
        public static void GrantRoleToGroup(ICollection ids, string groupID)
        {
            ICollection <SysRole> tents = GetRoleByIDs(ids);

            using (new SessionScope())
            {
                SysGroup group = SysGroup.Find(groupID);

                using (TransactionScope trans = new TransactionScope())
                {
                    try
                    {
                        foreach (SysRole ent in tents)
                        {
                            group.Role.Add(ent);
                        }

                        trans.VoteCommit();
                    }
                    catch (Exception ex)
                    {
                        trans.VoteRollBack();

                        throw ex;
                    }
                }
            }
        }
        /// <summary>
        /// 从组回收角色
        /// </summary>
        public static void RevokeRoleFromGroup(ICollection ids, string groupID)
        {
            IList list = GetRolList(ids);

            using (new SessionScope())
            {
                SysGroup group = SysGroup.Find(groupID);

                using (TransactionScope trans = new TransactionScope())
                {
                    try
                    {
                        IEnumerable <SysRole> tents = group.Role.Where(ent => list.Contains(ent.RoleID));
                        while (tents.Count() > 0)
                        {
                            group.Role.Remove(tents.First());
                        }

                        trans.VoteCommit();
                    }
                    catch (Exception ex)
                    {
                        trans.VoteRollBack();

                        throw ex;
                    }
                }
            }
        }
        /// <summary>
        /// 分配角色给用户
        /// </summary>
        public static void GrantRoleToUser(ICollection ids, string userID)
        {
            ICollection <SysRole> tRols = GetRoleByIDs(ids);

            using (new SessionScope())
            {
                SysUser user = SysUser.Find(userID);

                using (TransactionScope trans = new TransactionScope())
                {
                    try
                    {
                        foreach (SysRole role in tRols)
                        {
                            user.Role.Add(role);
                        }

                        trans.VoteCommit();
                    }
                    catch (Exception ex)
                    {
                        trans.VoteRollBack();

                        throw ex;
                    }
                }
            }
        }
        /// <summary>
        /// 授权给用户
        /// </summary>
        public static void GrantAuthToUser(ICollection authIDs, string userID)
        {
            ICollection <SysAuth> tAuths = GetAuthByIDs(authIDs);

            using (new SessionScope())
            {
                SysUser user = SysUser.Find(userID);

                using (TransactionScope trans = new TransactionScope())
                {
                    try
                    {
                        foreach (SysAuth auth in tAuths)
                        {
                            user.Auth.Add(auth);
                        }

                        trans.VoteCommit();
                    }
                    catch (Exception ex)
                    {
                        trans.VoteRollBack();

                        throw ex;
                    }
                }
            }
        }
        /// <summary>
        /// 从角色回收权限
        /// </summary>
        public static void RevokeAuthFromRole(ICollection authIDs, string roleID)
        {
            IList authList = GetAuthList(authIDs);

            using (new SessionScope())
            {
                SysRole role = SysRole.Find(roleID);

                using (TransactionScope trans = new TransactionScope())
                {
                    try
                    {
                        IEnumerable <SysAuth> tAuths = role.Auth.Where(ent => authList.Contains(ent.AuthID));
                        while (tAuths.Count() > 0)
                        {
                            role.Auth.Remove(tAuths.First());
                        }

                        trans.VoteCommit();
                    }
                    catch (Exception ex)
                    {
                        trans.VoteRollBack();

                        throw ex;
                    }
                }
            }
        }
        private void btnOk_Click(object sender, System.EventArgs e)
        {
            BaseServer server = serverItemControl1.Get();

            using (IDbSession session = _sessionFactory.NewSession())
                using (TransactionScope transactionScope = new TransactionScope(session))
                {
                    if (0 < server.Id)
                    {
                        session.Update("UpdateServer", server);
                    }
                    else
                    {
                        session.Insert("InsertServer", server);
                    }

                    transactionScope.VoteCommit();
                }

            if (1 == this.listView.SelectedIndices.Count)
            {
                this.listView.Items.RemoveAt(this.listView.SelectedIndices[0]);
            }

            InitServerList();
        }
Example #29
0
        /// <summary>
        /// 将人员关联到根节点
        /// </summary>
        /// <param name="RootEnt"></param>
        /// <returns></returns>
        public static int BindUserToRootNode(SysOrganization RootEnt)
        {
            using (TransactionScope trans = new TransactionScope())
            {
                //删除
                string SQL = "delete from SysOrgUser where OrgID='" + RootEnt.ID + "' ";
                Razor.DataHelper.ExecSql(SQL);

                var Arrs = SysUser.FindAll();
                SQL = "insert into SysOrgUser values('{0}','{1}','{2}','{3}','{4}');";
                StringBuilder strb = new StringBuilder();
                //添加
                foreach (var item in Arrs)
                {
                    //SysOrgUser Ent = new SysOrgUser();
                    //Ent.OrgID = RootEnt.ID;
                    //Ent.OrgName = RootEnt.Name;
                    //Ent.UserID = item.ID;
                    //Ent.UserName = item.Name;
                    //Ent.Create();
                    string ExeSql = string.Format(SQL, Guid.NewGuid().ToString(), RootEnt.ID, RootEnt.Name, item.ID, item.Name);
                    strb.Append(ExeSql);
                }
                Razor.DataHelper.ExecSql(strb.ToString());
                trans.VoteCommit();
            }
            return(1);
        }
Example #30
0
        public object ExecuteUpdate(IEngineContext context, IController controller, IControllerContext controllerContext)
        {
            controllerContext.Action = "update";
            using (var transaction = new TransactionScope()) {
                var instance = AR.Find <T>(context.GetParameter(IdParameter));
                if (instance == null)
                {
                    context.Handle404();
                    return(null);
                }

                var pk = AR.Holder.GetModel(Type).Metadata.GetIdentifier(instance, EntityMode.Poco).ToString();

                try {
                    var excludeattr  = controller.GetType().GetAttr <UpdateExcludeAttribute>();
                    var includeattr  = controller.GetType().GetAttr <UpdateIncludeAttribute>();
                    var includeprops = includeattr == null ? null : includeattr.Properties;
                    var excludeprops = excludeattr == null ? null : excludeattr.Properties;

                    var form = BuildCompositeNode(context.Request.Form, Queryfilters.Where(qf => qf.ApplyOnSave), true);

                    OnPreBind(controller, instance);
                    Binder.AutoLoad = AutoLoadBehavior.NullIfInvalidKey;
                    Binder.BindObjectInstance(instance, TemplateObjectName, excludeprops, includeprops, form);
                    OnPostBind(controller, instance);

                    OnPreSave(controller, instance);
                    OnPreUpdate(controller, instance);
                    if (Validator.IsValid(instance))
                    {
                        AR.Save <T>(instance);
                        OnPostUpdate(controller, instance);
                        OnPostSave(controller, instance);

                        transaction.Flush();
                        transaction.VoteCommit();

                        pk = AR.Holder.GetClassMetadata(Type).GetIdentifier(instance, EntityMode.Poco).ToString();
                        controllerContext.PropertyBag[TemplateObjectName] = instance;
                        context.SuccessMessage(instance + " has been updated");
                    }
                    else
                    {
                        transaction.VoteRollBack();
                        context.ErrorMessages(Validator.GetErrorSummary(instance).ErrorMessages);
                    }
                } catch (Exception ex) {
                    transaction.VoteRollBack();
                    context.ErrorMessages(ex);
                } finally {
                    context.Flash[TemplateObjectName]         = instance;
                    controllerContext.PropertyBag["objectid"] = pk;
                    context.CurrentControllerContext.PropertyBag[TemplateObjectName] = instance;
                }
            }

            return(null);
        }
Example #31
0
 protected override void UpdateName(object content)
 {
     using (IDbSession session = m_sessionFactory.NewSession())
         using (TransactionScope transactionScope = new TransactionScope(session))
         {
             session.Update("UpdateFolderForName", content);
             transactionScope.VoteCommit();
         }
 }
        public void ExplicitFlushInsideSecondTransactionProblem()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(),
                typeof(Company),
                typeof(Person),
                typeof(Blog),
                typeof(Post));
            Recreate();

            Company comp1 = new Company("comp1");
            Company comp2 = new Company("comp2");
            using(new SessionScope())
            {
                comp1.Create();
                comp2.Create();
            }

            using(new SessionScope(FlushAction.Never))
            {
                using(TransactionScope tx = new TransactionScope(OnDispose.Rollback))
                {
                    Company comp2a = Company.Find(comp2.Id);
                    comp2a.Name = "changed";
                    tx.VoteCommit();
                }

                using(new TransactionScope(OnDispose.Rollback))
                {
                    Company[] changedCompanies = ActiveRecordMediator<Company>.FindAllByProperty("Name", "changed");
                    Assert.AreEqual(1, changedCompanies.Length);
                    Company e2a = changedCompanies[0];
                    e2a.Delete();

                    SessionScope.Current.Flush();

                    Assert.AreEqual(0, ActiveRecordMediator<Company>.FindAllByProperty("Name", "changed").Length);
                }
            }
        }
		public void NestedTransactionWithRollbackOnDispose()
		{
			ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog));
			Recreate();

			Post.DeleteAll();
			Blog.DeleteAll();

			using(new TransactionScope())
			{
				Blog blog = new Blog();

				using(TransactionScope t1 = new TransactionScope(TransactionMode.Inherits, OnDispose.Rollback))
				{
					blog.Author = "hammett";
					blog.Name = "some name";
					blog.Save();

					t1.VoteCommit();
				}

				using(TransactionScope t2 = new TransactionScope(TransactionMode.Inherits, OnDispose.Rollback))
				{
					Post post = new Post(blog, "title", "post contents", "Castle");

					try
					{
						post.SaveWithException();

						t2.VoteCommit(); // Will never be called
					}
					catch(Exception)
					{
						// t2.VoteRollBack();
					}
				}
			}

			Blog[] blogs = Blog.FindAll();
			Assert.AreEqual(0, blogs.Length);

			Post[] posts = Post.FindAll();
			Assert.AreEqual(0, posts.Length);
		}
		public void MixingSessionScopeAndTransactionScopes()
		{
			ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog));
			Recreate();

			Post.DeleteAll();
			Blog.DeleteAll();

			using(new SessionScope())
			{
				using(TransactionScope root = new TransactionScope())
				{
					using(TransactionScope t1 = new TransactionScope()) // Isolated
					{
						Blog blog = new Blog();

						Blog.FindAll(); // Just to force a session association

						using(new TransactionScope(TransactionMode.Inherits))
						{
							Blog.FindAll(); // Just to force a session association

							blog.Author = "hammett";
							blog.Name = "some name";
							blog.Save();
						}

						using(new TransactionScope(TransactionMode.Inherits))
						{
							Post post = new Post(blog, "title", "post contents", "Castle");

							post.Save();
						}

						t1.VoteRollBack();
					}

					Blog.FindAll(); // Cant be locked

					using(new TransactionScope())
					{
						Blog blog = new Blog();
						Blog.FindAll(); // Just to force a session association

						using(new TransactionScope())
						{
							Blog.FindAll(); // Just to force a session association

							blog.Author = "hammett";
							blog.Name = "some name";
							blog.Save();
						}

						using(TransactionScope t1n = new TransactionScope(TransactionMode.Inherits))
						{
							Post post = new Post(blog, "title", "post contents", "Castle");

							try
							{
								post.SaveWithException();
							}
							catch(Exception)
							{
								t1n.VoteRollBack();
							}
						}
					}

					root.VoteCommit();
				}
			}

			Blog[] blogs = Blog.FindAll();
			Assert.AreEqual(1, blogs.Length);

			Post[] posts = Post.FindAll();
			Assert.AreEqual(0, posts.Length);
		}
 public void UsingTransactionScopeWithCommitAndInnerSessionScope()
 {
     using (TransactionScope scope = new TransactionScope())
     {
         using (new SessionScope())
         {
             new SSAFEntity("example").Save();
             Assert.AreEqual(1, SSAFEntity.FindAll().Count());
         }
         //Assert.AreEqual(1, SSAFEntity.FindAll().Length);
         scope.VoteCommit();
     }
     using (new SessionScope())
         Assert.AreEqual(1, SSAFEntity.FindAll().Count());
 }
		public void ValidateIsUniqueWithinTransactionScope()
		{
			ActiveRecordStarter.Initialize( GetConfigSource(), typeof(Blog2) );
			Recreate();
			
			// The IsUniqueValidator was created a new SessionScope and causing an
			// error when used inside TransactionScope
			
			using (TransactionScope scope = new TransactionScope())
			{
				Blog2 blog = new Blog2();
				blog.Name = "A cool blog";
				blog.Create();
					
				blog = new Blog2();
				blog.Name = "Another cool blog";
				blog.Create();
				
				scope.VoteCommit();
			}
		}