xmlroleprovider.cs

来自「个人博客系统」· CS 代码 · 共 465 行 · 第 1/2 页

CS
465
字号

            //Now that we know a xml file exists we can call it.
            ReadRoleDataStore();

            if (!RoleExists("Administrators") || !RoleExists("Editors"))
                AddUsersToRoles(_UserNames.ToArray(), _DefaultRolesToAdd);



            // Throw an exception if unrecognized attributes remain
            if (config.Count > 0)
            {
                string attr = config.GetKey(0);
                if (!String.IsNullOrEmpty(attr))
                    throw new ProviderException("Unrecognized attribute: " + attr);
            }


        }

        ///<summary>
        ///Adds the specified user names to the specified roles for the configured applicationName.
        ///</summary>
        ///
        ///<param name="roleNames">A string array of the role names to add the specified user names to. </param>
        ///<param name="usernames">A string array of user names to be added to the specified roles. </param>
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            List<string> currentRoles = new List<string>(GetAllRoles());
            if (usernames.Length != 0 && roleNames.Length != 0)
            {
                foreach (string _rolename in roleNames)
                {
                    if (!currentRoles.Contains(_rolename))
                    {
                        _Roles.Add(new Role(_rolename, new List<string>(usernames)));
                    }
                }

                foreach (Role role in _Roles)
                {
                    foreach (string _name in roleNames)
                    {
                        if (role.Name.ToLower() == _name.ToLower())
                        {
                            foreach (string s in usernames)
                            {
                                if (!role.Users.Contains(s))
                                    role.Users.Add(s);
                            }
                        }
                    }
                }
            }
            Save();
        }

        ///<summary>
        ///Removes the specified user names from the specified roles for the configured applicationName.
        ///</summary>
        ///
        ///<param name="roleNames">A string array of role names to remove the specified user names from. </param>
        ///<param name="usernames">A string array of user names to be removed from the specified roles. </param>
        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            if (usernames.Length != 0 && roleNames.Length != 0)
            {
                foreach (Role role in _Roles)
                {
                    foreach (string _name in roleNames)
                    {
                        if (role.Name.ToLower() == _name)
                        {
                            foreach (string user in usernames)
                            {
                                if (role.Name == "administrators")
                                {
                                    if (role.Users.Count != 1)
                                    {
                                        if (role.Users.Contains(user))
                                            role.Users.Remove(user);
                                    }
                                }
                                else
                                {
                                    if (role.Users.Contains(user))
                                        role.Users.Remove(user);
                                }
                            }

                        }
                    }
                }
            }
            Save();
        }

        ///<summary>
        ///Removes a role from the data source for the configured applicationName.
        ///</summary>
        ///
        ///<returns>
        ///true if the role was successfully deleted; otherwise, false.
        ///</returns>
        ///
        ///<param name="throwOnPopulatedRole">If true, throw an exception if roleName has one or more members and do not delete roleName.</param>
        ///<param name="roleName">The name of the role to delete.</param>
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            if (roleName != "administrators")
            {
                _Roles.Remove(new Role(roleName));
                Save();
                return true;
            }
            return false;
        }

        ///<summary>
        ///Adds a new role to the data source for the configured applicationName.
        ///</summary>
        ///
        ///<param name="roleName">The name of the role to create.</param>
        public override void CreateRole(string roleName)
        {
            if (!_Roles.Contains(new Core.Role(roleName)))
            {
                _Roles.Add(new Core.Role(roleName));
                Save();
            }

        }

        #endregion

        #region Helper methods

        /// <summary>
        /// Builds the internal cache of users.
        /// </summary>
        private void ReadRoleDataStore()
        {
            lock (this)
            {
                XmlDocument doc = new XmlDocument();

                try
                {
                    doc.Load(_XmlFileName);
                    XmlNodeList nodes = doc.GetElementsByTagName("role");
                    foreach (XmlNode roleNode in nodes)
                    {
                        Role tempRole = new Role(roleNode.SelectSingleNode("name").InnerText);
                        foreach (XmlNode userNode in roleNode.SelectNodes("users/user"))
                        {
                            tempRole.Users.Add(userNode.InnerText);
                        }
                        _Roles.Add(tempRole);

                    }
                }

                catch (XmlException)
                {
                    AddUsersToRoles(_UserNames.ToArray(), _DefaultRolesToAdd);
                }

            }
        }

        ///<summary>
        ///</summary>
        public void Save()
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;

            using (XmlWriter writer = XmlWriter.Create(_XmlFileName, settings))
            {
                writer.WriteStartDocument(true);
                writer.WriteStartElement("roles");

                foreach (Role _role in _Roles)
                {
                    writer.WriteStartElement("role");
                    writer.WriteElementString("name", _role.Name);
                    writer.WriteStartElement("users");
                    foreach (string username in _role.Users)
                    {
                        writer.WriteElementString("user", username);
                    }
                    writer.WriteEndElement(); //closes users
                    writer.WriteEndElement(); //closes role
                }
            }

        }

        /// <summary>
        /// Only so we can add users to the adminstrators and editors roles.
        /// </summary>
        private void ReadMembershipDataStore()
        {
            string fullyQualifiedPath = VirtualPathUtility.Combine
              (VirtualPathUtility.AppendTrailingSlash
              (HttpRuntime.AppDomainAppVirtualPath), BlogSettings.Instance.StorageLocation + "Users.xml");

            lock (this)
            {
                if (_UserNames == null)
                {
                    _UserNames = new List<string>();
                    XmlDocument doc = new XmlDocument();
                    doc.Load(HostingEnvironment.MapPath(fullyQualifiedPath));
                    XmlNodeList nodes = doc.GetElementsByTagName("User");

                    foreach (XmlNode node in nodes)
                    {
                        _UserNames.Add(node["UserName"].InnerText);
                    }

                }
            }
        }
        #endregion



    }


}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?