Home » Code

An XML User And Role Provider for ASP.net

27. October 2008 by thebeebs 2 Comments

If you want to implement User and Roles in your ASP.net Application but don’t have an SQL server you could use or extend the following XML providers.

// <copyright file="XMLRoles.cs" company="Martinbeeby">//      Copyright (c) 2008 MB// </copyright>// <author>Mbee</author>namespace Core.Providers{    using System;    using System.Collections.Generic;    using System.Collections.Specialized;    using System.Configuration.Provider;    using System.Security.Permissions;    using System.Web;    using System.Web.Hosting;    using System.Web.Security;    using System.Xml;    /// <summary>    /// The Roles Implimaentation With XML    /// </summary>    public class XMLRoles : RoleProvider    {        /// <summary>        /// A Private Field        /// </summary>        private Dictionary<string, string[]> usersAndRoles =            new Dictionary<string, string[]>(                16,            StringComparer.InvariantCultureIgnoreCase);        /// <summary>        /// A private Field        /// </summary>        private Dictionary<string, string[]> rolesAndUsers =            new Dictionary<string, string[]>(                16,            StringComparer.InvariantCultureIgnoreCase);        /// <summary>        /// A Private Field        /// </summary>        private string xmlFileName;        /// <summary>        /// Gets or sets the name of the application to store and retrieve role information for.        /// </summary>        /// <value></value>        /// <returns>        /// The name of the application to store and retrieve role information for.        /// </returns>        public override string ApplicationName        {            get { throw new NotSupportedException(); }            set { throw new NotSupportedException(); }        }        /// <summary>        /// Initializes the provider.        /// </summary>        /// <param name="name">The friendly name of the provider.</param>        /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>        /// <exception cref="T:System.ArgumentNullException">        /// The name of the provider is null.        /// </exception>        /// <exception cref="T:System.ArgumentException">        /// The name of the provider has a length of zero.        /// </exception>        /// <exception cref="T:System.InvalidOperationException">        /// An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a provider after the provider has already been initialized.        /// </exception>        public override void Initialize(            string name,            NameValueCollection config)        {            // Verify that config isn't null            if (config == null)            {                throw new ArgumentNullException("config");            }            // Assign the provider a default name if it doesn't have one            if (String.IsNullOrEmpty(name))            {                name = "ReadOnlyXmlRoleProvider";            }            // Add a default "description" attribute to config if the            // attribute doesn't exist or is empty            if (string.IsNullOrEmpty(config["description"]))            {                config.Remove("description");                config.Add("description", "Read-only XML role provider");            }            // Call the base class's Initialize method            base.Initialize(name, config);            // Initialize xmlFileName and make sure the path            // is app-relative            string path = config["xmlFileName"];            if (String.IsNullOrEmpty(path))            {                path = "~/App_Data/Users.xml";            }            if (!VirtualPathUtility.IsAppRelative(path))            {                throw new ArgumentException("xmlFileName must be app-relative");            }            string fullyQualifiedPath = VirtualPathUtility.Combine(VirtualPathUtility.AppendTrailingSlash(HttpRuntime.AppDomainAppVirtualPath), path);            this.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.Read,                this.xmlFileName);            permission.Demand();            // 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);                }            }            // Read the role data source. NOTE: Unlike            // ReadOnlyXmlMembershipProvider, this provider can            // read the data source at this point because Read-            // RoleDataStore doesn't call into the role manager            this.ReadRoleDataStore();        }        /// <summary>        /// Gets a value indicating whether the specified user is in the specified role for the configured applicationName.        /// </summary>        /// <param name="username">The user name to search for.</param>        /// <param name="roleName">The role to search in.</param>        /// <returns>        /// true if the specified user is in the specified role for the configured applicationName; otherwise, false.        /// </returns>        public override bool IsUserInRole(string username, string roleName)        {            // Validate input parameters            if (username == null || roleName == null)            {                throw new ArgumentNullException();            }            if (username == String.Empty || roleName == string.Empty)            {                throw new ArgumentException();            }            // Make sure the user name and role name are valid            if (!this.usersAndRoles.ContainsKey(username))            {                throw new ProviderException("Invalid user name");            }            if (!this.rolesAndUsers.ContainsKey(roleName))            {                throw new ProviderException("Invalid role name");            }            // Determine whether the user is in the specified role                string[] roles = this.usersAndRoles[username];            foreach (string role in roles)            {                if (String.Compare(role, roleName, true) == 0)                {                    return true;                }            }            return false;        }        /// <summary>        /// Gets a list of the roles that a specified user is in for the configured applicationName.        /// </summary>        /// <param name="username">The user to return a list of roles for.</param>        /// <returns>        /// A string array containing the names of all the roles that the specified user is in for the configured applicationName.        /// </returns>        public override string[] GetRolesForUser(string username)        {            // Validate input parameters            if (username == null)            {                throw new ArgumentNullException();            }            if (username == string.Empty)            {                throw new ArgumentException();            }            // Make sure the user name is valid            string[] roles;            if (!this.usersAndRoles.TryGetValue(username, out roles))            {                throw new ProviderException("Invalid user name");            }            // Return role names            return roles;        }        /// <summary>        /// Gets a list of users in the specified role for the configured applicationName.        /// </summary>        /// <param name="roleName">The name of the role to get the list of users for.</param>        /// <returns>        /// A string array containing the names of all the users who are members of the specified role for the configured applicationName.        /// </returns>        public override string[] GetUsersInRole(string roleName)        {            // Validate input parameters            if (roleName == null)            {                throw new ArgumentNullException();            }            if (roleName == string.Empty)            {                throw new ArgumentException();            }            // Make sure the role name is valid            string[] users;            if (!this.rolesAndUsers.TryGetValue(roleName, out users))            {                throw new ProviderException("Invalid role name");            }            // Return user names            return users;        }        /// <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()        {            int i = 0;            string[] roles = new string[this.rolesAndUsers.Count];            foreach (KeyValuePair<string, string[]> pair in this.rolesAndUsers)            {                roles[i++] = pair.Key;            }            return roles;        }        /// <summary>        /// Gets a value indicating whether the specified role name already exists in the role data source for the configured applicationName.        /// </summary>        /// <param name="roleName">The name of the role to search for in the data source.</param>        /// <returns>        /// true if the role name already exists in the data source for the configured applicationName; otherwise, false.        /// </returns>        public override bool RoleExists(string roleName)        {            // Validate input parameters            if (roleName == null)            {                throw new ArgumentNullException();            }            if (roleName == string.Empty)            {                throw new ArgumentException();            }            // Determine whether the role exists            return this.rolesAndUsers.ContainsKey(roleName);        }        /// <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)        {            throw new NotSupportedException();        }        /// <summary>        /// Removes a role from the data source for the configured applicationName.        /// </summary>        /// <param name="roleName">The name of the role to delete.</param>        /// <param name="throwOnPopulatedRole">If true, throw an exception if <paramref name="roleName"/> has one or more members and do not delete <paramref name="roleName"/>.</param>        /// <returns>        /// true if the role was successfully deleted; otherwise, false.        /// </returns>        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)        {            throw new NotSupportedException();        }        /// <summary>        /// Adds the specified user names to the specified roles for the configured applicationName.        /// </summary>        /// <param name="usernames">A string array of user names to be added to the specified roles.</param>        /// <param name="roleNames">A string array of the role names to add the specified user names to.</param>        public override void AddUsersToRoles(            string[] usernames,            string[] roleNames)        {            throw new NotSupportedException();        }        /// <summary>        /// Gets an array of user names in a role where the user name contains the specified user name to match.        /// </summary>        /// <param name="roleName">The role to search in.</param>        /// <param name="usernameToMatch">The user name to search for.</param>        /// <returns>        /// A string array containing the names of all the users where the user name matches <paramref name="usernameToMatch"/> and the user is a member of the specified role.        /// </returns>        public override string[] FindUsersInRole(            string roleName,            string usernameToMatch)        {            throw new NotSupportedException();        }        /// <summary>        /// Removes the specified user names from the specified roles for the configured applicationName.        /// </summary>        /// <param name="usernames">A string array of user names to be removed from the specified roles.</param>        /// <param name="roleNames">A string array of role names to remove the specified user names from.</param>        public override void RemoveUsersFromRoles(            string[] usernames,            string[] roleNames)        {            throw new NotSupportedException();        }        /// <summary>        /// Reads the role data store.        /// </summary>        private void ReadRoleDataStore()        {            XmlDocument doc = new XmlDocument();            doc.Load(this.xmlFileName);            XmlNodeList nodes = doc.GetElementsByTagName("User");            foreach (XmlNode node in nodes)            {                if (node["UserName"] == null)                {                    throw new ProviderException("Missing UserName element");                }                string user = node["UserName"].InnerText;                if (String.IsNullOrEmpty(user))                {                    throw new ProviderException("Empty UserName element");                }                if (node["Roles"] == null || String.IsNullOrEmpty(node["Roles"].InnerText))                {                    this.usersAndRoles.Add(user, new string[0]);                }                else                {                    string[] roles = node["Roles"].InnerText.Split(',');                    // Add the role names to usersAndRoles and                    // key them by user name                    this.usersAndRoles.Add(user, roles);                    foreach (string role in roles)                    {                        // Add the user name to rolesAndUsers and                        // key it by role names                        string[] users1;                        if (this.rolesAndUsers.TryGetValue(role, out users1))                        {                            string[] users2 =                                new string[users1.Length + 1];                            users1.CopyTo(users2, 0);                            users2[users1.Length] = user;                            this.rolesAndUsers.Remove(role);                            this.rolesAndUsers.Add(role, users2);                        }                        else                        {                            this.rolesAndUsers.Add(role, new string[] { user });                        }                    }                }            }        }    }}

 

 

 

// <copyright file="XMLMembership.cs" company="MartinBeeby">//      Copyright (c) 2008 MB// </copyright>// <author>Mbee</author>namespace Core.Providers{    using System;    using System.Collections.Generic;    using System.Collections.Specialized;    using System.Configuration.Provider;    using System.Security.Permissions;    using System.Web;    using System.Web.Hosting;    using System.Web.Security;    using System.Xml;    /// <summary>    /// An XML MemberShip Provider    /// </summary>    public class XmlMembershipProvider : MembershipProvider    {        /// <summary>        /// A private Field        /// </summary>        private Dictionary<string, MembershipUser> users;        /// <summary>        /// A Private Field        /// </summary>        private string xmlFileName;        /// <summary>        /// Gets or sets MembershipProvider Properties        /// </summary>        /// <value></value>        /// <returns>        /// The name of the application using the custom membership provider.        /// </returns>        public override string ApplicationName        {            get { throw new NotSupportedException(); }            set { throw new NotSupportedException(); }        }        /// <summary>        /// Gets a value indicating whether the membership provider is configured to allow users to retrieve their passwords.        /// </summary>        /// <value></value>        /// <returns>true if the membership provider is configured to support password retrieval; otherwise, false. The default is false.        /// </returns>        public override bool EnablePasswordRetrieval        {            get { return false; }        }        /// <summary>        /// Gets a value indicating whether the membership provider is configured to allow users to reset their passwords.        /// </summary>        /// <value></value>        /// <returns>true if the membership provider supports password reset; otherwise, false. The default is true.        /// </returns>        public override bool EnablePasswordReset        {            get { return false; }        }        /// <summary>        /// Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out.        /// </summary>        /// <value></value>        /// <returns>        /// The number of invalid password or password-answer attempts allowed before the membership user is locked out.        /// </returns>        public override int MaxInvalidPasswordAttempts        {            get { throw new NotSupportedException(); }        }        /// <summary>        /// Gets the minimum number of special characters that must be present in a valid password.        /// </summary>        /// <value></value>        /// <returns>        /// The minimum number of special characters that must be present in a valid password.        /// </returns>        public override int MinRequiredNonAlphanumericCharacters        {            get { throw new NotSupportedException(); }        }        /// <summary>        /// Gets the minimum length required for a password.        /// </summary>        /// <value></value>        /// <returns>        /// The minimum length required for a password.        /// </returns>        public override int MinRequiredPasswordLength        {            get { throw new NotSupportedException(); }        }        /// <summary>        /// Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.        /// </summary>        /// <value></value>        /// <returns>        /// The number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.        /// </returns>        public override int PasswordAttemptWindow        {            get { throw new NotSupportedException(); }        }        /// <summary>        /// Gets a value indicating the format for storing passwords in the membership data store.        /// </summary>        /// <value></value>        /// <returns>        /// One of the <see cref="T:System.Web.Security.MembershipPasswordFormat"/> values indicating the format for storing passwords in the data store.        /// </returns>        public override MembershipPasswordFormat PasswordFormat        {            get { throw new NotSupportedException(); }        }        /// <summary>        /// Gets the regular expression used to evaluate a password.        /// </summary>        /// <value></value>        /// <returns>        /// A regular expression used to evaluate a password.        /// </returns>        public override string PasswordStrengthRegularExpression        {            get { throw new NotSupportedException(); }        }        /// <summary>        /// Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval.        /// </summary>        /// <value></value>        /// <returns>true if a password answer is required for password reset and retrieval; otherwise, false. The default is true.        /// </returns>        public override bool RequiresQuestionAndAnswer        {            get { throw new NotSupportedException(); }        }        /// <summary>        /// Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name.        /// </summary>        /// <value></value>        /// <returns>true if the membership provider requires a unique e-mail address; otherwise, false. The default is true.        /// </returns>        public override bool RequiresUniqueEmail        {            get { throw new NotSupportedException(); }        }        /// <summary>        /// Initializes the provider.        /// </summary>        /// <param name="name">The friendly name of the provider.</param>        /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>        /// <exception cref="T:System.ArgumentNullException">        /// The name of the provider is null.        /// </exception>        /// <exception cref="T:System.ArgumentException">        /// The name of the provider has a length of zero.        /// </exception>        /// <exception cref="T:System.InvalidOperationException">        /// An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"/> on a provider after the provider has already been initialized.        /// </exception>        public override void Initialize(string name, NameValueCollection config)        {            // Verify that config isn't null            if (config == null)            {                throw new ArgumentNullException("config");            }            // Assign the provider a default name if it doesn't have one            if (String.IsNullOrEmpty(name))            {                name = "ReadOnlyXmlMembershipProvider";            }            // Add a default "description" attribute to config if the            // attribute doesn't exist or is empty            if (string.IsNullOrEmpty(config["description"]))            {                config.Remove("description");                config.Add("description", "Read-only XML membership provider");            }            // Call the base class's Initialize method            base.Initialize(name, config);            // Initialize xmlFileName and make sure the path            // is app-relative            string path = config["xmlFileName"];            if (String.IsNullOrEmpty(path))            {                path = "~/App_Data/Users.xml";            }            if (!VirtualPathUtility.IsAppRelative(path))            {                throw new ArgumentException("xmlFileName must be app-relative");            }            string fullyQualifiedPath = VirtualPathUtility.Combine(VirtualPathUtility.AppendTrailingSlash(HttpRuntime.AppDomainAppVirtualPath), path);            this.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.Read, this.xmlFileName);            permission.Demand();            // 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>        /// Verifies that the specified user name and password exist in the data source.        /// </summary>        /// <param name="username">The name of the user to validate.</param>        /// <param name="password">The password for the specified user.</param>        /// <returns>        /// true if the specified username and password are valid; otherwise, false.        /// </returns>        public override bool ValidateUser(string username, string password)        {            // Validate input parameters            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))            {                return false;            }            try            {                // Make sure the data source has been loaded                this.ReadMembershipDataStore();                // Validate the user name and password                MembershipUser user;                if (this.users.TryGetValue(username, out user))                {                    // Case-sensitive                    if (user.Comment == password)                    {                        // NOTE: A read/write membership provider                        // would update the user's LastLoginDate here.                        // A fully featured provider would also fire                        // an AuditMembershipAuthenticationSuccess                        // Web event                        return true;                    }                }                // NOTE: A fully featured membership provider would                // fire an AuditMembershipAuthenticationFailure                // Web event here                return false;            }            catch (Exception)            {                return false;            }        }        /// <summary>        /// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user.        /// </summary>        /// <param name="username">The name of the user to get information for.</param>        /// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>        /// <returns>        /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the specified user's information from the data source.        /// </returns>        public override MembershipUser GetUser(string username, bool userIsOnline)        {            // Note: This implementation ignores userIsOnline            // Validate input parameters            if (String.IsNullOrEmpty(username))            {                return null;            }            // Make sure the data source has been loaded            this.ReadMembershipDataStore();            // Retrieve the user from the data source            MembershipUser user;            if (this.users.TryGetValue(username, out user))            {                return user;            }            return null;        }        /// <summary>        /// Gets a collection of all the users in the data source in pages of data.        /// </summary>        /// <param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex"/> is zero-based.</param>        /// <param name="pageSize">The size of the page of results to return.</param>        /// <param name="totalRecords">The total number of matched users.</param>        /// <returns>        /// A <see cref="T:System.Web.Security.MembershipUserCollection"/> collection that contains a page of <paramref name="pageSize"/><see cref="T:System.Web.Security.MembershipUser"/> objects beginning at the page specified by <paramref name="pageIndex"/>.        /// </returns>        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)        {            // Note: This implementation ignores pageIndex and pageSize,            // and it doesn't sort the MembershipUser objects returned            // Make sure the data source has been loaded            this.ReadMembershipDataStore();            MembershipUserCollection allUsers = new MembershipUserCollection();            foreach (KeyValuePair<string, MembershipUser> pair in this.users)            {                allUsers.Add(pair.Value);            }            totalRecords = allUsers.Count;            return allUsers;        }        /// <summary>        /// Gets the number of users currently accessing the application.        /// </summary>        /// <returns>        /// The number of users currently accessing the application.        /// </returns>        public override int GetNumberOfUsersOnline()        {            throw new NotSupportedException();        }        /// <summary>        /// Processes a request to update the password for a membership user.        /// </summary>        /// <param name="username">The user to update the password for.</param>        /// <param name="oldPassword">The current password for the specified user.</param>        /// <param name="newPassword">The new password for the specified user.</param>        /// <returns>        /// true if the password was updated successfully; otherwise, false.        /// </returns>        public override bool ChangePassword(string username, string oldPassword, string newPassword)        {            throw new NotSupportedException();        }        /// <summary>        /// Processes a request to update the password question and answer for a membership user.        /// </summary>        /// <param name="username">The user to change the password question and answer for.</param>        /// <param name="password">The password for the specified user.</param>        /// <param name="newPasswordQuestion">The new password question for the specified user.</param>        /// <param name="newPasswordAnswer">The new password answer for the specified user.</param>        /// <returns>        /// true if the password question and answer are updated successfully; otherwise, false.        /// </returns>        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)        {            throw new NotSupportedException();        }        /// <summary>        /// Adds a new membership user to the data source.        /// </summary>        /// <param name="username">The user name for the new user.</param>        /// <param name="password">The password for the new user.</param>        /// <param name="email">The e-mail address for the new user.</param>        /// <param name="passwordQuestion">The password question for the new user.</param>        /// <param name="passwordAnswer">The password answer for the new user</param>        /// <param name="isApproved">Whether or not the new user is approved to be validated.</param>        /// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>        /// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"/> enumeration value indicating whether the user was created successfully.</param>        /// <returns>        /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the information for the newly created user.        /// </returns>        public override MembershipUser CreateUser(            string username,            string password,            string email,            string passwordQuestion,            string passwordAnswer,            bool isApproved,            object providerUserKey,            out MembershipCreateStatus status)        {            throw new NotSupportedException();        }        /// <summary>        /// Removes a user from the membership data source.        /// </summary>        /// <param name="username">The name of the user to delete.</param>        /// <param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param>        /// <returns>        /// true if the user was successfully deleted; otherwise, false.        /// </returns>        public override bool DeleteUser(            string username,            bool deleteAllRelatedData)        {            throw new NotSupportedException();        }        /// <summary>        /// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match.        /// </summary>        /// <param name="emailToMatch">The e-mail address to search for.</param>        /// <param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex"/> is zero-based.</param>        /// <param name="pageSize">The size of the page of results to return.</param>        /// <param name="totalRecords">The total number of matched users.</param>        /// <returns>        /// A <see cref="T:System.Web.Security.MembershipUserCollection"/> collection that contains a page of <paramref name="pageSize"/><see cref="T:System.Web.Security.MembershipUser"/> objects beginning at the page specified by <paramref name="pageIndex"/>.        /// </returns>        public override MembershipUserCollection            FindUsersByEmail(            string emailToMatch,            int pageIndex,            int pageSize,            out int totalRecords)        {            throw new NotSupportedException();        }        /// <summary>        /// Gets a collection of membership users where the user name contains the specified user name to match.        /// </summary>        /// <param name="usernameToMatch">The user name to search for.</param>        /// <param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex"/> is zero-based.</param>        /// <param name="pageSize">The size of the page of results to return.</param>        /// <param name="totalRecords">The total number of matched users.</param>        /// <returns>        /// A <see cref="T:System.Web.Security.MembershipUserCollection"/> collection that contains a page of <paramref name="pageSize"/><see cref="T:System.Web.Security.MembershipUser"/> objects beginning at the page specified by <paramref name="pageIndex"/>.        /// </returns>        public override MembershipUserCollection            FindUsersByName(            string usernameToMatch,            int pageIndex,            int pageSize,            out int totalRecords)        {            throw new NotSupportedException();        }        /// <summary>        /// Gets the password for the specified user name from the data source.        /// </summary>        /// <param name="username">The user to retrieve the password for.</param>        /// <param name="answer">The password answer for the user.</param>        /// <returns>        /// The password for the specified user name.        /// </returns>        public override string GetPassword(string username, string answer)        {            throw new NotSupportedException();        }        /// <summary>        /// Gets user information from the data source based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user.        /// </summary>        /// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param>        /// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>        /// <returns>        /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the specified user's information from the data source.        /// </returns>        public override MembershipUser GetUser(            object providerUserKey,            bool userIsOnline)        {            throw new NotSupportedException();        }        /// <summary>        /// Gets the user name associated with the specified e-mail address.        /// </summary>        /// <param name="email">The e-mail address to search for.</param>        /// <returns>        /// The user name associated with the specified e-mail address. If no match is found, return null.        /// </returns>        public override string GetUserNameByEmail(string email)        {            throw new NotSupportedException();        }        /// <summary>        /// Resets a user's password to a new, automatically generated password.        /// </summary>        /// <param name="username">The user to reset the password for.</param>        /// <param name="answer">The password answer for the specified user.</param>        /// <returns>The new password for the specified user.</returns>        public override string ResetPassword(            string username,            string answer)        {            throw new NotSupportedException();        }        /// <summary>        /// Clears a lock so that the membership user can be validated.        /// </summary>        /// <param name="userName">The membership user whose lock status you want to clear.</param>        /// <returns>        /// true if the membership user was successfully unlocked; otherwise, false.        /// </returns>        public override bool UnlockUser(string userName)        {            throw new NotSupportedException();        }        /// <summary>        /// Updates information about a user in the data source.        /// </summary>        /// <param name="user">A <see cref="T:System.Web.Security.MembershipUser"/> object that represents the user to update and the updated information for the user.</param>        public override void UpdateUser(MembershipUser user)        {            throw new NotSupportedException();        }        /// <summary>        /// Reads the membership data store.        /// </summary>        private void ReadMembershipDataStore()        {            lock (this)            {                if (this.users == null)                {                    this.users = new Dictionary<string, MembershipUser>(16, StringComparer.InvariantCultureIgnoreCase);                    XmlDocument doc = new XmlDocument();                    doc.Load(this.xmlFileName);                    XmlNodeList nodes = doc.GetElementsByTagName("User");                    foreach (XmlNode node in nodes)                    {                        MembershipUser user = new MembershipUser(                            Name,                       // Provider name                            node["UserName"].InnerText, // Username                            null,                       // providerUserKey                            node["EMail"].InnerText,    // Email                            String.Empty,               // passwordQuestion                            node["Password"].InnerText, // Comment                            true,                       // isApproved                            false,                      // isLockedOut                            DateTime.Now,               // creationDate                            DateTime.Now,               // lastLoginDate                            DateTime.Now,               // lastActivityDate                            DateTime.Now, // lastPasswordChangedDate                            new DateTime(1980, 1, 1));                        this.users.Add(user.UserName, user);                    }                }            }        }    }}

You can then use XML like below to manage your users accounts (I save this this in the App_Data Folder and call it MembershipUsers.xml) :

<Users>  <User>    <UserName>admin</UserName>    <Password>admin</Password>    <EMail>admin@admin.co.uk</EMail>  </User><User>  <UserName>admin1</UserName>  <Password>admin1</Password>  <EMail>admin1@admin.co.uk</EMail></User></Users>

 

You then set up the roles (Isave this in the App_Data folder and call it UserRoles.xml):

<Users>  <User>    <UserName>Admin</UserName>    <Roles>Members,Administrators</Roles>  </User>  <User>    <UserName>Admin1</UserName>    <Roles>Members</Roles>  </User></Users>

 

 

Lastly add the following into the Web.Config under the System.Web section:

<membership defaultProvider="AspNetReadOnlyXmlMembershipProvider">  <providers>    <add name="AspNetReadOnlyXmlMembershipProvider"      type="Core.Providers.XmlMembershipProvider"      description="Read-only XML membership provider"      xmlFileName="~/App_Data/MembershipUsers.xml"    />  </providers></membership><roleManager enabled="true"  defaultProvider="AspNetReadOnlyXmlRoleProvider">  <providers>    <add name="AspNetReadOnlyXmlRoleProvider"      type="Core.Providers.XMLRoles"      description="Read-only XML role provider"      xmlFileName="~/App_Data/UserRoles.xml"    />  </providers></roleManager>

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading