ASP.NET MVC2 custom rolemanager (webconfig problem)
- by ile
Structure of the web:
SAMembershipProvider.cs
namespace User.Membership
{
public class SAMembershipProvider : MembershipProvider
{
#region - Properties -
private int NewPasswordLength { get; set; }
private string ConnectionString { get; set; }
//private MachineKeySection MachineKey { get; set; } //Used when determining encryption key values.
public bool enablePasswordReset { get; set; }
public bool enablePasswordRetrieval { get; set; }
public bool requiresQuestionAndAnswer { get; set; }
public bool requiresUniqueEmail { get; set; }
public int maxInvalidPasswordAttempts { get; set; }
public int passwordAttemptWindow { get; set; }
public MembershipPasswordFormat passwordFormat { get; set; }
public int minRequiredNonAlphanumericCharacters { get; set; }
public int minRequiredPasswordLength { get; set; }
public string passwordStrengthRegularExpression { get; set; }
public override string ApplicationName { get; set; }
// Indicates whether passwords can be retrieved using the provider's GetPassword method.
// This property is read-only.
public override bool EnablePasswordRetrieval
{
get { return enablePasswordRetrieval; }
}
// Indicates whether passwords can be reset using the provider's ResetPassword method.
// This property is read-only.
public override bool EnablePasswordReset
{
get { return enablePasswordReset; }
}
// Indicates whether a password answer must be supplied when calling the provider's GetPassword and ResetPassword methods.
// This property is read-only.
public override bool RequiresQuestionAndAnswer
{
get { return requiresQuestionAndAnswer; }
}
public override int MaxInvalidPasswordAttempts
{
get { return maxInvalidPasswordAttempts; }
}
// For a description, see MaxInvalidPasswordAttempts.
// This property is read-only.
public override int PasswordAttemptWindow
{
get { return passwordAttemptWindow; }
}
// Indicates whether each registered user must have a unique e-mail address.
// This property is read-only.
public override bool RequiresUniqueEmail
{
get { return requiresUniqueEmail; }
}
public override MembershipPasswordFormat PasswordFormat
{
get { return passwordFormat; }
}
// The minimum number of characters required in a password.
// This property is read-only.
public override int MinRequiredPasswordLength
{
get { return minRequiredPasswordLength; }
}
// The minimum number of non-alphanumeric characters required in a password.
// This property is read-only.
public override int MinRequiredNonAlphanumericCharacters
{
get { return minRequiredNonAlphanumericCharacters; }
}
// A regular expression specifying a pattern to which passwords must conform.
// This property is read-only.
public override string PasswordStrengthRegularExpression
{
get { return passwordStrengthRegularExpression; }
}
#endregion
#region - Methods -
public override void Initialize(string name, NameValueCollection config)
{
throw new NotImplementedException();
}
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
throw new NotImplementedException();
}
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
throw new NotImplementedException();
}
// Takes, as input, a user name, password, e-mail address, and other information and adds a new user
// to the membership data source. CreateUser returns a MembershipUser object representing the newly
// created user. It also accepts an out parameter (in Visual Basic, ByRef) that returns a
// MembershipCreateStatus value indicating whether the user was successfully created or, if the user
// was not created, the reason why. If the user was not created, CreateUser returns null.
// Before creating a new user, CreateUser calls the provider's virtual OnValidatingPassword method to
// validate the supplied password. It then creates the user or cancels the action based on the outcome of the call.
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
throw new NotImplementedException();
}
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
throw new NotImplementedException();
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
// Returns a MembershipUserCollection containing MembershipUser objects representing users whose user names
// match the usernameToMatch input parameter. Wildcard syntax is data source-dependent. MembershipUser objects
// in the MembershipUserCollection are sorted by user name. If FindUsersByName finds no matching users, it
// returns an empty MembershipUserCollection.
// For an explanation of the pageIndex, pageSize, and totalRecords parameters, see the GetAllUsers method.
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
// Returns a MembershipUserCollection containing MembershipUser objects representing all registered users. If
// there are no registered users, GetAllUsers returns an empty MembershipUserCollection
// The results returned by GetAllUsers are constrained by the pageIndex and pageSize input parameters. pageSize
// specifies the maximum number of MembershipUser objects to return. pageIndex identifies which page of results
// to return. Page indexes are 0-based.
//
// GetAllUsers also takes an out parameter (in Visual Basic, ByRef) named totalRecords that, on return, holds
// a count of all registered users.
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
throw new NotImplementedException();
}
// Returns a count of users that are currently online-that is, whose LastActivityDate is greater than the current
// date and time minus the value of the membership service's UserIsOnlineTimeWindow property, which can be read
// from Membership.UserIsOnlineTimeWindow. UserIsOnlineTimeWindow specifies a time in minutes and is set using
// the <membership> element's userIsOnlineTimeWindow attribute.
public override int GetNumberOfUsersOnline()
{
throw new NotImplementedException();
}
// Takes, as input, a user name and a password answer and returns that user's password. If the user name is not
// valid, GetPassword throws a ProviderException.
// Before retrieving a password, GetPassword verifies that EnablePasswordRetrieval is true. If
// EnablePasswordRetrieval is false, GetPassword throws a NotSupportedException. If EnablePasswordRetrieval is
// true but the password format is hashed, GetPassword throws a ProviderException since hashed passwords cannot,
// by definition, be retrieved. A membership provider should also throw a ProviderException from Initialize if
// EnablePasswordRetrieval is true but the password format is hashed.
//
// GetPassword also checks the value of the RequiresQuestionAndAnswer property before retrieving a password. If
// RequiresQuestionAndAnswer is true, GetPassword compares the supplied password answer to the stored password
// answer and throws a MembershipPasswordException if the two don't match. GetPassword also throws a
// MembershipPasswordException if the user whose password is being retrieved is currently locked out.
public override string GetPassword(string username, string answer)
{
throw new NotImplementedException();
}
// Takes, as input, a user name or user ID (the method is overloaded) and a Boolean value indicating whether
// to update the user's LastActivityDate to show that the user is currently online. GetUser returns a MembershipUser
// object representing the specified user. If the user name or user ID is invalid (that is, if it doesn't represent
// a registered user) GetUser returns null (Nothing in Visual Basic).
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
throw new NotImplementedException();
}
// Takes, as input, a user name or user ID (the method is overloaded) and a Boolean value indicating whether to
// update the user's LastActivityDate to show that the user is currently online. GetUser returns a MembershipUser
// object representing the specified user. If the user name or user ID is invalid (that is, if it doesn't represent
// a registered user) GetUser returns null (Nothing in Visual Basic).
public override MembershipUser GetUser(string username, bool userIsOnline)
{
throw new NotImplementedException();
}
// Takes, as input, an e-mail address and returns the first registered user name whose e-mail address matches the
// one supplied.
// If it doesn't find a user with a matching e-mail address, GetUserNameByEmail returns an empty string.
public override string GetUserNameByEmail(string email)
{
throw new NotImplementedException();
}
// Virtual method called when a password is created. The default implementation in MembershipProvider fires a
// ValidatingPassword event, so be sure to call the base class's OnValidatingPassword method if you override
// this method. The ValidatingPassword event allows applications to apply additional tests to passwords by
// registering event handlers.
// A custom provider's CreateUser, ChangePassword, and ResetPassword methods (in short, all methods that record
// new passwords) should call this method.
protected override void OnValidatingPassword(ValidatePasswordEventArgs e)
{
base.OnValidatingPassword(e);
}
// Takes, as input, a user name and a password answer and replaces the user's current password with a new, random
// password. ResetPassword then returns the new password. A convenient mechanism for generating a random password
// is the Membership.GeneratePassword method.
// If the user name is not valid, ResetPassword throws a ProviderException. ResetPassword also checks the value of
// the RequiresQuestionAndAnswer property before resetting a password. If RequiresQuestionAndAnswer is true,
// ResetPassword compares the supplied password answer to the stored password answer and throws a
// MembershipPasswordException if the two don't match.
//
// Before resetting a password, ResetPassword verifies that EnablePasswordReset is true. If EnablePasswordReset is
// false, ResetPassword throws a NotSupportedException. If the user whose password is being changed is currently
// locked out, ResetPassword throws a MembershipPasswordException.
//
// Before resetting a password, ResetPassword calls the provider's virtual OnValidatingPassword method to validate
// the new password. It then resets the password or cancels the action based on the outcome of the call. If the new
// password is invalid, ResetPassword throws a ProviderException.
//
// Following a successful password reset, ResetPassword updates the user's LastPasswordChangedDate.
public override string ResetPassword(string username, string answer)
{
throw new NotImplementedException();
}
// Unlocks (that is, restores login privileges for) the specified user. UnlockUser returns true if the user is
// successfully unlocked. Otherwise, it returns false. If the user is already unlocked, UnlockUser simply returns true.
public override bool UnlockUser(string userName)
{
throw new NotImplementedException();
}
// Takes, as input, a MembershipUser object representing a registered user and updates the information stored for
// that user in the membership data source. If any of the input submitted in the MembershipUser object is not valid,
// UpdateUser throws a ProviderException.
// Note that UpdateUser is not obligated to allow all the data that can be encapsulated in a MembershipUser object to
// be updated in the data source.
public override void UpdateUser(MembershipUser user)
{
throw new NotImplementedException();
}
// Takes, as input, a user name and a password and verifies that they are valid-that is, that the membership data
// source contains a matching user name and password. ValidateUser returns true if the user name and password are
// valid, if the user is approved (that is, if MembershipUser.IsApproved is true), and if the user isn't currently
// locked out. Otherwise, it returns false.
// Following a successful validation, ValidateUser updates the user's LastLoginDate and fires an
// AuditMembershipAuthenticationSuccess Web event. Following a failed validation, it fires an
//
// AuditMembershipAuthenticationFailure Web event.
public override bool ValidateUser(string username, string password)
{
throw new NotImplementedException();
//if (string.IsNullOrEmpty(password.Trim())) return false;
//string hash = EncryptPassword(password);
//User user = _repository.GetByUserName(username);
//if (user == null) return false;
//if (user.Password == hash)
//{
// User = user;
// return true;
//}
//return false;
}
#endregion
/// <summary>
/// Procuses an MD5 hash string of the password
/// </summary>
/// <param name="password">password to hash</param>
/// <returns>MD5 Hash string</returns>
protected string EncryptPassword(string password)
{
//we use codepage 1252 because that is what sql server uses
byte[] pwdBytes = Encoding.GetEncoding(1252).GetBytes(password);
byte[] hashBytes = System.Security.Cryptography.MD5.Create().ComputeHash(pwdBytes);
return Encoding.GetEncoding(1252).GetString(hashBytes);
}
} // End Class
}
SARoleProvider.cs
namespace User.Membership
{
public class SARoleProvider : RoleProvider
{
#region - Properties -
// The name of the application using the role provider. ApplicationName is used to scope
// role data so that applications can choose whether to share role data with other applications.
// This property can be read and written.
public override string ApplicationName { get; set; }
#endregion
#region - Methods -
public override void Initialize(string name, NameValueCollection config)
{
throw new NotImplementedException();
}
// Takes, as input, a list of user names and a list of role names and adds the specified users to
// the specified roles.
// AddUsersToRoles throws a ProviderException if any of the user names or role names do not exist.
// If any user name or role name is null (Nothing in Visual Basic), AddUsersToRoles throws an
// ArgumentNullException. If any user name or role name is an empty string, AddUsersToRoles throws
// an ArgumentException.
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
// Takes, as input, a role name and creates the specified role.
// CreateRole throws a ProviderException if the role already exists, the role name contains a comma,
// or the role name exceeds the maximum length allowed by the data source.
public override void CreateRole(string roleName)
{
throw new NotImplementedException();
}
// Takes, as input, a role name and a Boolean value that indicates whether to throw an exception if there
// are users currently associated with the role, and then deletes the specified role.
// If the throwOnPopulatedRole input parameter is true and the specified role has one or more members,
// DeleteRole throws a ProviderException and does not delete the role. If throwOnPopulatedRole is false,
// DeleteRole deletes the role whether it is empty or not.
//
// When DeleteRole deletes a role and there are users assigned to that role, it also removes users from the role.
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotImplementedException();
}
// Takes, as input, a search pattern and a role name and returns a list of users belonging to the specified role
// whose user names match the pattern. Wildcard syntax is data-source-dependent and may vary from provider to
// provider. User names are returned in alphabetical order.
// If the search finds no matches, FindUsersInRole returns an empty string array (a string array with no elements).
// If the role does not exist, FindUsersInRole throws a ProviderException.
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
// Returns the names of all existing roles. If no roles exist, GetAllRoles returns an empty string array (a string
// array with no elements).
public override string[] GetAllRoles()
{
throw new NotImplementedException();
}
// Takes, as input, a user name and returns the names of the roles to which the user belongs.
// If the user is not assigned to any roles, GetRolesForUser returns an empty string array
// (a string array with no elements). If the user name does not exist, GetRolesForUser throws a
// ProviderException.
public override string[] GetRolesForUser(string username)
{
throw new NotImplementedException();
//User user = _repository.GetByUserName(username);
//string[] roles = new string[user.Role.Rights.Count + 1];
//roles[0] = user.Role.Description;
//int idx = 0;
//foreach (Right right in user.Role.Rights)
// roles[++idx] = right.Description;
//return roles;
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
// Takes, as input, a role name and returns the names of all users assigned to that role.
// If no users are associated with the specified role, GetUserInRole returns an empty string array (a string array with
// no elements). If the role does not exist, GetUsersInRole throws a ProviderException.
public override bool IsUserInRole(string username, string roleName)
{
throw new NotImplementedException();
//User user = _repository.GetByUserName(username);
//if (user != null)
// return user.IsInRole(roleName);
//else
// return false;
}
// Takes, as input, a list of user names and a list of role names and removes the specified users from the specified roles.
// RemoveUsersFromRoles throws a ProviderException if any of the users or roles do not exist, or if any user specified
// in the call does not belong to the role from which he or she is being removed.
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
// Takes, as input, a role name and determines whether the role exists.
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
#endregion
} // End Class
}
From Web.config:
<membership defaultProvider="SAMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="SAMembershipProvider" type="User.Membership.SAMembershipProvider, User" />
</providers>
</membership>
<roleManager defaultProvider="SARoleProvider" enabled="true" cacheRolesInCookie="true">
<providers>
<clear/>
<add name="SARoleProvider" type="User.Membership.SARoleProvider" />
</providers>
</roleManager>
When running project, I get following error:
Server Error in '/' Application.
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: The method or operation is not implemented.
Source Error:
Line 71: <providers>
Line 72: <clear/>
Line 73: <add name="SARoleProvider" type="User.Membership.SARoleProvider" />
Line 74: </providers>
Line 75: </roleManager>
I tried:
<add name="SARoleProvider" type="User.Membership.SARoleProvider, User" />
and
<add name="SARoleProvider" type="User.Membership.SARoleProvider, SARoleProvider" />
and
<add name="SARoleProvider" type="User.Membership.SARoleProvider, User.Membership" />
but none works
Any idea what's wrong here?
Thanks,
Ile