正文

定制的MembershipProvider类2007-10-07 17:34:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/goalbell/29941.html

分享到:

基于上一篇的翻译文章,我参考了一下别人的思路,尝试写了一下customed membershipprovider类。该代码适合于Login控件,LoginName控件,LoginStatus控件,CreateUserWizard控件,LoginView控件,ChangePassword控件。 代码如下: using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Data.OleDb; /// <summary>/// AccessMembershipProvider类/// </summary>public class AccessMembershipProvider:MembershipProvider{    private string connStr;//数据库连接字符串    private bool _requiresQuestionAndAnswer; //是否需要用户解答密码问题    private int _minRequiredPasswordLength;//取得密码所需的最小长度    public AccessMembershipProvider() {  //  // TODO: 在此处添加构造函数逻辑  // }    public override int MinRequiredPasswordLength    {        get { return _minRequiredPasswordLength; }     }     public override bool RequiresQuestionAndAnswer    {        get { return _requiresQuestionAndAnswer; }    }     public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)    {        if (config["requiresQuestionAndAnswer"] == "true")        {            _requiresQuestionAndAnswer = true;        }        else         {            _requiresQuestionAndAnswer = false;                }        int.TryParse(config["minRequiredPasswordLength"], out _minRequiredPasswordLength);        connStr = config["connectionString"];        base.Initialize(name, config);    }     public override bool ValidateUser(string username, string password)    {        OleDbConnection conn = new OleDbConnection(connStr);         try         {            conn.Open();            string sql = "select * from Membership where username=@username and password=@password";            OleDbCommand cmd = new OleDbCommand(sql, conn);            cmd.Parameters.AddWithValue("@username", username);            cmd.Parameters.AddWithValue("@password", password);            OleDbDataReader dr = cmd.ExecuteReader();             if (dr.HasRows)            {                conn.Close();                return true;            }            else            {                conn.Close();                return false;             }        }        catch           {                if(conn.State == ConnectionState.Open)                   conn.Close();                   return false;                                                                   }                }     public override string ApplicationName    {        get        {            throw new Exception("The method or operation is not implemented.");        }        set        {            throw new Exception("The method or operation is not implemented.");        }    }     public override bool ChangePassword(string username, string oldPassword, string newPassword)    {        if (!ValidateUser(username, oldPassword))            return false;        ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true);        OnValidatingPassword(args);        if (args.Cancel)            if (args.FailureInformation != null)                throw args.FailureInformation;            else                throw new MembershipPasswordException("Change password canceled due to new password validation failure.");         OleDbConnection conn = new OleDbConnection(connStr);        conn.Open();        string sql = "update [Membership] set [password]=@password where [username]=@username";        OleDbCommand cmd = new OleDbCommand(sql, conn);        cmd.Parameters.Add("@password", OleDbType.VarChar, 255).Value = newPassword;        cmd.Parameters.Add("@username", OleDbType.VarChar, 255).Value = username;        int rowsAffected = 0;        try        {            rowsAffected = cmd.ExecuteNonQuery();        }        catch        {            throw new Exception("Changepassword Exception.");         }        finally        {            conn.Close();                }        if (rowsAffected > 0)        {            return true;        }        return false;                }     public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)    {        if (!ValidateUser(username, password))            return false;        OleDbConnection conn = new OleDbConnection(connStr);        conn.Open();        string sql = "update [Membership] set [passwordQuestion]=@passwordQuestion and [passwordAnswer]=@passwordAnswer where [username]=@username";        OleDbCommand cmd = new OleDbCommand(sql, conn);        cmd.Parameters.Add("@username", OleDbType.VarChar, 255).Value = username;        cmd.Parameters.Add("@passwordQuestion", OleDbType.VarChar, 255).Value = newPasswordQuestion;        cmd.Parameters.Add("@passwordAnswer", OleDbType.VarChar, 255).Value = newPasswordAnswer;        int rowsAffected = 0;        try        {            rowsAffected = cmd.ExecuteNonQuery();         }        catch        {            throw new ApplicationException("ChangePasswordQuestionAndAnswer Exception.");         }        finally         {            conn.Close();        }        if (rowsAffected > 0)        {            return true;          }        return false;    }     public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)    {       OleDbConnection conn = new OleDbConnection(connStr);       try       {           conn.Open();                      string sql = "insert into Membership([username],[password],[Email],[passwordQuestion],[passwordAnswer]) values(@username,@password,@email,@passwordQuestion,@passwordAnswer)";           OleDbCommand command = new OleDbCommand(sql, conn);           command.Parameters.AddWithValue("@username", username);           command.Parameters.AddWithValue("@password", password);           command.Parameters.AddWithValue("@email", email);           command.Parameters.AddWithValue("@passwordQuestion", passwordQuestion);           command.Parameters.AddWithValue("@passwordAnswer", passwordAnswer);           command.ExecuteNonQuery();           conn.Close();           MembershipUser user = new MembershipUser("AccessMembershipProvider", username, providerUserKey, email, passwordQuestion, "", isApproved, true, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);           status = MembershipCreateStatus.Success;           return user;                                          }       catch       {          if (conn.State == ConnectionState.Open)            conn.Close();           status = MembershipCreateStatus.ProviderError;           return null;         }       }     public override bool DeleteUser(string username, bool deleteAllRelatedData)    {        throw new Exception("The method or operation is not implemented.");    }     public override bool EnablePasswordReset    {        get { throw new Exception("The method or operation is not implemented."); }    }     public override bool EnablePasswordRetrieval    {        get { throw new Exception("The method or operation is not implemented."); }    }     public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)    {        throw new Exception("The method or operation is not implemented.");    }     public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)    {        throw new Exception("The method or operation is not implemented.");    }     public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)    {        throw new Exception("The method or operation is not implemented.");    }     public override int GetNumberOfUsersOnline()    {        throw new Exception("The method or operation is not implemented.");    }     public override string GetPassword(string username, string answer)    {        if (!EnablePasswordRetrieval)        {            throw new ApplicationException("Password Retrieval Not Enable.");         }         OleDbConnection conn = new OleDbConnection(connStr);        conn.Open();        string sql = "select * from [Membership] where [username]=@username";        OleDbCommand cmd = new OleDbCommand(sql, conn);        cmd.Parameters.Add("@username", OleDbType.VarChar, 255).Value = username;        string password = null;        string passwordAnswer = null;        OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.SingleRow);        try        {            if (dr.HasRows)            {                dr.Read();                password = dr.GetString(1);                passwordAnswer = dr.GetString(4);            }        }        catch        {            throw new ApplicationException("GetPassword Exception.");        }        finally         {            if (dr != null)            {                dr.Close();            }            conn.Close();        }        return password;    }     public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)    {        throw new Exception("The method or operation is not implemented.");    }     public override MembershipUser GetUser(string username, bool userIsOnline)    {        OleDbConnection conn = new OleDbConnection(connStr);         conn.Open();        string sql="select * from [Membership] where username=@username";        OleDbCommand cmd = new OleDbCommand(sql, conn);        cmd.Parameters.Add("@username", OleDbType.VarChar, 255).Value = username;        OleDbDataReader dr = cmd.ExecuteReader();        MembershipUser user = null;        try        {            if (dr.HasRows)            {                dr.Read();//                user = GetUserFromReader(dr);                /*if (userIsOnline)                {                     do something here......                 }*/             }        }        catch        {            throw new ApplicationException("GetUser Exception!");         }        finally         {            if (dr != null)            {                dr.Close();            }            conn.Close();                 }        return user;              }     public override string GetUserNameByEmail(string email)    {        throw new Exception("The method or operation is not implemented.");    }     public override int MaxInvalidPasswordAttempts    {        get { throw new Exception("The method or operation is not implemented."); }    }     public override int MinRequiredNonAlphanumericCharacters    {        get { throw new Exception("The method or operation is not implemented."); }    }     public override int PasswordAttemptWindow    {        get { throw new Exception("The method or operation is not implemented."); }    }     public override MembershipPasswordFormat PasswordFormat    {        get { throw new Exception("The method or operation is not implemented."); }    }     public override string PasswordStrengthRegularExpression    {        get { throw new Exception("The method or operation is not implemented."); }    }     public override bool RequiresUniqueEmail    {        get { throw new Exception("The method or operation is not implemented."); }    }     public override string ResetPassword(string username, string answer)    {        throw new Exception("The method or operation is not implemented.");    }     public override bool UnlockUser(string userName)    {        throw new Exception("The method or operation is not implemented.");    }     public override void UpdateUser(MembershipUser user)    {        throw new Exception("The method or operation is not implemented.");    }     //通过OleDataReader获取当前的行,并测试MembershipUser的值,通过调用实现MembershipUser.GetUser方法.。     private MembershipUser GetUserFromReader(OleDbDataReader reader)     {                string username = reader.GetString(0);        string email = reader.GetString(2);        string passwordQuestion =null;        if (reader.GetValue(3) != DBNull.Value)        {            passwordQuestion = reader.GetString(3);        }           MembershipUser user = new MembershipUser("AccessMembershipProvider", username, "", email, passwordQuestion, "", true, true, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now);        return user;    }}  

阅读(2960) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册