Tuesday, July 1, 2014

Code of creating and clearing cookie for 'Remember Me' Check-box At Login page !!!



We all do coding for remembering the User-name and Password of user by creating cookie ( If user checks 'Remember Me' check-box while Login) or sometime it may happens that we forget to write a code for that functionality or even if we write a code, it doesn't work because of some mistakes. And we never bother to clear that cookie when next time that user log-outs and unchecked the 'Remember Me' check-box and Login again.

Please find the below code which we should use at Login page to create and clear cookie:
protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                //Uncheck the 'Remember Me' checkbox.
                RemMeCheckBox.Checked = false;

                //Check if cookie contains data.
                HttpCookie cookie = Request.Cookies["TNCredentialCookieOfAdmin"];
                if (cookie != null)
                {
                    //If cookie is not null and contains data, display data to user(as he wished to remember his Username and password.)
                    string username = cookie.Values["Username"].ToString();
                    string password = cookie.Values["Password"].ToString();
                    if (username != null)
                    {
                        txtUserName.Text = username;
                    }
                    if (password != null)
                    {
                        txtPassword.Attributes.Add("value", password);
                    }
                    //Check the 'Remember Me' checkbox.
                    RemMeCheckBox.Checked = true;
                }
                //your other code
                .
                .
                .
            }
        }
        catch (Exception ex)
        { }
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {          
            //your other code
            .
            .
            .
            //code for 'Remember Me' checkbox
            if (RemMeCheckBox.Checked == true)
            {
                //If 'Remember Me' checkbox is checked, create a cookie which will maintain Users Username and Password.
                HttpCookie createCookie = new HttpCookie("TNCredentialCookieOfAdmin");
                createCookie.Values["Username"] = txtUserName.Text.ToString();
                createCookie.Values["Password"] = txtPassword.Text.ToString();
                Response.Cookies.Add(createCookie);
            }
            else
            {
                //If 'Remember Me' checkbox is not checked, clear the cookie.
                Response.Cookies["TNCredentialCookieOfAdmin"].Expires = DateTime.Now;
            }
        }
        catch (Exception ex)
        { }
    }



No comments:

Post a Comment