Monday, July 7, 2008

Remember-Me Option On Login Page Via Cookies..

Hi EveryBody...
I am going to describe you How to apply Remember-Me Facility on you Login page. It's very simple by using og HttpCookies.The C# Code is given below...


public partial class Lgin_ThroughCookies : System.Web.UI.Page
{
HttpCookie bCookie = new HttpCookie("userLoginDetails");// cookie for remember me on this site
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.Cookies["userLoginDetails"] != null)
{
txtUname.Text = Server.HtmlEncode(Request.Cookies["userLoginDetails"].Values[0]).ToString();
txtPwd.Attributes.Add("value", Server.HtmlEncode(Request.Cookies["userLoginDetails"].Values[1]));
chkRemmberMe.Checked = true;
}
}
}
protected void BtnLogin_Click(object sender, EventArgs e)
{
int IsUserAuthenticate;
IsUserAuthenticate = AuthenticateLogin(txtUname.Text.Trim(), txtUname.Text.Trim());
if (IsUserAuthenticate == 1)//The Possible Value of "IsUserAuthenticate" is "1" or "0"
{
lblMsgLogin.Text = "Welcome! You are Logged in Now";
}
else
{
lblMsgLogin.Text = "Sorry! You are Not Logged in Now";
}
RememberMe();
Response.Redirect("../Cookie_Example/Welcome.aspx");
}
public void RememberMe()
{
if (chkRemmberMe.Checked == true)
{
// function for check that browser is cookkie enabled or not
HttpCookie TestCookie = new HttpCookie("BrowserTest");
TestCookie.Values.Add("strname", "strValue");
Response.Cookies.Add(TestCookie);
if (Server.HtmlEncode(Request.Cookies["BrowserTest"].Values[0]).ToString() != "strValue")
{
lblMsg.Text = "Browser is not cookie enabled";
}
else// if Browser is cookie enabled
{
bCookie.Values["userName"] = txtUname.Text.Trim();
bCookie.Values["userPassword"] = txtPwd.Text.Trim();
bCookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(bCookie);
lblMsg.Text = "";
}
}
else
{
Response.Cookies["userLoginDetails"].Expires = DateTime.Now.AddYears(-30);
}
}
public int AuthenticateLogin(string Username,string UPwd)
{
int LoginOutput;
if (txtUname.Text.Trim() == "sanjeev" && txtPwd.Text.Trim() == "kumar")
{
lblMsgLogin.Text = "You are loged in !! welcome";
Session["UId"] = Username;
LoginOutput = 1;
}
else
{
lblMsgLogin.Text = "You are not loged in !! Please try again111";
LoginOutput = 0;
}
return LoginOutput;
}
}

3 comments:

PradeepKumar said...

It is an Excellent code Sir
but i think it would have been more
easy if u have given comments for explanation of codes

waytoseeme said...

Great Article... Thanks alot

Anonymous said...
This comment has been removed by a blog administrator.