示例#1
0
        /// <summary>
        /// The method that executes to apply a migration.
        /// </summary>
        public override void Migrate()
        {
            var template = User.Template();

            var transaction = DatabaseSession.Instance.CreateTransaction();

            DatabaseSession.Instance.Connector.CreateTable(template, transaction);

            DatabaseSession.Instance.Connector.CreateColumn(typeof(User).GetProperty("Uuid"), template, transaction);
            DatabaseSession.Instance.Connector.CreateColumn(typeof(User).GetProperty("ModifiedOn"), template, transaction);
            DatabaseSession.Instance.Connector.CreateColumn(typeof(User).GetProperty("CreatedOn"), template, transaction);
            DatabaseSession.Instance.Connector.CreateColumn(typeof(User).GetProperty("Username"), template, transaction);
            DatabaseSession.Instance.Connector.CreateColumn(typeof(User).GetProperty("Email"), template, transaction);
            DatabaseSession.Instance.Connector.CreateColumn(typeof(User).GetProperty("Password"), template, transaction);
            DatabaseSession.Instance.Connector.CreateColumn(typeof(User).GetProperty("Salt"), template, transaction);
            DatabaseSession.Instance.Connector.CreateColumn(typeof(User).GetProperty("Usergroup"), template, transaction);

            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(template, transaction);

            // create foreign key contraint to usergroup
            var usergroupTemplate = Usergroup.Template();

            DatabaseSession.Instance.Connector.CreateForeignKeyConstraint(typeof(User).GetProperty("Usergroup"), template, typeof(Usergroup).GetProperty("Uuid"), usergroupTemplate, FkDeleteBehaviorKind.RESTRICT, transaction: transaction);

            DatabaseSession.Instance.CommitTransaction(transaction);
        }
        public void VerifyThatTransactionSafeDeleteTableWorks()
        {
            var fromObject = new User
            {
                Uuid = Guid.NewGuid(),
                Name = "John Doe"
            };

            var toObject = new Usergroup();

            Assert.Throws <InvalidDataException>(() => DatabaseSession.Instance.Connector.DeleteTable(fromObject));

            DatabaseSession.Instance.Connector.CreateTableWithColumns(fromObject);
            DatabaseSession.Instance.Connector.CreateTableWithColumns(toObject);
            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(fromObject);
            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(toObject);

            var transaction = DatabaseSession.Instance.CreateTransaction();

            DatabaseSession.Instance.Connector.CreateForeignKeyConstraint(fromObject.GetType().GetProperty("Usergroup_Id"), fromObject, toObject.GetType().GetProperty(toObject.PrimaryKey), toObject, FkDeleteBehaviorKind.CASCADE, true, transaction);
            DatabaseSession.Instance.Connector.DeleteForeignKeyConstraint(fromObject.GetType().GetProperty("Usergroup_Id"), fromObject, toObject.GetType().GetProperty(toObject.PrimaryKey), toObject, transaction);
            DatabaseSession.Instance.Connector.DeleteTable(fromObject, transaction);

            Assert.IsTrue(DatabaseSession.Instance.Connector.CheckTableExists(fromObject));

            DatabaseSession.Instance.Connector.DeleteTable(toObject, transaction);

            Assert.IsTrue(DatabaseSession.Instance.Connector.CheckTableExists(toObject));

            DatabaseSession.Instance.CommitTransaction(transaction);

            Assert.IsFalse(DatabaseSession.Instance.Connector.CheckTableExists(fromObject));
            Assert.IsFalse(DatabaseSession.Instance.Connector.CheckTableExists(toObject));
        }
        public async Task <IHttpActionResult> PutUsergroup(int id, Usergroup usergroup)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != usergroup.Pid)
            {
                return(BadRequest());
            }

            db.Entry(usergroup).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UsergroupExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
示例#4
0
        /// <summary>
        /// 由一行数据得到一个实体
        /// </summary>
        /// <param name="dr">SqlDataReader对象</param>
        /// <returns>实体对象</returns>
        private Usergroup GetModel(SqlDataReader dr)
        {
            Usergroup model = new Usergroup();

            model.ID                 = dbHelper.GetInt(dr["ID"]);
            model.Type               = dbHelper.GetByte(dr["Type"]);
            model.IsSystem           = dbHelper.GetByte(dr["IsSystem"]);
            model.GroupName          = dbHelper.GetString(dr["GroupName"]);
            model.Description        = dbHelper.GetString(dr["Description"]);
            model.CreditBegin        = dbHelper.GetInt(dr["CreditBegin"]);
            model.CreditEnd          = dbHelper.GetInt(dr["CreditEnd"]);
            model.stars              = dbHelper.GetByte(dr["stars"]);
            model.GroupAvatar        = dbHelper.GetString(dr["GroupAvatar"]);
            model.Readaccess         = dbHelper.GetInt(dr["Readaccess"]);
            model.AllowPost          = dbHelper.GetByte(dr["AllowPost"]);
            model.AllowComment       = dbHelper.GetByte(dr["AllowComment"]);
            model.AllowDownload      = dbHelper.GetByte(dr["AllowDownload"]);
            model.AllowAvatar        = dbHelper.GetByte(dr["AllowAvatar"]);
            model.AllowSpace         = dbHelper.GetByte(dr["AllowSpace"]);
            model.AllowTransfer      = dbHelper.GetByte(dr["AllowTransfer"]);
            model.AllowViewInfo      = dbHelper.GetByte(dr["AllowViewInfo"]);
            model.AllowNickname      = dbHelper.GetByte(dr["AllowNickname"]);
            model.MaxPMNum           = dbHelper.GetInt16(dr["MaxPMNum"]);
            model.MaxSignSize        = dbHelper.GetInt16(dr["MaxSignSize"]);
            model.MaxAttachSize      = dbHelper.GetInt(dr["MaxAttachSize"]);
            model.MaxAttachTotalSize = dbHelper.GetInt(dr["MaxAttachTotalSize"]);
            model.AttachExtension    = dbHelper.GetString(dr["AttachExtension"]);
            model.OrderID            = dbHelper.GetInt(dr["OrderID"]);
            return(model);
        }
示例#5
0
        /// <summary>
        /// 更新一条数据
        /// </summary>
        /// <param name="model">实体对象</param>
        /// <returns>返回影响行数</returns>
        public int Update(Usergroup model)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("UPDATE " + tablePrefix + "Usergroup SET ");
            strSql.Append("Type=@Type,");
            strSql.Append("IsSystem=@IsSystem,");
            strSql.Append("GroupName=@GroupName,");
            strSql.Append("Description=@Description,");
            strSql.Append("CreditBegin=@CreditBegin,");
            strSql.Append("CreditEnd=@CreditEnd,");
            strSql.Append("stars=@stars,");
            strSql.Append("GroupAvatar=@GroupAvatar,");
            strSql.Append("Readaccess=@Readaccess,");
            strSql.Append("AllowPost=@AllowPost,");
            strSql.Append("AllowComment=@AllowComment,");
            strSql.Append("AllowDownload=@AllowDownload,");
            strSql.Append("AllowAvatar=@AllowAvatar,");
            strSql.Append("AllowSpace=@AllowSpace,");
            strSql.Append("AllowTransfer=@AllowTransfer,");
            strSql.Append("AllowViewInfo=@AllowViewInfo,");
            strSql.Append("AllowNickname=@AllowNickname,");
            strSql.Append("MaxPMNum=@MaxPMNum,");
            strSql.Append("MaxSignSize=@MaxSignSize,");
            strSql.Append("MaxAttachSize=@MaxAttachSize,");
            strSql.Append("MaxAttachTotalSize=@MaxAttachTotalSize,");
            strSql.Append("AttachExtension=@AttachExtension,");
            strSql.Append("OrderID=@OrderID");
            strSql.Append(" WHERE ID=@ID");
            SqlParameter[] cmdParms =
            {
                AddInParameter("@Type",               SqlDbType.TinyInt,    1, model.Type),
                AddInParameter("@IsSystem",           SqlDbType.TinyInt,    1, model.IsSystem),
                AddInParameter("@GroupName",          SqlDbType.NVarChar,  50, model.GroupName),
                AddInParameter("@Description",        SqlDbType.NVarChar, 255, model.Description),
                AddInParameter("@CreditBegin",        SqlDbType.Int,        4, model.CreditBegin),
                AddInParameter("@CreditEnd",          SqlDbType.Int,        4, model.CreditEnd),
                AddInParameter("@stars",              SqlDbType.TinyInt,    1, model.stars),
                AddInParameter("@GroupAvatar",        SqlDbType.VarChar,  255, model.GroupAvatar),
                AddInParameter("@Readaccess",         SqlDbType.Int,        4, model.Readaccess),
                AddInParameter("@AllowPost",          SqlDbType.TinyInt,    1, model.AllowPost),
                AddInParameter("@AllowComment",       SqlDbType.TinyInt,    1, model.AllowComment),
                AddInParameter("@AllowDownload",      SqlDbType.TinyInt,    1, model.AllowDownload),
                AddInParameter("@AllowAvatar",        SqlDbType.TinyInt,    1, model.AllowAvatar),
                AddInParameter("@AllowSpace",         SqlDbType.TinyInt,    1, model.AllowSpace),
                AddInParameter("@AllowTransfer",      SqlDbType.TinyInt,    1, model.AllowTransfer),
                AddInParameter("@AllowViewInfo",      SqlDbType.TinyInt,    1, model.AllowViewInfo),
                AddInParameter("@AllowNickname",      SqlDbType.TinyInt,    1, model.AllowNickname),
                AddInParameter("@MaxPMNum",           SqlDbType.SmallInt,   2, model.MaxPMNum),
                AddInParameter("@MaxSignSize",        SqlDbType.SmallInt,   2, model.MaxSignSize),
                AddInParameter("@MaxAttachSize",      SqlDbType.Int,        4, model.MaxAttachSize),
                AddInParameter("@MaxAttachTotalSize", SqlDbType.Int,        4, model.MaxAttachTotalSize),
                AddInParameter("@AttachExtension",    SqlDbType.VarChar,  255, model.AttachExtension),
                AddInParameter("@OrderID",            SqlDbType.Int,        4, model.OrderID),
                AddInParameter("@ID",                 SqlDbType.Int,        4, model.ID)
            };

            return(dbHelper.ExecuteNonQuery(CommandType.Text, strSql.ToString(), cmdParms));
        }
 public ActionResult Edit(Usergroup model, Guid?[] formlist, Guid?[] DelList)
 {
     if (GlobalClass.SystemSession)
     {
         Usergroup abm = db.Usergroup.Find(model.UserGroupKey);
         abm.GroupName = model.GroupName;
         abm.GroupID   = model.GroupID;
         db.SaveChanges();
         if (formlist == null)
         {
         }
         else
         {
             if (formlist.Count() > 0)
             {
                 foreach (var item in formlist)
                 {
                     db = new HasanHoutoneEntities();
                     Forms f = db.Forms.Find(item);
                     CheckForModule(f.ModuleID, model.UserGroupKey);
                     UserGroupForm obj = new UserGroupForm();
                     obj.CompanyKey       = GlobalClass.Company.CompanyKey;
                     obj.ModuleKey        = f.ModuleID;
                     obj.UserGroupKey     = abm.UserGroupKey;
                     obj.UserGroupFormKey = Guid.NewGuid();
                     obj.FormKey          = item;
                     db.UserGroupForm.Add(obj);
                     db.SaveChanges();
                 }
             }
         }
         if (DelList == null)
         {
         }
         else
         {
             if (DelList.Count() > 0)
             {
                 foreach (var item in DelList)
                 {
                     db = new HasanHoutoneEntities();
                     UserGroupForm f = db.UserGroupForm.Find(item);
                     CheckForModuleBeforDelete(f);
                     db.UserGroupForm.Remove(f);
                     db.SaveChanges();
                 }
             }
         }
         return(RedirectToAction("Index"));
     }
     else
     {
         Exception e = new Exception("Sorry, your Session has Expired");
         return(View("Error", new HandleErrorInfo(e, "UserHome", "Logout")));
     }
 }
        /// <summary>
        /// The method that executes if a migration needs to be rolled back.
        /// </summary>
        public override void Reverse()
        {
            var template    = Usergroup.Template();
            var transaction = DatabaseSession.Instance.CreateTransaction();

            DatabaseSession.Instance.Connector.DeleteTable(template, transaction);

            // commit transaction
            DatabaseSession.Instance.Connector.CommitTransaction(transaction);
        }
        public async Task <Usergroup> GetUsergroup(int id)
        {
            Usergroup usergroup = await db.Usergroups.FindAsync(id);

            if (usergroup == null)
            {
                return(null);
            }

            return(usergroup);
        }
        public async Task <IHttpActionResult> PostUsergroup(Usergroup usergroup)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.Usergroups.Add(usergroup);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = usergroup.Pid }, usergroup));
        }
示例#10
0
 public ActionResult Edit(Guid id)
 {
     if (GlobalClass.SystemSession)
     {
         Usergroup obj = db.Usergroup.Find(id);
         return(View(obj));
     }
     else
     {
         Exception e = new Exception("Sorry, your Session has Expired");
         return(View("Error", new HandleErrorInfo(e, "UserHome", "Logout")));
     }
 }
        public async Task <IHttpActionResult> DeleteUsergroup(int id)
        {
            Usergroup usergroup = await db.Usergroups.FindAsync(id);

            if (usergroup == null)
            {
                return(NotFound());
            }

            db.Usergroups.Remove(usergroup);
            await db.SaveChangesAsync();

            return(Ok(usergroup));
        }
示例#12
0
        public Usergroup CreateGroup(int userId, string groupName)
        {
            var userGroup = new Usergroup()
            {
                AdminId   = userId,
                GroupName = groupName
            };

            var entry = _context.Usergroup.Add(userGroup);

            _context.SaveChanges();

            return(entry.Entity);
        }
示例#13
0
 protected void ShowLoginUser(ModAPI.Utils.WebService.User user)
 {
     Dispatcher.Invoke(delegate() {
         LoginButton.Visibility      = System.Windows.Visibility.Collapsed;
         LoginLoader.Visibility      = System.Windows.Visibility.Collapsed;
         LoggedIn.Visibility         = System.Windows.Visibility.Visible;
         UserAvatarLoader.Visibility = System.Windows.Visibility.Visible;
         System.Console.WriteLine(user.Usergroup);
         Usergroup.SetResourceReference(TextBlock.TextProperty, "Lang.UserGroup." + user.Usergroup);
         Username.Text       = user.Username;
         user.OnAvatarChange = AvatarChange;
         user.LoadAvatar();
     });
 }
示例#14
0
 public ActionResult Delete(Guid?id)
 {
     if (GlobalClass.SystemSession)
     {
         Usergroup company = db.Usergroup.Find(id);
         var       temp    = from x in db.UserGroupForm where x.UserGroupKey == id select x;
         var       temp2   = from x in db.UserGroupModule where x.UserGroupKey == id select x;
         var       temp3   = from x in db.StaffList where x.Usergr == id select x;
         if (temp.Count() > 0)
         {
             foreach (var a in temp)
             {
                 HasanHoutoneEntities ac   = new HasanHoutoneEntities();
                 UserGroupForm        form = db.UserGroupForm.Find(a.UserGroupFormKey);
                 ac.UserGroupForm.Remove(form);
                 ac.SaveChanges();
             }
         }
         if (temp3.Count() > 0)
         {
             foreach (var a in temp3)
             {
                 HasanHoutoneEntities ac   = new HasanHoutoneEntities();
                 StaffList            form = db.StaffList.Find(a.PersonnelKey);
                 form.Usergr = null;
                 ac.SaveChanges();
             }
         }
         if (temp2.Count() > 0)
         {
             foreach (var a in temp2)
             {
                 HasanHoutoneEntities ac   = new HasanHoutoneEntities();
                 UserGroupModule      form = db.UserGroupModule.Find(a.UserGroupModuleKey);
                 ac.UserGroupModule.Remove(form);
                 ac.SaveChanges();
             }
         }
         db.Usergroup.Remove(company);
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     else
     {
         Exception e = new Exception("Sorry, your Session has Expired");
         return(View("Error", new HandleErrorInfo(e, "UserHome", "Logout")));
     }
 }
示例#15
0
 public ActionResult Details(Guid id)
 {
     if (GlobalClass.SystemSession)
     {
         Usergroup company = db.Usergroup.Find(id);
         if (company == null)
         {
             return(HttpNotFound());
         }
         return(View(company));
     }
     else
     {
         Exception e = new Exception("Sorry, your Session has Expired");
         return(View("Error", new HandleErrorInfo(e, "UserHome", "Logout")));
     }
 }
        /// <summary>
        /// The method that executes to apply a migration.
        /// </summary>
        public override void Migrate()
        {
            var template = Usergroup.Template();

            var transaction = DatabaseSession.Instance.CreateTransaction();

            DatabaseSession.Instance.Connector.CreateTable(template, transaction);

            DatabaseSession.Instance.Connector.CreateColumn(typeof(Usergroup).GetProperty("Uuid"), template, transaction);
            DatabaseSession.Instance.Connector.CreateColumn(typeof(Usergroup).GetProperty("ModifiedOn"), template, transaction);
            DatabaseSession.Instance.Connector.CreateColumn(typeof(Usergroup).GetProperty("CreatedOn"), template, transaction);
            DatabaseSession.Instance.Connector.CreateColumn(typeof(Usergroup).GetProperty("Name"), template, transaction);
            DatabaseSession.Instance.Connector.CreateColumn(typeof(Usergroup).GetProperty("Permissions"), template, transaction);

            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(template, transaction);

            DatabaseSession.Instance.CommitTransaction(transaction);
        }
        /// <summary>
        /// The method that executes to apply a migration.
        /// </summary>
        public override void Migrate()
        {
            var claim     = new Claim();
            var usergroup = new Usergroup();
            var user      = new User();

            var transaction = DatabaseSession.Instance.CreateTransaction();

            DatabaseSession.Instance.Connector.CreateTableWithColumns(claim, transaction);
            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(claim, transaction);
            DatabaseSession.Instance.Connector.CreateTableWithColumns(usergroup, transaction);
            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(usergroup, transaction);
            DatabaseSession.Instance.Connector.CreateTableWithColumns(user, transaction);
            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(user, transaction);
            DatabaseSession.Instance.Connector.CreateUniquenessConstraint(new [] { user.GetType().GetProperty("UserName") }, user, transaction);
            DatabaseSession.Instance.Connector.CreateUniquenessConstraint(new[] { user.GetType().GetProperty("Email") }, user, transaction);

            DatabaseSession.Instance.Connector.CreateForeignKeyConstraint(user.GetType().GetProperty("UsergroupId"), user, usergroup.GetType().GetProperty("Id"), usergroup, transaction);

            DatabaseSession.Instance.CommitTransaction(transaction);
        }
        /// <summary>
        /// The method that executes to apply a migration.
        /// </summary>
        public override void Migrate()
        {
            var claim = new Claim();
            var usergroup = new Usergroup();
            var user = new User();

            var transaction = DatabaseSession.Instance.CreateTransaction();

            DatabaseSession.Instance.Connector.CreateTableWithColumns(claim, transaction);
            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(claim, transaction);
            DatabaseSession.Instance.Connector.CreateTableWithColumns(usergroup, transaction);
            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(usergroup, transaction);
            DatabaseSession.Instance.Connector.CreateTableWithColumns(user, transaction);
            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(user, transaction);
            DatabaseSession.Instance.Connector.CreateUniquenessConstraint(new []{ user.GetType().GetProperty("UserName") }, user, transaction);
            DatabaseSession.Instance.Connector.CreateUniquenessConstraint(new[] { user.GetType().GetProperty("Email") }, user, transaction);

            DatabaseSession.Instance.Connector.CreateForeignKeyConstraint(user.GetType().GetProperty("UsergroupId"),user, usergroup.GetType().GetProperty("Id"), usergroup, transaction);

            DatabaseSession.Instance.CommitTransaction(transaction);
        }
        public void VerifyThatOverridesAndForeignKeyConstraintsWork()
        {
            var fromObject = new User
            {
                Uuid = Guid.NewGuid(),
                Name = "John Doe"
            };

            var toObject = new Usergroup
            {
                Iid  = 1,
                Name = "Admin"
            };

            fromObject.Usergroup_Id = toObject.Iid;

            DatabaseSession.Instance.Connector.CreateTableWithColumns(toObject);
            DatabaseSession.Instance.Connector.CreateTableWithColumns(fromObject);

            Assert.Throws <InvalidDataException>(() => DatabaseSession.Instance.Connector.CreateForeignKeyConstraint(fromObject.GetType().GetProperty("Usergroup_Id"), fromObject, toObject.GetType().GetProperty(toObject.PrimaryKey), toObject));

            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(toObject);
            Assert.Throws <InvalidDataException>(
                () =>
                DatabaseSession.Instance.Connector.DeleteForeignKeyConstraint(
                    fromObject.GetType().GetProperty("Usergroup_Id"), fromObject,
                    toObject.GetType().GetProperty(toObject.PrimaryKey), toObject));

            Assert.DoesNotThrow(() => DatabaseSession.Instance.Connector.CreateForeignKeyConstraint(fromObject.GetType().GetProperty("Usergroup_Id"), fromObject, toObject.GetType().GetProperty(toObject.PrimaryKey), toObject));

            toObject.Save();

            Assert.DoesNotThrow(() => fromObject.Save());

            DatabaseSession.Instance.Connector.DeleteForeignKeyConstraint(fromObject.GetType().GetProperty("Usergroup_Id"), fromObject, toObject.GetType().GetProperty(toObject.PrimaryKey), toObject);

            Assert.DoesNotThrow(() => toObject.Delete());
            DatabaseSession.Instance.Connector.DeleteTable(new User());
            DatabaseSession.Instance.Connector.DeleteTable(new Usergroup());
        }
示例#20
0
        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            string role = txtRole.Text.Trim();

            if (MessageBox.Show($"Do you want to create role : {role}").DialogResult == DialogResult.OK)
            {
                Usergroup usergroup = new Usergroup()
                {
                    Name        = role,
                    UserGroupID = ""
                };
                string json    = JsonConvert.SerializeObject(usergroup);
                string url     = ApiRouting.GetUrl("", "", "usergroup", ApiFunction.Add).ToString();
                bool   confirm = url.Post <Usergroup>(json);
                if (confirm)
                {
                    MessageBox.Show($"User Role : {role} is successfully created.");
                    var obj = Singleton.Instance.Container.Resolve <MainView>("user role");
                    obj.Init();
                    this.Dispose();
                }
            }
        }
示例#21
0
        /// <summary>
        /// 增加一条数据
        /// </summary>
        /// <param name="ID">编号ID</param>
        /// <returns>返回影响行数</returns>
        public int Add(Usergroup model)
        {
            StringBuilder strSql = new StringBuilder();

            strSql.Append("INSERT INTO " + tablePrefix + "Usergroup(");
            strSql.Append("Type,IsSystem,GroupName,Description,CreditBegin,CreditEnd,stars,GroupAvatar,Readaccess,AllowPost,AllowComment,AllowDownload,AllowAvatar,AllowSpace,AllowTransfer,AllowViewInfo,AllowNickname,MaxPMNum,MaxSignSize,MaxAttachSize,MaxAttachTotalSize,AttachExtension,OrderID)");
            strSql.Append(" VALUES (");
            strSql.Append("@Type,@IsSystem,@GroupName,@Description,@CreditBegin,@CreditEnd,@stars,@GroupAvatar,@Readaccess,@AllowPost,@AllowComment,@AllowDownload,@AllowAvatar,@AllowSpace,@AllowTransfer,@AllowViewInfo,@AllowNickname,@MaxPMNum,@MaxSignSize,@MaxAttachSize,@MaxAttachTotalSize,@AttachExtension,@OrderID)");
            SqlParameter[] cmdParms =
            {
                AddInParameter("@Type",               SqlDbType.TinyInt,    1, model.Type),
                AddInParameter("@IsSystem",           SqlDbType.TinyInt,    1, model.IsSystem),
                AddInParameter("@GroupName",          SqlDbType.NVarChar,  50, model.GroupName),
                AddInParameter("@Description",        SqlDbType.NVarChar, 255, model.Description),
                AddInParameter("@CreditBegin",        SqlDbType.Int,        4, model.CreditBegin),
                AddInParameter("@CreditEnd",          SqlDbType.Int,        4, model.CreditEnd),
                AddInParameter("@stars",              SqlDbType.TinyInt,    1, model.stars),
                AddInParameter("@GroupAvatar",        SqlDbType.VarChar,  255, model.GroupAvatar),
                AddInParameter("@Readaccess",         SqlDbType.Int,        4, model.Readaccess),
                AddInParameter("@AllowPost",          SqlDbType.TinyInt,    1, model.AllowPost),
                AddInParameter("@AllowComment",       SqlDbType.TinyInt,    1, model.AllowComment),
                AddInParameter("@AllowDownload",      SqlDbType.TinyInt,    1, model.AllowDownload),
                AddInParameter("@AllowAvatar",        SqlDbType.TinyInt,    1, model.AllowAvatar),
                AddInParameter("@AllowSpace",         SqlDbType.TinyInt,    1, model.AllowSpace),
                AddInParameter("@AllowTransfer",      SqlDbType.TinyInt,    1, model.AllowTransfer),
                AddInParameter("@AllowViewInfo",      SqlDbType.TinyInt,    1, model.AllowViewInfo),
                AddInParameter("@AllowNickname",      SqlDbType.TinyInt,    1, model.AllowNickname),
                AddInParameter("@MaxPMNum",           SqlDbType.SmallInt,   2, model.MaxPMNum),
                AddInParameter("@MaxSignSize",        SqlDbType.SmallInt,   2, model.MaxSignSize),
                AddInParameter("@MaxAttachSize",      SqlDbType.Int,        4, model.MaxAttachSize),
                AddInParameter("@MaxAttachTotalSize", SqlDbType.Int,        4, model.MaxAttachTotalSize),
                AddInParameter("@AttachExtension",    SqlDbType.VarChar,  255, model.AttachExtension),
                AddInParameter("@OrderID",            SqlDbType.Int,        4, model.OrderID)
            };

            return(dbHelper.ExecuteNonQuery(CommandType.Text, strSql.ToString(), cmdParms));
        }
示例#22
0
            public void Execute(HtmlNode coreNode)
            {
                // Fetch the user title badges. User which do not belong to any group or do not have got any badges will be lacking of the 'rank' element in their profile page
                if (coreNode == null)
                {
                    return;
                }

                var rankNodes = new List <HtmlNode>(coreNode.ChildNodes.GetElementsByTagName("img")); // every rank badge got his very own 'img' element

                foreach (var node in rankNodes)
                {
                    if (!node.Attributes.Contains("src"))
                    {
                        continue;
                    }

                    var parsedRank = new Usergroup();
                    if (Usergroup.FromUrl(node.Attributes["src"].Value, out parsedRank)) // 'src' holds the url to the rank image
                    {
                        Target.Usergroups.Add(parsedRank);
                    }
                }
            }
        private void BtnSubmit_Click(object sender, EventArgs e)
        {
            string    group     = txtGroup.Text.Trim();
            Usergroup usergroup = new Usergroup()
            {
                Name        = group,
                UserGroupID = ""
            };
            string json    = JsonConvert.SerializeObject(usergroup);
            string url     = ApiRouting.GetUrl("", "", "usergroup", ApiFunction.Add).ToString();
            bool   confirm = url.Post <Usergroup>(json);

            if (confirm)
            {
                var obj = Singleton.Instance.Container.Resolve <MainView>("group");
                MessageBox.Show("Operation Successful", "Success");
                obj.Init();
                this.Dispose();
            }
            else
            {
                MessageBox.Show("Cannot Connect to Server!", "Success");
            }
        }
示例#24
0
        /// <summary>
        /// The method that executes if a migration needs to be rolled back.
        /// </summary>
        public override void Reverse()
        {
            var transaction = DatabaseSession.Instance.CreateTransaction();

            var UsergroupReferencePropertyInfo = typeof(User).GetProperty("Usergroup");
            var usergroupIdPropertyInfo        = typeof(Usergroup).GetProperty("Uuid");

            DatabaseSession.Instance.Connector.DeleteForeignKeyConstraint(UsergroupReferencePropertyInfo, User.Template(), usergroupIdPropertyInfo, Usergroup.Template(), transaction: transaction);
            DatabaseSession.Instance.CommitTransaction(transaction);
        }
示例#25
0
        public UsergroupsModule() : base("/admin")
        {
            this.RequiresAuthentication();
            this.RequiresClaims(new[] { "Users" });

            this.Get["/usergroups"] = x =>
            {
                this.Model.Usergroups = new UsergroupsModel();
                return(this.View["admin/Usergroups", this.Model]);
            };

            this.Get["/usergroups/{id:guid}"] = x =>
            {
                var usergroup = Usergroup.Find(Guid.Parse(x.id));

                if (usergroup == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                this.Model.Usergroup = usergroup;

                return(this.View["admin/usergroup", this.Model]);
            };

            this.Get["/usergroups/create"] = x =>
            {
                this.Model.Usergroup = new Usergroup();
                this.Model.Claims    = Claim.All();
                return(this.View["admin/UsergroupEdit", this.Model]);
            };

            this.Post["/usergroups/create"] = x =>
            {
                // do the save
                var name   = (string)this.Request.Form.Name;
                var claims = (string)this.Request.Form.Claims;

                var master = (MasterModel)this.Model.MasterModel;
                master.Errored = false;
                master.ErrorsList.Clear();

                var newUsergroup = new Usergroup()
                {
                    Id   = Guid.NewGuid(),
                    Name = name
                };

                var allUsergroups = Usergroup.All();

                if (string.IsNullOrWhiteSpace(newUsergroup.Name))
                {
                    master.ErrorsList.Add("The name must not be empty.");
                }

                if (allUsergroups.Any(u => u.Name.Equals(newUsergroup.Name)))
                {
                    master.ErrorsList.Add("The provided name is already taken.");
                }

                // set the claims
                newUsergroup.Claims = claims.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList().Select(Guid.Parse).ToList();

                // save

                if (master.ErrorsList.Any())
                {
                    master.Errored       = true;
                    this.Model.Usergroup = newUsergroup;
                    this.Model.Claims    = Claim.All();
                    var u = this.BindTo(newUsergroup);
                    return(this.View["admin/UsergroupEdit", this.Model]);
                }

                newUsergroup.Save();

                // redirect to the list
                return(this.Response.AsRedirect("/admin/usergroups"));
            };

            this.Get["/usergroups/{id:guid}/edit"] = x =>
            {
                var usergroup = Usergroup.Find(Guid.Parse(x.id));

                if (usergroup == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                this.Model.Usergroup = usergroup;
                this.Model.Claims    = Claim.All();

                return(this.View["admin/UsergroupEdit", this.Model]);
            };

            this.Post["/usergroups/{id:guid}/update"] = x =>
            {
                // do the save
                var name   = (string)this.Request.Form.Name;
                var claims = (string)this.Request.Form.Claims;

                var master = (MasterModel)this.Model.MasterModel;
                master.Errored = false;
                master.ErrorsList.Clear();

                var oldUsergroup = Usergroup.Find((Guid)x.Id);

                var allUsergroups = Usergroup.All();


                if (string.IsNullOrWhiteSpace(name))
                {
                    master.ErrorsList.Add("The name must not be empty.");
                }

                if (allUsergroups.Any(u => u.Name.Equals(name) && !u.Name.Equals(oldUsergroup.Name)))
                {
                    master.ErrorsList.Add("The provided name is already taken.");
                }

                oldUsergroup.Name = name;

                oldUsergroup.Claims = claims.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList().Select(Guid.Parse).ToList();

                // save
                if (master.ErrorsList.Any())
                {
                    master.Errored        = true;
                    this.Model.Usergroup  = oldUsergroup;
                    this.Model.Usergroups = Claim.All();
                    var u = this.BindTo(oldUsergroup);
                    return(this.View["admin/UsergroupEdit", this.Model]);
                }

                oldUsergroup.Save();

                // redirect to the list
                return(this.Response.AsRedirect("/admin/usergroups"));
            };

            this.Post["/usergroups/{id:guid}/remove"] = x =>
            {
                var usergroup = Usergroup.Find((Guid)x.id);

                if (usergroup == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                // remove the user

                try
                {
                    usergroup.Delete();
                }
                catch (InvalidDataException)
                {
                    var master = (MasterModel)this.Model.MasterModel;
                    master.Errored = true;
                    master.ErrorsList.Add("You cannot delete a usergroup that has members assigned.");

                    this.Model.Usergroups = new UsergroupsModel();
                    return(this.View["admin/Usergroups", this.Model]);
                }

                return(this.Response.AsRedirect("/admin/usergroups"));
            };
        }
        /// <summary>
        /// The seeds the database if needed. This method can be left empty.
        /// </summary>
        public override void Seed()
        {
            var adminUsergroup = new Usergroup
            {
                Uuid        = Guid.NewGuid(),
                Name        = "Administrator",
                CreatedOn   = DateTime.UtcNow,
                ModifiedOn  = DateTime.UtcNow,
                Permissions = new List <string> {
                    "CanAll"
                }
            };

            adminUsergroup.Save();

            // default admin passowrd
            var adminpassword = "******";

#if DEBUG
            var testUsergroup = new Usergroup
            {
                Uuid        = Guid.NewGuid(),
                Name        = "User",
                CreatedOn   = DateTime.UtcNow,
                ModifiedOn  = DateTime.UtcNow,
                Permissions = new List <string> {
                    "CanViewSome", "CanWriteSome"
                }
            };

            testUsergroup.Save();

            // for easy testing seed a simple password
            adminpassword = "******";
#endif
            var adminUser = new User
            {
                Uuid       = Guid.NewGuid(),
                Username   = "******",
                CreatedOn  = DateTime.UtcNow,
                ModifiedOn = DateTime.UtcNow,
                Email      = "*****@*****.**",
                Usergroup  = adminUsergroup.Uuid
            };

            adminUser.Salt     = CryptographyHelper.GetSalt();
            adminUser.Password = CryptographyHelper.Encrypt(adminpassword, adminUser.Salt);

            adminUser.Save();

#if DEBUG
            // seed some dummy users in debug
            for (var i = 0; i < 10; i++)
            {
                var user = new User
                {
                    Uuid       = Guid.NewGuid(),
                    Username   = $"user{i}",
                    CreatedOn  = DateTime.UtcNow,
                    ModifiedOn = DateTime.UtcNow,
                    Email      = $"bla{i}@bla.com",
                    Usergroup  = testUsergroup.Uuid
                };

                user.Salt     = CryptographyHelper.GetSalt();
                user.Password = CryptographyHelper.Encrypt(adminpassword, user.Salt);

                user.Save();
            }
#endif
        }
        /// <summary>
        /// Seeds the needed claims, usergroups and some users.
        /// </summary>
        public override void Seed()
        {
            var usergroupClaim = new Claim
            {
                Name = "Usergroups",
                Id = Guid.NewGuid(),
                Description = "Allows for viewing and editing of Usergroups."
            };

            usergroupClaim.Save();

            var userClaim = new Claim
            {
                Name = "Users",
                Id = Guid.NewGuid(),
                Description = "Allows for viewing and editing the Users."
            };

            userClaim.Save();

            var adminSectionClaim = new Claim
            {
                Name = "AdminOverview",
                Id = Guid.NewGuid(),
                Description = "Grants access to to the Administration section of the application."
            };

            adminSectionClaim.Save();

            var logClaim = new Claim
            {
                Name = "Log",
                Id = Guid.NewGuid(),
                Description = "Allows for viewing the Log."
            };

            logClaim.Save();

            var adminUsergroup = new Usergroup()
            {
                Name = "Administrator",
                Id = Guid.NewGuid()
            };

            adminUsergroup.Claims.Add(adminSectionClaim.Id);
            adminUsergroup.Claims.Add(usergroupClaim.Id);
            adminUsergroup.Claims.Add(userClaim.Id);
            adminUsergroup.Claims.Add(logClaim.Id);
            adminUsergroup.Save();

            var userUsergroup = new Usergroup()
            {
                Name = "User",
                Id = Guid.NewGuid()
            };

            userUsergroup.Save();

            var adminUser = new User
            {
                DateRegistered = DateTime.Now,
                Email = "*****@*****.**",
                Password = "******",
                Id = Guid.NewGuid(),
                UserName = "******",
                UsergroupId = adminUsergroup.Id
            };

            adminUser.EncodePassword();

            adminUser.Save();

            #if DEBUG
            var normalUser = new User
            {
                DateRegistered = DateTime.Now,
                Email = "*****@*****.**",
                Password = "******",
                Id = Guid.NewGuid(),
                UserName = "******",
                UsergroupId = userUsergroup.Id
            };

            normalUser.EncodePassword();
            normalUser.Save();
            #endif
        }
        public void VerifyThatTransactionSafeDeleteTableWorks()
        {
            var fromObject = new User
            {
                Id = Guid.NewGuid(),
                Name = "John Doe"
            };

            var toObject = new Usergroup();

            Assert.Throws<InvalidDataException>(() => DatabaseSession.Instance.Connector.DeleteTable(fromObject));

            DatabaseSession.Instance.Connector.CreateTableWithColumns(fromObject);
            DatabaseSession.Instance.Connector.CreateTableWithColumns(toObject);
            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(fromObject);
            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(toObject);

            var transaction = DatabaseSession.Instance.CreateTransaction();

            DatabaseSession.Instance.Connector.CreateForeignKeyConstraint(fromObject.GetType().GetProperty("Usergroup_Id"), fromObject, toObject.GetType().GetProperty(toObject.PrimaryKey), toObject, transaction);
            DatabaseSession.Instance.Connector.DeleteForeignKeyConstraint(fromObject.GetType().GetProperty("Usergroup_Id"), fromObject, toObject.GetType().GetProperty(toObject.PrimaryKey), toObject, transaction);
            DatabaseSession.Instance.Connector.DeleteTable(fromObject, transaction);

            Assert.IsTrue(DatabaseSession.Instance.Connector.CheckTableExists(fromObject));

            DatabaseSession.Instance.Connector.DeleteTable(toObject, transaction);

            Assert.IsTrue(DatabaseSession.Instance.Connector.CheckTableExists(toObject));

            DatabaseSession.Instance.CommitTransaction(transaction);

            Assert.IsFalse(DatabaseSession.Instance.Connector.CheckTableExists(fromObject));
            Assert.IsFalse(DatabaseSession.Instance.Connector.CheckTableExists(toObject));
        }
        public void VerifyThatOverridesAndForeignKeyConstraintsWork()
        {
            var fromObject = new User
            {
                Id = Guid.NewGuid(),
                Name = "John Doe"
            };

            var toObject = new Usergroup
            {
                Iid = 1,
                Name = "Admin"
            };

            fromObject.Usergroup_Id = toObject.Iid;

            DatabaseSession.Instance.Connector.CreateTableWithColumns(toObject);
            DatabaseSession.Instance.Connector.CreateTableWithColumns(fromObject);

            Assert.Throws<InvalidDataException>(() => DatabaseSession.Instance.Connector.CreateForeignKeyConstraint(fromObject.GetType().GetProperty("Usergroup_Id"), fromObject, toObject.GetType().GetProperty(toObject.PrimaryKey), toObject));

            DatabaseSession.Instance.Connector.CreatePrimaryKeyConstraint(toObject);
            Assert.Throws<InvalidDataException>(
                () =>
                    DatabaseSession.Instance.Connector.DeleteForeignKeyConstraint(
                        fromObject.GetType().GetProperty("Usergroup_Id"), fromObject,
                        toObject.GetType().GetProperty(toObject.PrimaryKey), toObject));

            Assert.DoesNotThrow(() => DatabaseSession.Instance.Connector.CreateForeignKeyConstraint(fromObject.GetType().GetProperty("Usergroup_Id"), fromObject, toObject.GetType().GetProperty(toObject.PrimaryKey), toObject));

            Assert.Throws<InvalidDataException>(() => fromObject.Save());

            toObject.Save();

            Assert.DoesNotThrow(() => fromObject.Save());

            Assert.Throws<InvalidDataException>(() => toObject.Delete());

            DatabaseSession.Instance.Connector.DeleteForeignKeyConstraint(fromObject.GetType().GetProperty("Usergroup_Id"), fromObject, toObject.GetType().GetProperty(toObject.PrimaryKey), toObject);

            Assert.DoesNotThrow(() => toObject.Delete());
            DatabaseSession.Instance.Connector.DeleteTable(new User());
            DatabaseSession.Instance.Connector.DeleteTable(new Usergroup());
        }
示例#30
0
        /// <summary>
        /// Usergroup module
        /// </summary>
        public UsergroupModule()
        {
            // get
            this.Get(
                "/Usergroup",
                x =>
            {
                var entity = "Usergroup";

                var type = ApiHelper.GetEntityTypeFromName(@"Redshift.Seed.Model", entity, "Redshift.Seed");

                List <Attribute> attributes;

                var typeErrors =
                    ApiHelper.GetTypeErrors(this.Negotiate, entity, type, out attributes, this.Context);

                if (typeErrors != null)
                {
                    return(typeErrors);
                }

                List <Usergroup> resp;
                QueryParameterContainer queryParams;
                var count = -1L;

                try
                {
                    queryParams = this.ProcessQueryParameters(this.Request, type);
                }
                catch (Exception)
                {
                    return(ApiHelper.ConstructFailResponse(
                               this.Negotiate,
                               entity,
                               "The query parameters are badly formatted and cannot be parsed.",
                               this.Context,
                               HttpStatusCode.BadRequest));
                }

                try
                {
                    if (queryParams.IsFiltered && !queryParams.IsPaginated)
                    {
                        resp = Usergroup.Where(queryParams.FilterList, true, null, null, queryParams.OrderProperty,
                                               queryParams.IsDescending);

                        if (queryParams.IsCountExpected)
                        {
                            // all entities are already queried and in memory so simple count is fine
                            count = resp.Count;
                        }
                    }
                    else if (queryParams.IsPaginated)
                    {
                        // when paginating, always return count
                        queryParams.IsCountExpected = true;

                        resp = Usergroup.Where(queryParams.FilterList, true, queryParams.Limit, queryParams.Offset,
                                               queryParams.OrderProperty, queryParams.IsDescending);

                        // paginated response provide count always and the count is of total filtered records
                        count = Usergroup.CountWhere(queryParams.FilterList);
                    }
                    else
                    {
                        resp = Usergroup.Where(queryParams.FilterList, true, null, null, null, true);

                        if (queryParams.IsCountExpected)
                        {
                            // all entities are already queried and in memory so simple count is fine
                            count = resp.Count;
                        }
                    }
                }
                catch (Exception e)
                {
                    return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
                }

                var response = new ResponseContainer();
                response.AddToResponse(resp);

                // add count to the response
                if (queryParams.IsCountExpected)
                {
                    response.Add("count", new List <object> {
                        count
                    });
                }

                return(ApiHelper.ConstructSuccessResponse(this.Negotiate, response, this.Context));
            });

            this.Get(
                "/Usergroup/{uuid:guid}",
                x =>
            {
                // parse id
                var uuid = ApiHelper.GetIdFromString(x.uuid.ToString());

                if (uuid == null)
                {
                    return(ApiHelper.ConstructFailResponse(
                               this.Negotiate,
                               "uuid",
                               string.Format("The requested uuid {0} cannot be parsed.", x.uuid),
                               this.Context,
                               HttpStatusCode.BadRequest));
                }

                // parse entity
                var entity = "Usergroup";

                var type = ApiHelper.GetEntityTypeFromName(@"Redshift.Seed.Model", entity, "Redshift.Seed");

                List <Attribute> attributes;
                var typeErrors =
                    ApiHelper.GetTypeErrors(this.Negotiate, entity, type, out attributes, this.Context);

                if (typeErrors != null)
                {
                    return(typeErrors);
                }

                // acquire the response
                Usergroup resp;

                try
                {
                    resp = Usergroup.Find(uuid);
                }
                catch (Exception e)
                {
                    return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
                }

                if (resp == null)
                {
                    return(ApiHelper.ConstructFailResponse(
                               this.Negotiate,
                               "uuid",
                               string.Format("The requested {1} with id {0} does not exist.", uuid, entity),
                               this.Context));
                }

                var response = new ResponseContainer();
                response.AddToResponse(resp);

                return(ApiHelper.ConstructSuccessResponse(this.Negotiate, response, this.Context));
            });

            this.Post(
                "/Usergroup",
                x =>
            {
                var postBody = RequestStream.FromStream(this.Request.Body).AsString();

                var entity = "Usergroup";
                var type   = ApiHelper.GetEntityTypeFromName(@"Redshift.Seed.Model", entity, "Redshift.Seed");

                List <Attribute> attributes;

                var typeErrors = ApiHelper.GetTypeErrors(
                    this.Negotiate,
                    entity,
                    type,
                    out attributes,
                    this.Context);

                if (typeErrors != null)
                {
                    return(typeErrors);
                }

                // demoinstrates a way to generalize
                return(this.PerformSimplePost(type, postBody));
            });

            this.Put(
                "/Usergroup/{uuid:guid}",
                x =>
            {
                var uuid    = ApiHelper.GetIdFromString(x.uuid.ToString());
                var putBody = RequestStream.FromStream(Request.Body).AsString();

                var entity = "Usergroup";
                var type   = ApiHelper.GetEntityTypeFromName(@"Redshift.Seed.Model", entity, "Redshift.Seed");

                var typeErrors = ApiHelper.GetTypeErrors(
                    this.Negotiate,
                    entity,
                    type,
                    out var attributes,
                    this.Context);

                if (typeErrors != null)
                {
                    return(typeErrors);
                }

                IEntityObject savedResp;

                try
                {
                    // acquire the response
                    Usergroup resp;

                    try
                    {
                        resp = Usergroup.Find(uuid);

                        if (resp != null)
                        {
                            try
                            {
                                JsonConvert.PopulateObject(
                                    putBody,
                                    resp);

                                // make sure the uuid is set correctly/not being changed.
                                resp.Uuid = uuid;
                            }
                            catch (Exception e)
                            {
                                return(ApiHelper.ConstructFailResponse(this.Negotiate, "update",
                                                                       "The request was not properly formatted and could not be used to update the object!",
                                                                       this.Context, HttpStatusCode.BadRequest, e));
                            }
                        }
                        else
                        {
                            // if there is an object of this type in the database then this POST is invalid
                            return(ApiHelper.ConstructFailResponse(
                                       this.Negotiate,
                                       type.Name,
                                       "An object with this Uuid does not exist and cannot be updated!",
                                       this.Context,
                                       HttpStatusCode.NotFound));
                        }
                    }
                    catch (Exception e)
                    {
                        return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
                    }

                    var transaction = DatabaseSession.Instance.CreateTransaction();
                    savedResp       = resp.Save(transaction: transaction);
                    DatabaseSession.Instance.CommitTransaction(transaction);
                }
                catch (Exception e)
                {
                    return(ApiHelper.ConstructErrorResponse(this.Negotiate, e, this.Context));
                }

                var container = new ResponseContainer();
                container.AddToResponse(savedResp);

                return(ApiHelper.ConstructSuccessResponse(this.Negotiate, container, this.Context));
            });
示例#31
0
        public UsersModule() : base("/admin")
        {
            this.RequiresAuthentication();
            this.RequiresClaims(new[] { "Users" });

            this.Get["/users"] = x =>
            {
                this.Model.Users = new UsersModel();
                return(this.View["admin/Users", this.Model]);
            };

            this.Get["/users/{id:guid}"] = x =>
            {
                var user = User.Find(Guid.Parse(x.id));

                if (user == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                this.Model.User = user;

                return(this.View["admin/user", this.Model]);
            };

            this.Get["/users/create"] = x =>
            {
                this.Model.User       = new User();
                this.Model.Usergroups = Usergroup.All();
                return(this.View["admin/UserEdit", this.Model]);
            };

            this.Post["/users/create"] = x =>
            {
                // do the save
                var username      = (string)this.Request.Form.UserName;
                var email         = (string)this.Request.Form.Email;
                var password      = (string)this.Request.Form.Password;
                var passwordValid = (string)this.Request.Form.PasswordValidation;
                var usergroup     = Guid.Parse((string)this.Request.Form.Usergroup);

                var master = (MasterModel)this.Model.MasterModel;
                master.Errored = false;
                master.ErrorsList.Clear();

                var newUser = new User()
                {
                    Id          = Guid.NewGuid(),
                    UserName    = username,
                    Email       = email,
                    Password    = password,
                    UsergroupId = usergroup
                };

                newUser.EncodePassword();

                var allUsers = User.All();

                if (string.IsNullOrWhiteSpace(newUser.UserName))
                {
                    master.ErrorsList.Add("The username must not be empty.");
                }

                if (allUsers.Any(u => u.UserName.Equals(newUser.UserName)))
                {
                    master.ErrorsList.Add("The provided username is already taken.");
                }

                if (string.IsNullOrWhiteSpace(newUser.Email))
                {
                    master.ErrorsList.Add("The email must not be empty.");
                }

                if (allUsers.Any(u => u.Email.Equals(newUser.Email)))
                {
                    master.ErrorsList.Add("The provided email is already taken.");
                }

                if (string.IsNullOrWhiteSpace(newUser.Password))
                {
                    master.ErrorsList.Add("The password must not be empty.");
                }

                if (!newUser.Password.Equals(passwordValid))
                {
                    master.ErrorsList.Add("The passwords do not match.");
                }

                // save

                if (master.ErrorsList.Any())
                {
                    master.Errored        = true;
                    this.Model.User       = newUser;
                    this.Model.Usergroups = Usergroup.All();
                    var u = this.BindTo(newUser, "Password");
                    return(this.View["admin/UserEdit", this.Model]);
                }

                newUser.Save();


                // redirect to the list
                return(this.Response.AsRedirect("/admin/users"));
            };

            this.Get["/users/{id:guid}/edit"] = x =>
            {
                var user = User.Find(Guid.Parse(x.id));

                if (user == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                this.Model.User       = user;
                this.Model.Usergroups = Usergroup.All();

                return(this.View["admin/UserEdit", this.Model]);
            };

            this.Post["/users/{id:guid}/update"] = x =>
            {
                // do the save
                var username      = (string)this.Request.Form.UserName;
                var email         = (string)this.Request.Form.Email;
                var password      = (string)this.Request.Form.Password;
                var passwordValid = (string)this.Request.Form.PasswordValidation;
                var usergroup     = Guid.Parse((string)this.Request.Form.Usergroup);

                var master = (MasterModel)this.Model.MasterModel;
                master.Errored = false;
                master.ErrorsList.Clear();

                var oldUser = User.Find((Guid)x.Id);

                var allUsers = User.All();


                if (string.IsNullOrWhiteSpace(username))
                {
                    master.ErrorsList.Add("The username must not be empty.");
                }

                if (allUsers.Any(u => u.UserName.Equals(username) && !u.UserName.Equals(oldUser.UserName)))
                {
                    master.ErrorsList.Add("The provided username is already taken.");
                }

                oldUser.UserName = username;

                if (string.IsNullOrWhiteSpace(oldUser.Email))
                {
                    master.ErrorsList.Add("The email must not be empty.");
                }

                if (allUsers.Any(u => !u.Email.Equals(oldUser.Email) && u.Email.Equals(email)))
                {
                    master.ErrorsList.Add("The provided email is already taken.");
                }

                oldUser.Email = email;

                if (!string.IsNullOrWhiteSpace(password))
                {
                    if (!password.Equals(passwordValid))
                    {
                        master.ErrorsList.Add("The passwords do not match.");
                    }
                    else
                    {
                        oldUser.Password = password;
                        oldUser.EncodePassword();
                    }
                }

                oldUser.UsergroupId = usergroup;

                // save
                if (master.ErrorsList.Any())
                {
                    master.Errored        = true;
                    this.Model.User       = oldUser;
                    this.Model.Usergroups = Usergroup.All();
                    var u = this.BindTo(oldUser, "Password");
                    return(this.View["admin/UserEdit", this.Model]);
                }

                oldUser.Save();

                // redirect to the list
                return(this.Response.AsRedirect("/admin/users"));
            };

            this.Post["/users/{id:guid}/remove"] = x =>
            {
                var user = User.Find((Guid)x.id);

                if (user == null)
                {
                    return(HttpStatusCode.NotFound);
                }

                // remove the user
                user.Delete();

                return(this.Response.AsRedirect("/admin/users"));
            };
        }
示例#32
0
 /// <summary>
 /// 更新一条数据
 /// </summary>
 /// <param name="model">实体对象</param>
 /// <returns>返回影响行数</returns>
 public int Update(Usergroup model)
 {
     return(dal.Update(model));
 }
示例#33
0
 /// <summary>
 /// 增加一条数据
 /// </summary>
 /// <param name="model">实体对象</param>
 /// <returns>返回影响行数</returns>
 public int Add(Usergroup model)
 {
     return(dal.Add(model));
 }
示例#34
0
        public IActionResult CreateGroup(int userId, string groupName)
        {
            Usergroup usergroup = _userService.CreateGroup(userId, groupName);

            return(Ok(usergroup));
        }
示例#35
0
            internal static void UsergroupUpdated(Usergroup Usergroup)
            {
                if (Services.Events.UsergroupUpdated != null)
                {
                    List<object> sender = new List<object>();
                    sender.Add (Usergroup);

                    Services.Events.UsergroupUpdated (sender, new EventArgs ());
                }
            }
        public UsergroupsModule()
            : base("/admin")
        {
            this.RequiresAuthentication();
            this.RequiresClaims(new[] {"Users"});

            this.Get["/usergroups"] = x =>
            {
                this.Model.Usergroups = new UsergroupsModel();
                return this.View["admin/Usergroups", this.Model];
            };

            this.Get["/usergroups/{id:guid}"] = x =>
            {
                var usergroup = Usergroup.Find(Guid.Parse(x.id));

                if (usergroup == null)
                {
                    return HttpStatusCode.NotFound;
                }

                this.Model.Usergroup = usergroup;

                return this.View["admin/usergroup", this.Model];
            };

            this.Get["/usergroups/create"] = x =>
            {
                this.Model.Usergroup = new Usergroup();
                this.Model.Claims = Claim.All();
                return this.View["admin/UsergroupEdit", this.Model];
            };

            this.Post["/usergroups/create"] = x =>
            {
                // do the save
                var name = (string)this.Request.Form.Name;
                var claims = (string)this.Request.Form.Claims;

                var master = (MasterModel)this.Model.MasterModel;
                master.Errored = false;
                master.ErrorsList.Clear();

                var newUsergroup = new Usergroup()
                {
                    Id = Guid.NewGuid(),
                    Name = name
                };

                var allUsergroups = Usergroup.All();

                if (string.IsNullOrWhiteSpace(newUsergroup.Name))
                {
                    master.ErrorsList.Add("The name must not be empty.");
                }

                if (allUsergroups.Any(u => u.Name.Equals(newUsergroup.Name)))
                {
                    master.ErrorsList.Add("The provided name is already taken.");
                }

                // set the claims
                newUsergroup.Claims = claims.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).ToList().Select(Guid.Parse).ToList();

                // save

                if (master.ErrorsList.Any())
                {
                    master.Errored = true;
                    this.Model.Usergroup = newUsergroup;
                    this.Model.Claims = Claim.All();
                    var u = this.BindTo(newUsergroup);
                    return this.View["admin/UsergroupEdit", this.Model];
                }

                newUsergroup.Save();

                // redirect to the list
                return this.Response.AsRedirect("/admin/usergroups");
            };

            this.Get["/usergroups/{id:guid}/edit"] = x =>
            {
                var usergroup = Usergroup.Find(Guid.Parse(x.id));

                if (usergroup == null)
                {
                    return HttpStatusCode.NotFound;
                }

                this.Model.Usergroup = usergroup;
                this.Model.Claims = Claim.All();

                return this.View["admin/UsergroupEdit", this.Model];
            };

            this.Post["/usergroups/{id:guid}/update"] = x =>
            {
                // do the save
                var name = (string)this.Request.Form.Name;
                var claims = (string)this.Request.Form.Claims;

                var master = (MasterModel)this.Model.MasterModel;
                master.Errored = false;
                master.ErrorsList.Clear();

                var oldUsergroup = Usergroup.Find((Guid)x.Id);

                var allUsergroups = Usergroup.All();

                if (string.IsNullOrWhiteSpace(name))
                {
                    master.ErrorsList.Add("The name must not be empty.");
                }

                if (allUsergroups.Any(u => u.Name.Equals(name) && !u.Name.Equals(oldUsergroup.Name)))
                {
                    master.ErrorsList.Add("The provided name is already taken.");
                }

                oldUsergroup.Name = name;

                oldUsergroup.Claims = claims.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList().Select(Guid.Parse).ToList();

                // save
                if (master.ErrorsList.Any())
                {
                    master.Errored = true;
                    this.Model.Usergroup = oldUsergroup;
                    this.Model.Usergroups = Claim.All();
                    var u = this.BindTo(oldUsergroup);
                    return this.View["admin/UsergroupEdit", this.Model];
                }

                oldUsergroup.Save();

                // redirect to the list
                return this.Response.AsRedirect("/admin/usergroups");
            };

            this.Post["/usergroups/{id:guid}/remove"] = x =>
            {
                var usergroup = Usergroup.Find((Guid)x.id);

                if (usergroup == null)
                {
                    return HttpStatusCode.NotFound;
                }

                // remove the user

                try
                {
                    usergroup.Delete();
                }
                catch (InvalidDataException)
                {
                    var master = (MasterModel)this.Model.MasterModel;
                    master.Errored = true;
                    master.ErrorsList.Add("You cannot delete a usergroup that has members assigned.");

                    this.Model.Usergroups = new UsergroupsModel();
                    return this.View["admin/Usergroups", this.Model];
                }

                return this.Response.AsRedirect("/admin/usergroups");
            };
        }