asp.net cookies are getting overwritten - asp.net

I have an asp.net web application with one drop down box containing language preferences (English, French). When I select French I write cookie as following -
protected void ddChoice_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("pref");
cookie.Value = ddChoice.SelectedValue;
cookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(cookie);
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddChoice.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddChoice.SelectedValue);
Server.Transfer(Request.Path);
}
and read this cookie in begin request as follows -
protected void Application_BeginRequest(object sender, EventArgs e)
{
string lang = string.Empty;//default to the invariant culture
HttpCookie cookie = Request.Cookies["pref"];
if (cookie != null && cookie.Value != null && !string.IsNullOrEmpty(cookie.Value.Trim()))
lang = cookie.Value;
if (string.IsNullOrEmpty(lang))
lang = "en-US";
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
}
This time if I check the browser cookie it is rightly set to "fr-FR". But after this, when I go to home page and refresh this page cookie gets set to blank.
I'm not sure where it is getting overwritten. Any help?

I suppose that ddChoice_SelectedIndexChanged event is generated with empty SelectedValue and therefore your cookie is empty. Try to put breakpoint in the mehod or comment it out.

As your test case in the step 4 when you hit F5 page getting postback and language dropdown of language gets set with the default top language.
For that you need to write a function in control or page where your language dropdown is placed which set the selected lanaguage.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
setLangDropdown();
}
}
private void setLangDropdown()
{
HttpCookie cookie = Request.Cookies["pref"];
string lang = string.Empty;
if (cookie != null && cookie.Value != null && !string.IsNullOrEmpty(cookie.Value.Trim()))
lang = cookie.Value;
if (!string.IsNullOrEmpty(lang))
ddChoice.SelectedValue = lang;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("pref");
cookie.Value = ddChoice.SelectedValue;
cookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(cookie);
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(ddChoice.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(ddChoice.SelectedValue);
}

Related

Cookie always return null in asp.net

net web pages,in the first one, I wrote like below:
protected void lbXML_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("RequestedXML");
cookie["xmlContent"] = hide_XML.Value;
Response.Cookies.Add(cookie);
cookie.Expires = DateTime.Now.AddMinutes(20);
Response.Write("<script>window.open('XML_Editor.aspx', '_blank', 'toolbar=no, location=no, resizable=yes, width=800px, height=500px', true);</script>");
}
In XML_Editor.aspx, I wrote code like this:
protected void Page_Load(object sender, EventArgs e)
{
Page lastPage = (Page)Context.Handler;
if (!IsPostBack)
{
HttpCookie cookie = Request.Cookies["RequestedXML"];
if (cookie != null)
{
TextBox1.Text = cookie["xmlContent"];
}
}
}
the problem is that the cookie always return null to me in Page_Load in XML_Editor.aspx, why is that?
Your problem can be you code, try it:
HttpCookie cookie = new HttpCookie("RequestedXML");
cookie.Value =hide_XML.Value;
cookie.Expires = DateTime.Now.AddMinutes(20);
Response.Cookies.Add(cookie);
Response.Write("<script>window.open('XML_Editor.aspx', '_blank', 'toolbar=no, location=no, resizable=yes, width=800px, height=500px', true);</script>");
XML_Editor.aspx
Page lastPage = (Page)Context.Handler;
if (!IsPostBack)
{
var cookie = Request.Cookies["RequestedXML"];
if (cookie != null)
{
Response.Write(cookie.Value);
}
}

Putting Data from Cookie into a List<string> with ASP.net

I'm trying to make a shoppingcart using a cookie.
Every item has a Id which is put into the cookie.
Now I'm trying to put my cookie values into a List but I can't really find how to do it.
I want every value to be in a seperate index, is this possible?
Making the cookie:
HttpCookie myCookie = new HttpCookie("MyTestCookie");
Response.Cookies.Add(myCookie);
Adding a Id on buttonclick:
protected void Button1_Click(object sender, EventArgs e)
{
Request.Cookies["MyTestCookie"].Values.Add("", "3");
Response.Write(Request.Cookies["MyTestCookie"].Values.ToString());;
}
Try this
public void SetCookiesList(List<string> listOfCookies)
{
var req = HttpContext.Current.Request;
HttpCookie cookie = req.Cookies["cookieName"];
if (cookie != null)
{
var cookieVal = cookie.Value;
if (!string.IsNullOrEmpty(cookieVal))
listOfCookies.Add(cookieVal);
}
}

How to implement keep me logged in asp.net

How to implement keep me logged in asp.net using login control and membership in asp.net
By adding a checkbox..
And if it's checked you have to create a cookie with authentication and if it's not checked you have to put it in session
http://msdn.microsoft.com/en-us/library/system.web.sessionstate.httpsessionstate.aspx
Another way is to implement a cookie that's not persistent if it's unchecked like that:
int timeout = rememberMe ? 525600 : 30; // Timeout in minutes, 525600 = 365 days.
var ticket = new FormsAuthenticationTicket(userName, rememberMe, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
cookie.HttpOnly = true; // cookie not available in javascript.
Response.Cookies.Add(cookie);
First you need to create Cookie on login button click as follows and Store the Login Detail in it
protected void btnLogin_Click(object sender, System.EventArgs e)
{
string username = txtUsername.Text;
string Password = txtPassword.Text;
// Create Cookie and Store the Login Detail in it if check box is checked
if ((CheckBox1.Checked == true)) {
HttpCookie mycookie = new HttpCookie("LoginDetail");
mycookie.Values("Username") = txtUsername.Text.Trim();
mycookie.Values("Password") = txtPassword.Text.Trim();
mycookie.Expires = System.DateTime.Now.AddDays(1);
Response.Cookies.Add(mycookie);
}
Response.Redirect("Default2.aspx");
}
then check if cookie exists (is remember me checked), if yes fill the details as follows-
protected void Page_Load(object sender, System.EventArgs e)
{
//check if cookie exist then login page from
if ((Response.Cookies("LoginDetail") != null)) {
//Username
string uname = Response.Cookies("LoginDetail").Values("Username").ToString();
string pass = Response.Cookies("LoginDetail").Values("Username").ToString();
Response.Redirect("Default2.aspx");
}
}

Asp.NET cookies returning null

I'm trying to save a cookie when a button is clicked like so...
protected void btn_login_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("test");
cookie["work"] = "now";
cookie.Expires = DateTime.Now + new TimeSpan(1, 0, 0, 0);
cookie.Domain = ".cookie.com";
Response.Cookies.Add(cookie);
}
Then on the page_load I am reading the cookie...
protected void Page_Load(object sender, EventArgs e)
{
string a = Response.Cookies["test"]["work"];
}
But it keeps coming back null. I am running this under localhost and I read that cookies won't save under localhost so I edited my host file to say
127.0.0.1 test.cookie.com
When I used Fiddler to see what was getting posted to the header of the page. It looks like this...
test/work = now
test =
So I can see that it is getting set but for some reason when I read it in it returns null.
On the page_load change it from Response.Cookies to Request.Cookies.
The Response object is for sending data back. The Request object has data that is passed to you.
example:
String a = Request.Cookies["test"]["work"];
Note that if the cookie doesn't exist, then this will cause a null reference exception.
Usually you should do something like:
protected void Page_Load(object sender, EventArgs e) {
HttpCookie cookie = Request.Cookies["test"];
String a = String.Empty;
if (cookie != null) {
a = cookie["work"];
}
}
Try this
Response.Cookies["work"].Value = "Value1"
Refer this for more information.
On pageload for reading the cookie try
string value = Request.Cookies["work"].Value

Set culture using cookie in asp.net, not updated

I'm using asp.net and want to make it possible for the user to set the culture to use in the website by himself. In MasterPage I have the following code to set a language cookie:
protected void Page_Load(object sender, EventArgs e) {
if (Request.QueryString["setLanguage"] != null)
{
HttpCookie languageCookie = new HttpCookie("language");
languageCookie.Value = Request.QueryString["setLanguage"];
languageCookie.Expires = DateTime.Now.AddDays(10);
Response.SetCookie(languageCookie);
}
}
In Global.asax I use the cookie like this:
protected void Application_BeginRequest(object sender, EventArgs e) {
HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["language"];
if (languageCookie.Value != null)
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(language);
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(language);
}
}
The problem is that after I set the cookie with Response.SetCookie I need to reload the page to get the new language. How can I make my code so when the user set a new language the page is reloaded with the new language directly?
You can do
Response.Redirect(Request.PathAndQuery);
But why not just set the language after setting the Cookie? You can even use the BeginRequest event to check for specific input being posted and use it as an alternative condition for setting the language.
I had the same issue with the language being selected by the user. In order for it to work you have to do it on
protected override void InitializeCulture()
{
HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["language"];
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(language);
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(language);
}
In order for it to work on every page of the site, I created a class that inherited from System.Web.UI.Page and implemented there
public class myBasePage : System.Web.UI.Page
{
protected override void InitializeCulture()
{
HttpCookie languageCookie = System.Web.HttpContext.Current.Request.Cookies["language"];
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(language);
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(language);
base.InitializeCulture();
}
}
from then on I had all my pages inherit from myBasePage.
This way, I used a Server (Postback) control to set the language and the page would get reloaded, and the language would be set.
If you are using Asp.Net MVC
//A foreigner, has possibly brew a cookie for me
public class SpeakNativeTongueAttribute : ActionFilterAttribute, IActionFilter
{
const string cookieName = "culture";
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
var cookieKeys = filterContext.RequestContext.HttpContext.Request.Cookies.AllKeys;
if (cookieKeys.Contains(cookieName))
{
//eat the cookie
var theCultureCookie = filterContext.RequestContext.HttpContext.Request.Cookies[cookieName];
var theCulture = theCultureCookie.Value;
//say thanks in native tongue
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo(theCulture);
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo(theCulture);
}
else
{
//Didn't receive a cookie, don't speak their language, those bastards!
}
}
}

Resources