⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xmlroleprovider.cs

📁 个人博客系统
💻 CS
📖 第 1 页 / 共 2 页
字号:
// Written by: Roman D. Clarkson
// http://www.romanclarkson.com  inspirit@romanclarkson.com


using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Globalization;
using System.IO;
using System.Security.Permissions;
using System.Web;
using System.Web.Hosting;
using System.Web.Security;
using System.Xml;
using System.Xml.Serialization;
using BlogEngine.Core;

namespace BlogEngine.Core.Providers
{
    ///<summary>
    ///</summary>
    public class XmlRoleProvider : RoleProvider
    {
        private static string _Folder = HttpContext.Current.Server.MapPath(BlogSettings.Instance.StorageLocation);

        #region Properties

        private List<Role> _Roles = new List<Role>();
        private List<string> _UserNames;
        private string _XmlFileName;
        readonly string[] _DefaultRolesToAdd = new string[] { "Administrators", "Editors" };


        ///<summary>
        ///Gets or sets the name of the application to store and retrieve role information for.
        ///</summary>
        ///
        ///<returns>
        ///The name of the application to store and retrieve role information for.
        ///</returns>
        ///
        public override string ApplicationName
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        ///<summary>
        ///Gets a value indicating whether the specified role name already exists in the role data source for the configured applicationName.
        ///</summary>
        ///
        ///<returns>
        ///true if the role name already exists in the data source for the configured applicationName; otherwise, false.
        ///</returns>
        ///
        ///<param name="roleName">The name of the role to search for in the data source. </param>
        public override bool RoleExists(string roleName)
        {
            List<string> currentRoles = new List<string>(GetAllRoles());
            return (currentRoles.Contains(roleName)) ? true : false;
        }

        ///<summary>
        ///Gets a list of all the roles for the configured applicationName.
        ///</summary>
        ///
        ///<returns>
        ///A string array containing the names of all the roles stored in the data source for the configured applicationName.
        ///</returns>
        ///
        public override string[] GetAllRoles()
        {
            List<string> allRoles = new List<string>();
            foreach (Role role in _Roles)
            {
                allRoles.Add(role.Name);
            }
            return allRoles.ToArray();
        }

        ///<summary>
        ///Gets a list of users in the specified role for the configured applicationName.
        ///</summary>
        ///
        ///<returns>
        ///A string array containing the names of all the users who are members of the specified role for the configured applicationName.
        ///</returns>
        ///
        ///<param name="roleName">The name of the role to get the list of users for. </param>
        public override string[] GetUsersInRole(string roleName)
        {
            //  ReadRoleDataStore();
            List<string> UsersInRole = new List<string>();

            foreach (Role role in _Roles)
            {
                if (role.Name.ToLower() == roleName.ToLower())
                {
                    foreach (string user in role.Users)
                    {
                        UsersInRole.Add(user.ToLower());
                    }
                }
            }
            return UsersInRole.ToArray();
        }

        ///<summary>
        ///Gets a value indicating whether the specified user is in the specified role for the configured applicationName.
        ///</summary>
        ///
        ///<returns>
        ///true if the specified user is in the specified role for the configured applicationName; otherwise, false.
        ///</returns>
        ///
        ///<param name="username">The user name to search for.</param>
        ///<param name="roleName">The role to search in.</param>
        public override bool IsUserInRole(string username, string roleName)
        {
            //  ReadRoleDataStore();
            List<string> UsersInRole = new List<string>();

            foreach (Role role in _Roles)
            {
                if (role.Name.ToLower() == roleName.ToLower())
                {
                    foreach (string user in role.Users)
                    {
                        if (user == username)
                            return true;
                    }
                }
            }
            return false;
        }

        ///<summary>
        ///Gets a list of the roles that a specified user is in for the configured applicationName.
        ///</summary>
        ///
        ///<returns>
        ///A string array containing the names of all the roles that the specified user is in for the configured applicationName.
        ///</returns>
        ///
        ///<param name="username">The user to return a list of roles for.</param>
        public override string[] GetRolesForUser(string username)
        {
            //  ReadRoleDataStore();
            List<string> rolesForUser = new List<string>();

            foreach (Role role in _Roles)
            {
                foreach (string user in role.Users)
                {
                    if (user.ToLower() == username.ToLower())
                        rolesForUser.Add(role.Name.ToLower());
                }
            }
            return rolesForUser.ToArray();
        }

        #endregion

        #region Supported methods

        ///<summary>
        ///Gets an array of user names in a role where the user name contains the specified user name to match.
        ///</summary>
        ///
        ///<returns>
        ///A string array containing the names of all the users where the user name matches usernameToMatch and the user is a member of the specified role.
        ///</returns>
        ///
        ///<param name="usernameToMatch">The user name to search for.</param>
        ///<param name="roleName">The role to search in.</param>
        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            List<string> UsersInRole = new List<string>();
            if (IsUserInRole(usernameToMatch, roleName))
                UsersInRole.AddRange(_UserNames);
            return UsersInRole.ToArray();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="config"></param>
        public override void Initialize(string name, NameValueCollection config)
        {
            ReadMembershipDataStore();
            if (config == null)
                throw new ArgumentNullException("config");

            if (String.IsNullOrEmpty(name))
                name = "XmlMembershipProvider";

            if (string.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "XML role provider");
            }

            base.Initialize(name, config);

            // Initialize _XmlFileName and make sure the path
            // is app-relative
            string path = config["xmlFileName"];

            if (String.IsNullOrEmpty(path))
                path = BlogSettings.Instance.StorageLocation + "roles.xml";


            if (!VirtualPathUtility.IsAppRelative(path))
                throw new ArgumentException
                    ("xmlFileName must be app-relative");

            string fullyQualifiedPath = VirtualPathUtility.Combine
                (VirtualPathUtility.AppendTrailingSlash
                     (HttpRuntime.AppDomainAppVirtualPath), path);

            _XmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath);
            config.Remove("xmlFileName");

            // Make sure we have permission to read the XML data source and
            // throw an exception if we don't
            FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write, _XmlFileName);
            permission.Demand();

            if (!System.IO.File.Exists(_XmlFileName))
                AddUsersToRoles(_UserNames.ToArray(), _DefaultRolesToAdd);

⌨️ 快捷键说明

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