Automatically login for improper Logouts(Check on Remember me on this Computer).


If you carefully observe any of the websites like dotnetspider you may see this option(remember me on this computer).If you had not log out properly i.e.( on click of sign out or Log out button link).when you revisit the website will automatically log in without giving your credentials(i.e.User Name and Password).if you check on remember me Option.How to work out this scenario in your c# code.i will explain with Code snippets real time images

As i mentioned in the Article Summary an improper Log out will revisit the Dashboard or Home Page or Inbox page without giving his/her Credentials.I think one reason behind for this sometimes when you are working in the website there is a possibility that your computer may shutdown automatically for various reasons(Power off,Hardware problem e.t.c...)or the User do not want to log in with his Credentials he wants to visit the Main page for his frequent visits of the website in the same computer.For this they may use this technique to store the data(Username and Password) in your(Client) machine and revisit the Home page or Main page without re-log in in the website.

How to achieve this Task

In Asp.net programming there is a technique to store the data in Client Machine and that data will be stored/resides in the form of text files.That data will be very small in size less than a 4kb that is none other than cookies.Yes with Cookies we can achieve this Task.

Add cookies through code :

Now we know that the Cookies will do the necessary task but how to use them in Coding we need to know for that below is the Code snippet for that.



HttpCookie cookie = new HttpCookie("UserName");
cookie.Value = txtUserName.Text;
cookie.Expires = DateTime.Now.AddYears(1); //==== Make sure you have set expire time
Response.Cookies.Add(cookie);






When you add a Cookie through coding there are four important things to remember one write the Cookie name in the cookie class constructor.

And next one is the cookie value what value you are storing the cookie for that you have a cookie Property called value.

And Next one is the Expire time of the Cookie and it will be available as an property in cookie class.Here you can mention the sustainability of the cookie or expiry time of the cookie.You can add seconds,Minutes,Hours,days,Months and years...

Last but not least is adding the cookie through add() method .

This is about add a cookie through coding..

Fetch the Cookie value through Coding :

Now its time to fetch the cookie value through coding the cookie which you added through code so how to fetch the cookie value through asp.net coding.


Request.Cookies["UserName"].Value


for Check if the cookies exists in coding


if(Request.Cookies["UserName"] !=null)
{

}


Now we had seen how to add a cookie , how to request a cookie and how to Check a cookie with all this Example given above our task becomes much more easier.

Now i will store User Name and Password in master page i will store the url value of a
Cookie.

When to add our First Cookie in Our Programming :

So adding a cookie is a tricky one in your code.whenever your first login was successful You need to add UserName and Password to your Cookie.

store cookies

and your Master Page you add the url store...

Url store cookie Master

Now in Log in page i add request for a cookie coding.

Request cookie in login page


If cookie Found, Now i will create a click event delegate to click the btnlogin

Event Delegate

with the cookie Information found in request i will send to database and visit the Main page/Home page...


Now up to here it is over.But we have not yet finish we need to do code further because of browser settings.

Now i debug my code and find that i am unable to store the cookie value whats the problem in the code i am unable to figure it out.Then i started to Google it but my search was in vain.Later i suddenly realize that my internet option settings was gone wrong.Because of the following setting my cookies get cleared.

Browser History exit

Now after Unchecked it i am able to retrieve cookies.But i can not tell to client to set the browser settings like that.without manually setting this option i need to solve this Problem

I published the website in IIS. There i found an interesting thing.I had gone to IIS and click on help which is there on right panel and search about cookies.

Cookies Help

Now i Understand about reading this when we click Authentication settings we can set Cookie seetings.

Autheneticatiion

Now i will double click on that option and set my cookie settings.

Cookie settings in iissss



Change the Url as per your requirement.

There are four Modes in this which from iis help i got this information.

Do not use cookies - Cookies are not used.


Use cookies - Cookies are always used, regardless of device.


Auto Detect - Cookies are used if the device profile supports cookies. Otherwise, no cookies are used. For desktop browsers that are known to support cookies, ASP.NET checks to determine whether cookies are enabled.


Use device profile - Cookies are used if the device profile supports cookies. Otherwise, no cookies are used. ASP.NET does not check to determine whether cookies are enabled on devices that support cookies. This is the default setting.


Now for My requirement i use the UseCookies.

Cookies information iis

Now i had Observed the webconfig file i had seen this.

webconfig cookies

Now without concern of my browser setting i can read and add a cookie.

and in Logout.aspx i delete the Cookies from the Client Machine with the following code.

Delete a Cookie :



HttpCookie cookie = new HttpCookie("UserName");
cookie.Value = txtUserName.Text;
cookie.Expires = DateTime.Now.AddYears(-1); //==== Make sure you have set expire time
Response.Cookies.Add(cookie);




This is all about the Article..

Full code


protected void btnLogin_Click(object sender, EventArgs e)
{
BELogin objBELogin = new BELogin();
BCLogin objBCLogin = new BCLogin();
string strErr = null;
Hashtable objHash = null;
DataSet objDs = null;

try
{
objBELogin = new BESynapseUsers.BELogin();
objBCLogin = new BCSynapseUsers.BCLogin();

//objBELogin.strUserName = txtUserName1.Value.Trim();
//objBELogin.strPassword = txtPassword1.Value.Trim();

if (Request.Cookies["UserName"] != null && txtUserName1.Value.Trim() != "")
{
objBELogin.strUserName = Request.Cookies["UserName"].Value;
objBELogin.strPassword = Request.Cookies["Password"].Value;
}

//if ((chkRemMe.Checked) && (Request.Cookies["UserName"] != null))
//{
// HttpCookie cookie = new HttpCookie("UserName");
// string strPageName = null;
// strPageName = txtUserName1.Value.Trim();
// cookie.Value = txtUserName1.Value.Trim();
// cookie.Expires = DateTime.Now.AddDays(7); //==== Make sure you have set expire time
// Response.Cookies.Add(cookie);

// HttpCookie cookie1 = new HttpCookie("Password");
// string strPwd = null;
// strPageName = Strings.LCase(Request.Url.ToString());
// cookie1.Value = txtPassword1.Value.Trim();
// cookie1.Expires = DateTime.Now.AddDays(7); //==== Make sure you have set expire time
// Response.Cookies.Add(cookie1);

//}

if (txtUserName1.Value != "" && txtUserName1.Value != "Username" && txtPassword1.Value != "Password" && txtPassword1.Value != "")
{
objBELogin.strUserName = txtUserName1.Value.Trim();
objBELogin.strPassword = txtPassword1.Value.Trim();

}

if (HttpContext.Current.Application["SA_ConfigKeys"] == null)
{
objHash = new Hashtable();
}
else
{
objHash = (Hashtable)HttpContext.Current.Application["SA_ConfigKeys"];
}

if (!objBCLogin.CheckLogin(objBELogin, ref objDs, ref objHash))
{
if (Convert.ToInt32(objBELogin.nReturn) == 2)
{
strErr = Convert.ToString(GetLocalResourceObject("msgJSUsername"));
}
else if (Convert.ToInt32(objBELogin.nReturn) == 3)
{
strErr = Convert.ToString(GetLocalResourceObject("msgJSPassword"));
}
else if (Convert.ToInt32(objBELogin.nReturn) == 5)
{
strErr = Convert.ToString(GetLocalResourceObject("msgInvalidADUser"));
}
else
{
strErr = objBCLogin.GetLastError();
}
lblError.Text = strErr;
return;
}

if ((objHash != null))
{
HttpContext.Current.Application.Add("SA_ConfigKeys", objHash);
}
else
{
return;
}


//Checks the customer expiry
string strExpDate = Convert.ToString((Convert.IsDBNull(objDs.Tables[0].Rows[0]["CUST_Dtm_ExpireDate"]) ? "" : objDs.Tables[0].Rows[0]["CUST_Dtm_ExpireDate"]));

if (strExpDate != "")
{
DateTime dtsysdate = DateTime.Now.Date;
// DateTime dtCustExpDate = Convert.ToDateTime(strExpDate).Date;
// Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); System.Threading.Thread.CurrentThread.CurrentCulture.Name
// DateTime dtCustExpDate = DateTime.Parse(strExpDate);
System.IFormatProvider format = new System.Globalization.CultureInfo("");
DateTime date2 = Convert.ToDateTime(strExpDate, System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat);
DateTime dtCustExpDate = DateTime.ParseExact(strExpDate, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
if (dtCustExpDate < dtsysdate)
{
lblError.Text = Convert.ToString(GetLocalResourceObject("msgCustExpDate"));
return;
}
}

if (!DoPostLogin(objBELogin, objDs))
{
lblError.Text = Convert.ToString(GetLocalResourceObject("msgInvalidADUser"));
return;
}

if (!ChecksNoOfSessions(objBELogin))
{

// lblError.Text = Convert.ToString(GetLocalResourceObject("msgNoOfSessions"));

return;
}


if (!BCCommon.SetPreferences(objBESession.strMBCId))
{
return;
}
StoreCookieValues();

GoToDashboardPage();

}


catch (Exception ex)
{
lblError.Text = ex.Message;
SetError(ex.ToString(), m_objBEError, m_objBCError);
return;
}
}
public void StoreCookieValues()
{
if (chkRemMe.Checked == true)
{
Response.Cookies["ckUSERNAME"].Value = txtUserName1.Value;
Response.Cookies["ckUSERNAME"].Expires = DateTime.Now.AddDays(7);
Response.Cookies["ckPASSWORD"].Value = txtPassword1.Value;
Response.Cookies["ckPASSWORD"].Expires = DateTime.Now.AddDays(7);



if (Request.Cookies["UserName"] == null)
{
HttpCookie cookie = new HttpCookie("UserName");
string strPageName = null;
strPageName = txtUserName1.Value.Trim();
cookie.Value = txtUserName1.Value.Trim();
cookie.Expires = DateTime.Now.AddDays(7); //==== Make sure you have set expire time
Response.Cookies.Add(cookie);

HttpCookie cookie1 = new HttpCookie("Password");
string strPwd = null;
strPageName = Strings.LCase(Request.Url.ToString());
cookie1.Value = txtPassword1.Value.Trim();
cookie1.Expires = DateTime.Now.AddDays(7); //==== Make sure you have set expire time
Response.Cookies.Add(cookie1);
}

}
else
{
//Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-7);
//Response.Cookies["Password"].Expires = DateTime.Now.AddDays(-7);
// Response.Cookies["ckUSERNAME"].Expires = DateTime.Now.AddDays(-7);
// Response.Cookies["ckPASSWORD"].Expires = DateTime.Now.AddDays(-7);
// Response.Cookies["UrlStored"].Expires = DateTime.Now.AddDays(-7);
}
}



I Hope you had enjoyed of reading this Article and got some vital information about how to use cookies in your asp.net website.


Attachments

Article by srirama
A Good advice from parent to a Child , Master to a Student , Scholar to an Ignorant is like a doctor prescribed pill it is bitter to take but when they take it will do all good for them --- Bhushan

Follow srirama or read 74 articles authored by srirama

Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: