Set culture using cookie in asp.net, not updated - asp.net

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!
}
}
}

Related

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);
}
}

Passing parameters to remote SSRS report from ASP.NET MVC application

I have an ASP.NET MVC application that uses SSRS for reporting (using a web form and report viewer). I would like to pass two parameters dynamically to the remote report. My current implementation stores the parameters in session, which works fine on VS Development Server, but the variable is null on IIS, upon retrieval in the web form.
Here is the controller method that calls the view
public ActionResult ShowReport(string id)
{
var reportParameters = new Dictionary<string, string>();
reportParameters.Add("Param1", id);
reportParameters.Add("Param2", "user1");
Session["reportParameters"] = reportParameters;
return View("ReportName");
}
And here is how I attempt to retrieve the parameters from the web form
protected void Page_Load(object sender, EventArgs e)
{
var reportParameters = (Dictionary<string, string>)Session["reportParameters"];
foreach (var item in reportParameters)
{
ReportParameter rp = new ReportParameter(item.Key, item.Value);
ReportViewer1.ServerReport.SetParameters(rp);
}
}
Anyone know why Session["reportParameters"] is null?
Or is there some other way of passing these parameters?
You can do it too:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
var js = new JavaScriptSerializer();
string reportPath= Request.QueryString["LocalReport"];
string parametersTemp = Request.QueryString["ParametersReport"];
List<ReportParameter> parameters = null;
if (parametrosTemp != "")
{
parameters = JsonConvert.DeserializeObject
<List<ReportParameter>>(parametrosTemp);
}
GenerateReport(reportPath, parameters );
}
catch (Exception ex) {
statusReport.Value = ex.Message;
}
}
}
private void GenerateReport(string reportPath, List<ReportParameter> reportParameters)
{
reportCurrent.ProcessingMode = ProcessingMode.Remote;
ServerReport serverReport = reportCurrent.ServerReport;
serverReport.ReportServerUrl =
new Uri(AppSettings.URLReportServer);
serverReport.ReportPath = reportPath;
serverReport.Refresh();
if (reportParameters != null)
{
reportCurrent.ServerReport.SetParameters(reportParameters);
}
}
Is the problem that Session["reportParameters"] is null or is it that you don't get any parameters added to your report? Because your code, as it stands, won't add parameters to your report even if you pass them across properly and so the report parameters will be null.
SetParameters takes IEnumerable<ReportParameter> (usually a List), not a ReportParameterobject. Your code should look more like this:
protected void Page_Load(object sender, EventArgs e)
{
var reportParameters = (Dictionary<string, string>)Session["reportParameters"];
List<ReportParameter> parameters = new List<ReportParameter>();
foreach (var item in reportParameters)
{
parameters.Add(new ReportParameter(item.Key, item.Value););
}
ReportViewer1.ServerReport.SetParameters(parameters);
}

Session Seems to be lost when Button_Click event fired asp.net C#

I am coding an ASP.NET website with C# and Entity Framework.
I stored into a session a Login class I created. The class contains information such as the NetID, the Roles available to the user, and the role the user selects to login as.
The problem I am encountering is that whenever I try to get the information that is stored in the session inside of a Button_Click event, it seems to not get the information. I do not know if this is allowed. However, I also put the Login variable that contains the user information as public variable for any function inside the partial class to access and I still have the same problem accessing the information inside a Button_Click event. When I get the Session information inside the Page_Load event, I am able to get the values that were placed inside that Session.
The following is the code of my program.
public partial class Private_HomePagePortal : System.Web.UI.Page
{
Login SysUser = new Login();
protected void Page_Load(object sender, EventArgs e)
{
string[] Roles;
SysUser.Ticket = Request.QueryString["casticket"];
SysUser.GetNetID();
if (SysUser.Authenticate(SysUser.NetID))
{
SysUser.GetRoles(SysUser.NetID);
Roles = SysUser.Roles;
CasOut.Text = "Welcome <b>" + SysUser.NetID + "</b>! You are now Logged in! " + "Please choose a role you would like to sign in as." + "<br>" + "<br>";
foreach (string item in Roles)
{
if (item == "Admin")
{
Admin.Visible = true;
Admin.CssClass = "btn btn-danger";
AdminBreak.Text = "<br><br>";
}
if (item == "SuperAdmin")
{
SuperAdmin.Visible = true;
SuperAdmin.CssClass = "btn btn-danger";
SuperAdminBreak.Text = "<br><br>";
}
if (item == "Member")
{
Member.Visible = true;
Member.CssClass = "btn btn-danger";
MemberBreak.Text = "<br><br>";
}
if (item == "Convener")
{
Convener.Visible = true;
Convener.CssClass = "btn btn-danger";
ConvenerBreak.Text = "<br><br>";
}
if (item == "ITAdmin")
{
ITAdmin.Visible = true;
ITAdmin.CssClass = "btn btn-danger";
}
}
else
CasOut.Text = "You are not in the IUCommittee System!!!! If you believe this is an error, contact the IT Administrator for assistance.";
Session["Login"] = SysUser;
Login User = (Login)Session["Login"]; //Used to test information is actually in the Session
CasOut.Text = User.NetID;
}
protected void Admin_Click(object sender, EventArgs e)
{
Login User = (Login)Session["Login"];
User.SelectedRole = "Admin";
CasOut.Text = User.NetID + User.SelectedRole;
Session["Login"] = User;
}
}
I would greatly appreciate the help.
Page_Load code will be executed each time when you press the button and in that case value of QueryString value will be erased.
Be ensure that code in page_load gets executed once per page postback (use IsPostBack) or something like:
protected void Page_Load(object sender, EventArgs e)
{
if(Session["Login"]==null)
{
string[] Roles;
....
CasOut.Text = User.NetID;
}
}
OR
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string[] Roles;
....
CasOut.Text = User.NetID;
}
}

Propagting the resource culture change in master page to the content web pages

I'm a noob when it comes to web applications. But i'm trying my best to learn it using ASP.NET 2.0 and sorry for the long post.
I have a master page(M1) and 3 different content pagesC1,C2,C3 which basically use the master page M1 for filling its respective contents in the content placeholder.
All the web-forms are localized and appropriate language resource strings are added in the resource (xml) files ex: Resource.en-US.xml,Resource.de-DE.xml and so on.Finally the resources are referred in the code after setting up the appropriate current culture and current uiculture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
//where the btnSubmit is a control on the form
btnSubmit.Text = rm.GetString("Submit", Thread.CurrentThread.CurrentCulture);
Now comes the question, I have included an option of changing the display language in the master page available to the user as an asp:linkbutton with an asp:image. Whenever the user clicks the linkbutton for the desired language, the content page controls shall display the whole content strings corresponding to the culture selected.
How do i achieve this ?
Do i have to implement Session variables to include the selected
language ? Or storing in Cookie would also do the job ?
What i tried
On master page load event. I tried calling a method SetCultureSpecificInformation, which basically sets the culture and uiculture properties of CurrentThread and store the selected language inside a session variable.
Also a similar implementation on the asp:linkbutton OnClick eventhandler. In this case it modifies the session variable.
Finally refer the session variable on the content web page OnPage_Load event.
But somehow the above approach is not yielding desired results. The switching of language is not consistent. Anyone out there who can help me out with a good enough design approach for implementing the same.
Thanks in advance
Add Global.asax file: write this piece of code
void Application_BeginRequest(Object sender, EventArgs e)
{
// Code that runs on application startup
HttpCookie cookie = HttpContext.Current.Request.Cookies["CultureInfo"];
if (cookie != null && cookie.Value != null)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cookie.Value);
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cookie.Value);
}
else
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en");
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");
}
}
And on Masterpage page
protected void ddlanguage_SelectedIndexChanged(object sender, EventArgs e)
{
Session["language"] = ddlanguage.SelectedValue;
//Sets the cookie that is to be used by Global.asax
HttpCookie cookie = new HttpCookie("CultureInfo");
cookie.Value = ddlanguage.SelectedValue;
Response.Cookies.Add(cookie);
//Set the culture and reload for immediate effect.
//Future effects are handled by Global.asax
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddlanguage.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddlanguage.SelectedValue);
if (cookie.Value == "en")
{
Session["ddindex"] = 0;
}
else if (cookie.Value == "fr")
{
Session["ddindex"] = 1;
}
else if (cookie.Value == "de")
{
Session["ddindex"] = 2;
}
Server.Transfer(Request.Path);
}
}
In my case used a couple of buttons for setting culture from the master page, then used this code in the master page's code behid:
protected void IdiomButton_Click(object sender, ImageClickEventArgs e)
{
ImageButton theButton = (ImageButton)sender;
Session["culture"] = theButton.ID == "ItalianButton" ? CultureInfo.CreateSpecificCulture("it-IT") : CultureInfo.CreateSpecificCulture("en-US");
Response.Redirect(Request.RawUrl);
}
Then in every child page I used :
protected override void InitializeCulture()
{
if (Session["culture"] != null)
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(Session["culture"].ToString());
else
System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture("it-IT");
}

asp.net cookies are getting overwritten

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);
}

Resources