/// <summary>
    /// 权限分配时,生成每个资源对应的权限
    /// </summary>
    public static MvcHtmlString DistributeOptions(this HtmlHelper helper, int moduleId)
    {
        StringBuilder strBuilder = new StringBuilder();
        string label = "<form class=\"js-form-permission\" name=\"setPermission\"><input type=\"checkbox\" class=\"js-checkall-permission\" style=\"margin-top:-2px\" data-toggle=\"tooltip\" data-placement=\"top\" data-original-title=\"全选\" /><label class=\"inline mr40 pl20\">{0}</label>";
        string checkbox = "<input type=\"checkbox\" name=\"{0}-{1}\" style=\"margin:-2px 8px 0 8px\" />{2}";
        using (DBEntity db = new DBEntity())
        {
            IEnumerable<Module> modules = db.Module.GetEntities(m => m.ParentId == moduleId);
            string[] operations = null;
            int actionId = 0;
            Operation operation = null;
            foreach (Module module in modules)
            {
                if (!string.IsNullOrWhiteSpace(module.Operations))
                {
                    strBuilder.AppendFormat(label, module.Name);
                    operations = module.Operations.Split(',');
                    foreach (string op in operations)
                    {
                        actionId = Convert.ToInt32(op);
                        operation = db.Operation.GetEntity(o => o.ID == actionId);
                        strBuilder.AppendFormat(checkbox, module.ID, operation.ID, operation.Name);
                    }
                    strBuilder.Append("</form><p></p>");
                }
            }
        }

        return MvcHtmlString.Create(strBuilder.ToString());
    }
        public ActionResult GetPermission(int id)
        {
            using (DBEntity db = new DBEntity())
            {
                var permissions = db.Permission.Where(p => p.RoleID == id)
                                    .Select(p => new { p.ControllerID, p.ActionID })
                                    .AsEnumerable();
                if (permissions.Count() == 0)
                {
                    return null;
                }
                else
                {
                    Dictionary<string, string> result = new Dictionary<string, string>();
                    string controllerId;
                    foreach (var permission in permissions)
                    {
                        controllerId = permission.ControllerID.ToString();
                        if (!result.ContainsKey(controllerId))
                        {
                            result.Add(controllerId, permission.ActionID.ToString());
                        }
                        else
                        {
                            result[controllerId] += permission.ActionID.ToString();
                        }
                    }

                    return Json(result, JsonRequestBehavior.AllowGet);
                }
            }
        }
    /// <summary>
    /// 生成用户功能菜单
    /// </summary>
    public static MvcHtmlString CreateMenu(this HtmlHelper helper)
    {
        using (DBEntity db = new DBEntity())
        {
            int roleID = 1;
            IEnumerable<UserBrowseViewModel> modules = db.GetUserBrowse(roleID).AsEnumerable();

            string parentMenu = "<a href=\"#{0}\" class=\"nav-header\" data-toggle=\"collapse\"><i class=\"ico-menu ico-{1}\"></i>{2}</a>";
            string childMenu = "<ul id=\"{0}\" class=\"nav nav-list collapse in\">{1}</ul>";
            string childContent = "<li><a target=\"content\" href=\"/{0}\"><i class=\"ico-menu ico-{1}\"></i>{2}</a></li>";

            IList<UserBrowseViewModel> parentModules = modules.GetEntities(m => m.ParentId == null).ToList();
            IEnumerable<Module> childModules = null;
            StringBuilder strBuilder = new StringBuilder();
            StringBuilder childBuilder = new StringBuilder();
            foreach (var parent in parentModules)
            {
                strBuilder.AppendFormat(parentMenu, parent.Name + "-menu", parent.Code, parent.Name);
                childModules = db.Module.GetEntities(m => m.ParentId == parent.ID);
                foreach (var child in childModules)
                {
                    childBuilder.AppendFormat(childContent, child.Url, child.Code, child.Name);
                }

                strBuilder.AppendFormat(childMenu, parent.Name + "-menu", childBuilder.ToString());
                childBuilder.Clear();
            }

            return MvcHtmlString.Create(strBuilder.ToString());
        }
    }
 public static void ToSaveEntity(RoleEditViewModel viewModel)
 {
     using (DBEntity db = new DBEntity())
     {
         Role role = db.Role.GetEntity(m => m.ID == viewModel.ID);
         role.Name = viewModel.Name;
         role.Remark = viewModel.Remark;
         role.IsEnable = int.Parse(viewModel.IsEnable) == 1 ? true : false;
         db.SaveChanges();
     }
 }
 public override void OnAuthorization(AuthorizationContext filterContext)
 {
     //ToTest
     //int roleID = Convert.ToInt32(HttpContext.Current.Session["RoleID"]);
     int roleID = 1;
     using (DBEntity db = new DBEntity())
     {
         IEnumerable<UserBrowseViewModel> modules = db.GetUserBrowse(roleID).AsEnumerable();
         foreach (UserBrowseViewModel module in modules)
         {
             filterContext.SetViewData(module.Code, module.Name);
         }
     }
 }
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        using (DBEntity db = new DBEntity())
        {
            //ToTest
            //int roleID = Convert.ToInt32(HttpContext.Current.Session["RoleID"]);
            int roleID = 1;

            string controller = filterContext.GetController();
            int controllerID = db.Module.GetEntityField(m => m.Controller == controller, m => m.ID);
            IEnumerable<string> actions = db.GetUserOperation(roleID, controllerID);
            foreach (string action in actions)
            {
                filterContext.SetViewData(action, true);
            }
        }
    }
    /// <summary>
    /// 生成权限操作选项
    /// </summary>
    public static MvcHtmlString Operations(this HtmlHelper helper)
    {
        using (DBEntity db = new DBEntity())
        {
            IDictionary<int, string> operations = db.Operation
                                                    .Select(s => new { s.ID, s.Name })
                                                    .AsEnumerable()
                                                    .ToDictionary(k => k.ID, k => k.Name);
            string label = "<label class=\"checkbox inline ml10\"><input type=\"checkbox\" id=\"op{0}\" name=\"op{0}\" />{1}</label>";
            StringBuilder strBuilder = new StringBuilder();
            foreach (KeyValuePair<int, string> item in operations)
            {
                strBuilder.AppendFormat(label, item.Key, item.Value);
            }

            return MvcHtmlString.Create(strBuilder.ToString());
        }
    }
        public ActionResult Index(string userName, string userPwd)
        {
            using (DBEntity db = new DBEntity())
            {
                //DB操作方法一:使用原生SQL
                //string sql = "select count(*) from User where Name='admin' and Password='******'";
                //db.ExecuteStoreQuery<int>(sql).FirstOrDefault();
                //db.ExecuteStoreCommand(sql);

                //DB操作方法二:使用参数化SQL
                //string sql = "select count(*) from User where Name=@Name and Password=@Password";
                //var args = new DbParameter[] { new SqlParameter { ParameterName = "Name", Value = "admin" }, new SqlParameter { ParameterName = "Password", Value = "admin" } };
                //db.ExecuteStoreQuery<User>(sql, args);

                //DB操作方法三:使用LINQ
                var user = (from u in db.User
                            join r in db.UserRole
                            on u.ID equals r.UserID
                            where (u.Name == userName && u.Password == userPwd)
                            select new 
                            {
                                UserID = u.ID,
                                RoleID = r.RoleID,
                                RealName = u.RealName,
                                UserName = u.Name
                            }).FirstOrDefault();
                if (user != null)
                {
                    Session.Add("UserId", user.UserID);
                    Session.Add("RoleId", user.RoleID);
                    Session.Add("RealName", user.RealName);
                    Session.Add("UserName", user.UserName);
                    return RedirectToAction("../Home/Index");
                }

                ViewBag.info = "用户名或密码输入错误,请重新输入!";
                return View();
            }
        }
 public ManageController()
 {
     db = new DBEntity();
     ViewBag.dataCount = this.DataCount;
     ViewBag.pageSize = this.PageSize;
 }