Monday, July 11, 2011

Rememberme in Login Control

protected void Page_init(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request.Cookies["UserCookie"] != null)
{
HttpCookie cookie = Request.Cookies.Get("UserCookie");
Login1.UserName = cookie.Values["username"];
TextBox txtPassword = Login1.FindControl("Password") as TextBox;
txtPassword.Attributes.Add("value", Request.Cookies["UserCookie"]["Password"]);
CheckBox checkMe = (CheckBox)Login1.FindControl("RememberMe");
checkMe.Checked = true;
}
TextBox txtUser = Login1.FindControl("UserName") as TextBox;
if (txtUser != null)
this.SetFocus(txtUser);
}
}

protected void Login1_Authenticate(object sender, System.Web.UI.WebControls.AuthenticateEventArgs e)
{
//your login code
//if login is sucess
HttpCookie UserCookie = new HttpCookie("UserCookie ");
Boolean remember = Login1.RememberMeSet;

if (remember)
{
Int32 persistTime = 5;
UserCookie .Values.Add("username", Login1.UserName);
UserCookie .Values.Add("password", Login1.Password);
UserCookie .Expires = DateTime.Now.AddYears(persistTime);
}
else
{
UserCookie .Values.Add("username", string.Empty);
UserCookie .Values.Add("password", string.Empty);
UserCookie .Expires = DateTime.Now.AddMinutes(1);
}
Response.Cookies.Add(UserCookie );
}

No comments:

Post a Comment