Example #1
0
        // ---------------------------------------------------------------------

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public OperationResult UpdateReservable(DTOReservable tableDTO)
        {
            OperationResult result = new OperationResult();

            //::::::::::::::::::::::::::::::::::::::::::

            using (TransactionScope scope = new TransactionScope(TransactionMode.New, OnDispose.Commit))
            {
                try
                {
                    Table    tableToUpdate = Table.Find(tableDTO.Id);
                    Location location      = Location.Find(tableToUpdate.ParentLocation.Id);

                    location.UpdateTable(tableToUpdate, tableDTO.Name, tableDTO.MaxGuests, tableDTO.X, tableDTO.Y, tableDTO.Width, tableDTO.Height, tableDTO.Shape, tableDTO.Number);

                    result.Success        = true;
                    result.ObjectAffected = tableDTO.Id;
                    result.Message        = string.Format("Table id => {0} update ok", tableDTO.Id);

                    ServiceLogger.Log(result.Message);
                }
                catch (ReservableAlreadyExistsException rae)
                {
                    scope.VoteRollBack();

                    // TODO: logging, proper message in result

                    result.Success        = false;
                    result.ObjectAffected = 0;
                    result.Message        = rae.ToString();

                    ServiceLogger.LogException(string.Format("Table already exists => {0}.", tableDTO.ToString()), rae);
                }
                catch (Castle.ActiveRecord.NotFoundException nfe)
                {
                    scope.VoteRollBack();
                    // TODO: logging, proper message in result
                    result.Success        = false;
                    result.ObjectAffected = 0;
                    result.Message        = nfe.ToString();

                    ServiceLogger.LogException(string.Format("Table not found => {0}.", tableDTO.ToString()), nfe);
                }
                catch (ActiveRecordException are)
                {
                    scope.VoteRollBack();
                    // TODO: logging, proper message in result
                    result.Success        = false;
                    result.ObjectAffected = 0;
                    result.Message        = are.ToString();

                    ServiceLogger.LogException(string.Format("Table => {0}.", tableDTO.ToString()), are);
                }
            }

            //::::::::::::::::::::::::::::::::::::::::::

            return(result);
        }
Example #2
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 #3
0
        // ---------------------------------------------------------------------

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public OperationResult AddReservable(DTOReservable tableDTO, DTOLocation locationDTO)
        {
            OperationResult result = new OperationResult();

            //::::::::::::::::::::::::::::::::::::::::::

            using (TransactionScope scope = new TransactionScope(TransactionMode.New, OnDispose.Commit))
            {
                try
                {
                    DTOHelpers.ValidateReservableDTO(tableDTO);
                    DTOHelpers.ValidateLocationDTO(locationDTO);

                    Location location = Location.Find(locationDTO.Id);
                    Table    table    = DTOHelpers.TableFromDTO(tableDTO);

                    location.AddTable(table);

                    result.Success        = true;
                    result.ObjectAffected = table.Id;
                    result.Message        = String.Format("{0} added successfully to {1}", tableDTO.ToString(), location.ToString());

                    ServiceLogger.Log(string.Format("Table {0} added to location {1}", tableDTO.Name, location.Name));
                }
                catch (ActiveRecordException are)
                {
                    scope.VoteRollBack();
                    result.Success = false;
                    result.Message = string.Format("Could not add table {0};{1}{2}", tableDTO.Name, Environment.NewLine, are.ToString());

                    ServiceLogger.LogException(string.Format("Could not add table {0}", tableDTO.Name), are);
                }
                catch (ReservableAlreadyExistsException rree)
                {
                    scope.VoteRollBack();
                    result.Success = false;
                    result.Message = string.Format("A table called => {0} already exists;{1}{2}", tableDTO.Name, Environment.NewLine, rree.ToString());

                    ServiceLogger.LogException(string.Format("A table called => {0} already exists", tableDTO.Name), rree);
                }
                catch (InvalidDTOException ide)
                {
                    scope.VoteRollBack();
                    result.Success = false;
                    result.Message = string.Format("Problem with supplied information, cannot add table {0}; {1}{2}", tableDTO.Name, Environment.NewLine, ide.ToString());

                    ServiceLogger.LogException(string.Format("Problem with supplied information, cannot add table {0}", tableDTO.Name), ide);
                }
            }

            //::::::::::::::::::::::::::::::::::::::::::

            return(result);
        }
        /// <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;
                    }
                }
            }
        }
Example #5
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;
                     }
                 }
             });
         });
     });
 }
        /// <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 #7
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);
        }
Example #8
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 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;
                    }
                }
            }
        }
        public void RollbackVote()
        {
            ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog));
            Recreate();

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

            using (TransactionScope transaction = new TransactionScope())
            {
                Blog blog = new Blog();
                blog.Author = "hammett";
                blog.Name   = "some name";
                blog.Save();

                Post post = new Post(blog, "title", "post contents", "Castle");
                post.Save();

                // pretend something went wrong

                transaction.VoteRollBack();
            }

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

            Post[] posts = Post.FindAll();
            Assert.AreEqual(0, posts.Length);
        }
        /// <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;
                    }
                }
            }
        }
        /// <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;
                    }
                }
            }
        }
		public void RollbackVote()
		{
			ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog));
			Recreate();

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

			using(TransactionScope transaction = new TransactionScope())
			{
				Blog blog = new Blog();
				blog.Author = "hammett";
				blog.Name = "some name";
				blog.Save();

				Post post = new Post(blog, "title", "post contents", "Castle");
				post.Save();

				// pretend something went wrong

				transaction.VoteRollBack();
			}

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

			Post[] posts = Post.FindAll();
			Assert.AreEqual(0, posts.Length);
		}
        public void RollbackUponException()
        {
            using (var transaction = new TransactionScope())
            {
                var blog = new Blog {
                    Author = "hammett", Name = "some name"
                };
                blog.Save();

                var post = new Post(blog, "title", "post contents", "Castle");

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

            using (new SessionScope()) {
                var blogs = Blog.FindAll().ToArray();
                Assert.AreEqual(0, blogs.Length);

                var posts = Post.FindAll().ToArray();
                Assert.AreEqual(0, posts.Length);
            }
        }
        /// <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;
                    }
                }
            }
        }
        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;
                }
            }
        }
        /// <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;
                    }
                }
            }
        }
Example #18
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 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 #20
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;
                }
            }
        }
Example #21
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;
                }
            }
        }
        public void RollbackVote()
        {
            using (var transaction = new TransactionScope())
            {
                var blog = new Blog {
                    Author = "hammett", Name = "some name"
                };
                blog.Save();

                var post = new Post(blog, "title", "post contents", "Castle");
                post.Save();

                // pretend something went wrong

                transaction.VoteRollBack();
            }

            using (new SessionScope()) {
                var blogs = Blog.FindAll().ToArray();
                Assert.AreEqual(0, blogs.Length);

                var posts = Post.FindAll().ToArray();
                Assert.AreEqual(0, posts.Length);
            }
        }
        /// <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 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 #25
0
        // ---------------------------------------------------------------------

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public OperationResult DeleteReservable(DTOReservable tableDTO, DTOLocation locationDTO)
        {
            OperationResult result = new OperationResult();

            //::::::::::::::::::::::::::::::::::::::::::

            using (TransactionScope txnScope = new TransactionScope(TransactionMode.New, OnDispose.Commit))
            {
                try
                {
                    Table table = Table.Find(tableDTO.Id);

                    // remove the reference to the table from the location
                    Location loc = Location.Find(locationDTO.Id);
                    loc.RemoveTable(table);

                    result.Success        = true;
                    result.Message        = string.Format("Table => {0} deleted ok.", tableDTO.Name);
                    result.ObjectAffected = tableDTO.Id;

                    ServiceLogger.Log(result.Message);
                }
                catch (InvalidOperationException ioe)
                {
                    txnScope.VoteRollBack();
                    result.Success        = false;
                    result.Message        = string.Format("Cannot delete table => {0}{1}{2}.", tableDTO.ToString(), Environment.NewLine, ioe.ToString());
                    result.ObjectAffected = tableDTO.Id;

                    ServiceLogger.LogException(string.Format("Cannot delete table => {0}.", tableDTO.ToString()), ioe);
                }
                catch (ActiveRecordException are)
                {
                    txnScope.VoteRollBack();

                    result.Success        = false;
                    result.Message        = string.Format("Error when trying to delete Table => {0};{1}{2}", tableDTO.Name, Environment.NewLine, are.ToString());
                    result.ObjectAffected = tableDTO.Id;

                    ServiceLogger.LogException(string.Format("Error when trying to delete Table => {0}", tableDTO.Name), are);
                }
            }

            //::::::::::::::::::::::::::::::::::::::::::

            return(result);
        }
        public void UsingTransactionScopeWithRollback()
        {
            SqlConnection conn = CreateSqlConnection2();
            ISession      session1, session2;
            ITransaction  trans1, trans2;

            using (TransactionScope scope = new TransactionScope())
            {
                Blog blog = new Blog {
                    Name = "hammett's blog", Author = "hamilton verissimo"
                };
                blog.Save();

                session1 = blog.GetCurrentSession();
                trans1   = blog.GetCurrentSession().Transaction;
                Assert.IsNotNull(session1);
                Assert.IsNotNull(session1.Transaction);
                Assert.IsFalse(session1.Transaction.WasCommitted);
                Assert.IsFalse(session1.Transaction.WasRolledBack);

                blog.Evict();
                conn.Open();

                using (new DifferentDatabaseScope(conn))
                {
                    blog.Create();

                    session2 = blog.GetCurrentSession();
                    trans2   = blog.GetCurrentSession().Transaction;
                    Assert.IsNotNull(session2);

                    Assert.IsFalse(Object.ReferenceEquals(session1, session2));

                    Assert.IsNotNull(session2.Transaction);
                    Assert.IsFalse(session2.Transaction.WasCommitted);
                    Assert.IsFalse(session2.Transaction.WasRolledBack);

                    scope.VoteRollBack();
                }
            }

            Assert.IsFalse(session1.IsOpen);
            Assert.IsFalse(session2.IsOpen);
            Assert.IsFalse(trans1.WasCommitted);
            Assert.IsTrue(trans1.WasRolledBack);
            Assert.IsFalse(trans2.WasCommitted);
            Assert.IsTrue(trans2.WasRolledBack);

            using (new SessionScope()) {
                var blogs = Blog.FindAll().ToArray();
                Assert.IsNotNull(blogs);
                Assert.AreEqual(0, Blog.Count());

                var blogs2 = OtherDbBlog.FindAll().ToArray();
                Assert.IsNotNull(blogs2);
                Assert.AreEqual(0, OtherDbBlog.Count());
            }
        }
Example #27
0
        public object ExecuteCreate(IEngineContext context, IController controller, IControllerContext controllerContext)
        {
            T      instance = null;
            string pk       = null;
            var    form     = BuildCompositeNode(context.Request.Form, Queryfilters.Where(qf => qf.ApplyOnSave), true);

            using (var transaction = new TransactionScope()) {
                try {
                    Binder.AutoLoad = AutoLoadBehavior.OnlyNested;
                    instance        = (T)Binder.BindObject(typeof(T), TemplateObjectName, CreateExcludedProperties, CreateAllowedProperties, form);
                    OnPostBind(controller, instance);

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

                        OnPostCreate(controller, instance);
                        OnPostSave(controller, instance);

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

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

            return(null);
        }
Example #28
0
 public void ActiveRecordUsingTransactionScopeWithRollback()
 {
     InitModel();
     using (TransactionScope scope = new TransactionScope())
     {
         new SSAFEntity("example").Save();
         //Assert.AreEqual(1, SSAFEntity.FindAll().Length);
         scope.VoteRollBack();
     }
     Assert.AreEqual(0, SSAFEntity.FindAll().Length);
 }
Example #29
0
        public static void Registro()
        {
            foreach (var archivo in ActiveRecordBase <ConsumoDto> .FindAllByProperty("Procesado", false))
            {
                var documento = HelperPersona.GetPersona(
                    archivo.Cuit, archivo.TipoCliente,
                    archivo.RazonSocial, archivo.NombrePersona,
                    archivo.NroDocumento, archivo.Empresa);

                var cliente = HelperCuenta.GetCuenta(
                    archivo.Cuit, archivo.NroDocumento, archivo.Empresa);

                using (var transac = new TransactionScope())
                    try
                    {
                        var puntos = HelperPuntos.GetPuntos(archivo.Empresa, archivo.FechaHoraComprobante,
                                                            archivo.ImportePesosNetoImpuestos);

                        double acelerador = Double.Parse(archivo.Coeficiente) / 100;
                        puntos = acelerador > 0 ? acelerador * puntos : puntos;

                        var cuenta = new CuentaCorrienteDto
                        {
                            FechaCompra = archivo.FechaHoraComprobante.Date,
                            HoraCompra  = DateTime.Now,
                            Key         = new KeyCuenta
                            {
                                CodEmpresa        = archivo.Empresa,
                                NumeroComprobante = archivo.NroComprobante
                            },
                            MontoCompra     = archivo.ImportePesosNetoImpuestos,
                            Movimiento      = puntos >= 0 ? HelperMovimiento.FindMovimiento("Suma De Puntos") : HelperMovimiento.FindMovimiento("Anulación Carga"),
                            NumeroDocumento = documento,
                            NumeroCuenta    = cliente,
                            Puntos          = puntos,
                            Sucursal        = HelperSucursal.GetSucursal(),
                            Usuario         = "web",
                            Programa        = archivo.Programa,
                            Secretaria      = archivo.Secretaria,
                            Coeficiente     = archivo.Coeficiente
                        };
                        cuenta.Save();
                        transac.VoteCommit();
                    }
                    catch (Exception ex)
                    {
                        archivo.Error = ex.Message;
                        Log.Fatal(ex);
                        transac.VoteRollBack();
                    }
                archivo.Procesado = true;
                archivo.Save();
            }
        }
Example #30
0
 public void UsingTransactionScopeWithRollback()
 {
     using (TransactionScope scope = new TransactionScope())
     {
         new SSAFEntity("example").Save();
         //Assert.AreEqual(1, SSAFEntity.FindAll().Length);
         scope.VoteRollBack();
     }
     using (new SessionScope())
         Assert.AreEqual(0, SSAFEntity.FindAll().Count());
 }
Example #31
0
        /// <summary>
        /// 改变当前节点的父节点
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="target"></param>
        /// <param name="position"></param>
        protected virtual void ChangeParent(IDbConnection conn, T target, int position)
        {
            // 目标节点必须存在且与当前父节点不同,当前节点不能为目标节点下层节点
            if (target != null && this.ParentID != target.ID && this.ID != target.ID &&
                (String.IsNullOrEmpty(target.Path) || target.Path.IndexOf(this.ID) < 0))
            {
                using (TransactionScope trans = new TransactionScope())
                {
                    try
                    {
                        string orgParentID  = this.ParentID;
                        int    orgSortIndex = this.SortIndex.GetValueOrDefault();

                        this.RefreshStructureInfo(target.ID, position);

                        string sql = String.Empty;

                        if (!String.IsNullOrEmpty(orgParentID))
                        {
                            // 调整源父节点的IsLeaf状态
                            sql = String.Format("UPDATE {0} SET {3} = 1 WHERE {1} = '{2}' AND NOT EXISTS(SELECT {1} FROM {0} WHERE {4} = '{2}'); ",
                                                TableName, PrimaryKeyName, orgParentID,
                                                Prop_IsLeaf, Prop_ParentID);

                            // 调整源父节点的子节点的SortIndex
                            sql += String.Format("UPDATE {0} SET {3} = {3} - 1 WHERE {4} = '{1}' AND {3} > {2} ",
                                                 TableName, orgParentID, orgSortIndex,
                                                 Prop_SortIndex, Prop_ParentID);
                        }
                        else
                        {
                            // 调整源父节点的子节点的SortIndex
                            sql = String.Format("UPDATE {0} SET {1} = {1} - 1 WHERE {2} IS NULL OR LTRIM(RTRIM({2})) = '' ",
                                                TableName,
                                                Prop_SortIndex, Prop_ParentID);
                        }

                        DataHelper.QueryValue(sql, conn);

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

                        throw ex;
                    }
                }

                // 5.刷新节点状态
                this.Refresh();
                target.Refresh();
            }
        }
		public void NestedTransactions()
		{
			ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Post), typeof(Blog));
			Recreate();

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

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

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

					t1.VoteCommit();
				}

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

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

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

			Post[] posts = Post.FindAll();
			Assert.AreEqual(0, posts.Length);
		}
 public void UsingTransactionScopeWithRollbackAndInnerSessionScope()
 {
     using (TransactionScope scope = new TransactionScope())
     {
         using (new SessionScope())
         {
             new SSAFEntity("example").Save();
             Assert.AreEqual(1, SSAFEntity.FindAll().Count());
         }
         Assert.AreEqual(1, SSAFEntity.FindAll().Count());
         scope.VoteRollBack();
     }
     using (new SessionScope())
         Assert.AreEqual(0, SSAFEntity.FindAll().Count());
 }
        public void UsingNestedTransactionScopesWithRollback()
        {
            using (TransactionScope scope = new TransactionScope())
            {
                using (new TransactionScope(TransactionMode.Inherits))
                {
                    new SSAFEntity("example").Save();
                    Assert.AreEqual(1, SSAFEntity.FindAll().Count());
                }
                Assert.AreEqual(1, SSAFEntity.FindAll().Count());
                scope.VoteRollBack();
            }

            using (new SessionScope())
                Assert.AreEqual(0, SSAFEntity.FindAll().Count());
        }
        public void UsingTransactionScopeWithRollback()
        {
            SqlConnection conn = CreateSqlConnection();
            ISession session1, session2;
            ITransaction trans1, trans2;

            using(TransactionScope scope = new TransactionScope())
            {
                Blog blog = new Blog();
                blog.Name = "hammett's blog";
                blog.Author = "hamilton verissimo";
                blog.Save();

                session1 = blog.CurrentSession;
                trans1 = blog.CurrentSession.Transaction;
                Assert.IsNotNull(session1);
                Assert.IsNotNull(session1.Transaction);
                Assert.IsFalse(session1.Transaction.WasCommitted);
                Assert.IsFalse(session1.Transaction.WasRolledBack);

                conn.Open();

                using(new DifferentDatabaseScope(conn))
                {
                    blog.Create();

                    session2 = blog.CurrentSession;
                    trans2 = blog.CurrentSession.Transaction;
                    Assert.IsNotNull(session2);

                    Assert.IsFalse( Object.ReferenceEquals(session1, session2) );

                    Assert.IsNotNull(session2.Transaction);
                    Assert.IsFalse(session2.Transaction.WasCommitted);
                    Assert.IsFalse(session2.Transaction.WasRolledBack);

                    scope.VoteRollBack();
                }
            }

            Assert.IsFalse(session1.IsOpen);
            Assert.IsFalse(session2.IsOpen);
            Assert.IsFalse(trans1.WasCommitted);
            Assert.IsTrue(trans1.WasRolledBack);
            Assert.IsFalse(trans2.WasCommitted);
            Assert.IsTrue(trans2.WasRolledBack);

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

            OtherDbBlog[] blogs2 = OtherDbBlog.FindAll();
            Assert.IsNotNull( blogs2 );
            Assert.AreEqual( 0, blogs2.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 MixingSessionScopeAndTransactionScopes3()
		{
			ActiveRecordStarter.Initialize(GetConfigSource(), typeof(PostLazy), typeof(BlogLazy));
			Recreate();

			PostLazy.DeleteAll();
			BlogLazy.DeleteAll();

			BlogLazy b = new BlogLazy();

			using(new SessionScope())
			{
				b.Name = "a";
				b.Author = "x";
				b.Save();

				using(new TransactionScope())
				{
					for(int i = 1; i <= 10; i++)
					{
						PostLazy post = new PostLazy(b, "t", "c", "General");
						post.Save();
					}
				}
			}

			using(new SessionScope())
			{
				// We should load this outside the transaction scope

				b = BlogLazy.Find(b.Id);

				using(TransactionScope transaction = new TransactionScope())
				{
					int total = b.Posts.Count;

					foreach(PostLazy p in b.Posts)
					{
						p.Delete();
					}

					b.Delete();

					transaction.VoteRollBack();
				}
			}

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

			PostLazy[] posts = PostLazy.FindAll();
			Assert.AreEqual(10, posts.Length);
		}