Friday, December 12, 2008

Remember me on this computer - Store username and password in cookie and login automatically.

·

Write below code on page load event to check cookie it exist or not.


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// check your cookies is null or not
if (Request.Cookies["myCockie"] != null) //Cookie Exists??
{

// Create cookie object
HttpCookie cookie = Request.Cookies.Get("myCockie");

// retrive username and password from cookie
string user = cookie.Values["Username"].ToString();
string pass = cookie.Values["Password"].ToString();

if (user != "")
{
txtUname.Text = user;
//Write the username onto login username textbox
}
if (pass != "")
{
txtPW.Attributes.Add("value", pass);
// set password string to the password textbox.
}

// check "remember me on this computer" checkbox
chkRemmember.Checked = true;

// call method to login into the system
Login_User(txtUname.Text, txtPW.Text);
}
txtUname.Focus();
}
}

On Login Button Click Event, Store username and password in cookie.


protected void btnLogin_Click(object sender, ImageClickEventArgs e)
{
if (chkRemmember.Checked)
{
HttpCookie myCookie = new HttpCookie("myCockie");
//Instance the new cookie

Response.Cookies.Remove("myCockie");
//Remove previous cookie

Response.Cookies.Add(myCookie);

myCookie.Values.Add("Username", this.txtUname.Text);
//Add the username field to the cookie

DateTime deathDate = DateTime.Now.AddYears(1);
//Days of life

Response.Cookies["myCockie"].Expires = deathDate;
//Assign the life period

//IF YOU WANT SAVE THE PASSWORD TOO (IT IS NOT RECOMMENDED)

myCookie.Values.Add("Password", this.txtPW.Text);
}
// call method to login into the system
Login_User(txtUname.Text, txtPW.Text);
}


Method to login into the system


public void Login_User(string username,string password)
{
// Login user into the system
}

0 comments: