I am using session value to identify the language that user chosen.
LoadMultilingual() is the method that I will call for all pages to assign the value for label.
I realized that the session value wont store value for long time, by default it store 20 minutes, so when user click any button that will reload the multilingual function, it will prompt an error.
I set the time out for session value for 60 minutes, when I try to click a button at around 45 minutes, it throw me this value.
the code below is how I declare the timeout for session
<sessionState
mode="InProc"
cookieless="true"
timeout="60" />
The code below is the code form C# that user choose their preferred language at Login page..
protected void Page_Load(object sender, EventArgs e)
{
Session["index"] = null;
Session["counter"] = null;
Session["LoginMsg"] = null;
if (Session["Lang"] == null)
{
Session["Lang"] = Request.UserLanguages[0];
}
if (Session["login"] == null)
{
Session["login"] = 1;
}
if (!IsPostBack)
{
LoadMultilingual();
if ((String)Session["Lang"] == "zh-TW")
{
ddLang.SelectedIndex = 1;
}
else
{
ddLang.SelectedIndex = 0;
}
}
Session["stop"] = null;
}
protected void ddLang_SelectedIndexChanged(object sender, EventArgs e)
{
Session["Lang"] = ddLang.SelectedValue;
LoadMultilingual();
}
The code below is the code from C# that use session for multilingual.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DisableLinkBtn();
LoadMultilingual();
}
}
private void LoadMultilingual()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(Session["Lang"].ToString());
rm = new ResourceManager("SOMaintenance.App_GlobalResources.Lang", Assembly.GetExecutingAssembly());
ci = Thread.CurrentThread.CurrentCulture;
Site1 site = this.Master as Site1;
if (site != null)
{
Label SensorTemperatureLabel = site.FindControl("label1") as Label;
string header = validate.getError("userheader", (String)Session["Lang"]);
SensorTemperatureLabel.Text = header;
}
if ((String)Session["Lang"] == "zh-TW")
{
GridView1.Columns[0].HeaderText = "用户账号";
GridView1.Columns[1].HeaderText = "用户名称";
GridView1.Columns[2].HeaderText = "用户职位";
}
btnAdd.Attributes.Add("title", rm.GetString("btnAdd", ci));
btnSearch.Attributes.Add("title", rm.GetString("btnSearch", ci));
}
Anyone has any idea why it is not working? my code work perfectly find within 40 minutes, the things is I already set the session timeout for 60 minutes.
The error is pointing to session["Lang"] this value. (its only appear around 45 minutes and after, I tried on 25minutes it's ok)
If someone visits the page before you've initialize Session["Lang"] then they'll get a null reference exception. So you need to initialize it. The best place to do that is in the Session_Start event in your global application class (global.asax).
protected void Session_Start(object sender, EventArgs e)
{
Session["Lang"] = //add your code here to figure out the language
}
By initializing it in the session start, you can ensure the variable will always be initialized (unless you later set it to null).
Also, you have cookieless authentication enabled. Do not do that! That's very insecure, as sensitive data will now be stored in the URL..
After tested all the method for THREE days. I have found out the solution.
For those which to extend Session in asp.net can use this method.
Step 1 - set session time out at web.config
Copy and paste the code below to web.config
<authentication mode="Forms">
<forms timeout="60"/>
</authentication>
<sessionState
mode="InProc"
cookieless="true"
timeout="60" />
Please take note, by default session value only last for 20 minutes, as code above, I have set it to 60 minutes.
Step 2 - configuration IIS
If you publish your web application to IIS, go to IIS Manager.
Start --> IIS Manager --> Sites --> Default Web site --> ASP
(If you didnt create a new one for your web app, else just click on the one you use for your web app)
then find Session Properties --> time-out set it to 01:00:00 it means 60 minutes.
By default you should see 00:20:00
After that click Apply on your right hand side.
Sample screen as below
After you done the step above, u can laugh your web application, then problem SOLVED!!!
Have a nice day and hope it help!
Related
First time login to the asp.net application,stored some session value
Eg: Session["Test"]="Saving Sesison";
Logout the application
When opened the browser for the second time,need to retain the same session value.
Eg: Session["Test"]="Saving Sesison";
How can i do that,can anyone help me with some solution to proceed further please.
if (!Page.IsPostBack)
{
if (Session["Test"] == null)
{
Binding data to repeater control(with out filter)
}
else
{
//Get Session value (To maintain session value across the browser)
var cookieSession = Request.Cookies["Test"]; //While opening the browser for the 2nd time,this line is getting null for all the browsers,but session is getting value for firefox & Chrome not for IE { Session["Test"] }
if (cookieSession != null &&!String.IsNullOrEmpty(cookieSession.Value))
{
Session["Test"] = cookieSession.Value;
}
Binding data to repeater control(with filter using session value)
}
}
//On Drop down selection.
protected void Dropdown_SelectedIndexChanged(object sender, EventArgs e)
{
Binding data to repeater control(based on the dropdown selected value)
Session["Test"] = Dropdown.SelectedItem.Text.ToString(); //To maintain the Dropdown selection all over the app
// Set it
if (Session["Test"] == null)
{
Session["Test"] = Guid.NewGuid().ToString();
var cookie = new HttpCookie("Test", (string)Session["Test"]);
Response.Cookies.Add(cookie);
}
}
ASP.NET Session scope is for only particular session only. So its not possible to have that kind of functionality.
But you can use Cache in same way and it will be there until you make it null or time period exceeds. But beware of fact that it will be there for every browser. So either you need to use different key(Unique key) not like 'test'
You have a few options. Though sessions should be sticky between a browser being re-launched assuming it's not in private/incognito mode. If you're finding the session is timing out too quickly you can extend it in Web.config
<system.web>
<sessionState timeout="10080" mode="InProc" />
</system.web>
Where timeout is in minutes. Note: If you're are debugging stopping and starting the debugger will reset your sessions. So will any kind of re-deployment of the application on IIS. If this is an issue for you, you should check out using something like the SQL session state provider: http://msdn.microsoft.com/en-us/library/vstudio/h6bb9cz9(v=vs.100).aspx
Another method of dealing with this is to store some kind of token in a cookie (again, only works if the browser is not in incognito/private mode, and the user data hasn't been flushed).
// Set it
if (Session["Test"] == null)
{
Session["Test"] = Guid.NewGuid().ToString();
var cookie = new HttpCookie("Test", (string)Session["Test"]);
Response.Cookies.Add(cookie);
}
// Get it
var cookieSession = Request.Cookies["Test"];
if (cookieSession != null && !String.IsNullOrEmpty(cookieSession.Value))
{
Session["Test"] = cookieSession.Value;
}
As a note using the SQL session state provider while is one of the more persistent storages there can be some serious overhead requirements. It's easy to rack up a couple of gigs worth of sessions that are being tracked.
In my experience a combination of cookies and the session provider seem to work best if you need to be very certain that some things are sticking to a users experience on the site.
Edit
So the issue with your drop down selection saver is it's always false and should never set the cookie.
protected void Dropdown_SelectedIndexChanged(object sender, EventArgs e)
{
//Binding data to repeater control(based on the dropdown selected value)
// add to Session
Session["Test"] = Dropdown.SelectedItem.Text.ToString();
// Add Cookie
var cookie = new HttpCookie("Test", (string)Session["Test"]);
Response.Cookies.Add(cookie);
}
Now to get your data back out, put this code in the actions/controllers to run BEFORE you try to access Session["Test"]
var cookieSession = Request.Cookies["Test"];
if (cookieSession != null && !String.IsNullOrEmpty(cookieSession.Value))
{
Session["Test"] = cookieSession.Value; // Should contain the selected text from the drop down
}
I am facing a problem of mixed information between sessions in my application. The problem
occurs when a user loads a page and it populates a session (Session ["Whatever"]) ... so far so good. The problem starts to happen when that same user opens the same screen on another browser tab for example. He carries other information for the same session that is used on the first screen it opened. (Here is a small example)
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["id"] != null)
{
if (Request.QueryString["id"] != "")
Session["Any"] = Request.QueryString["id"].ToString(); //<-Here it changes the session for the first tab
}
}
}
I wonder if there is a better way to do this. Has some way to create a unique identifier for each tab opened by the user? Or some unique id in order to concatenate the name of the session? So sessions would be only by open flap.
Thanked.
I am using WF 4 with ASP.NET and as part of the workflow the system may need to redirect to other pages for the user to input additional information under certain circumstances. Once they have entered that information, the system needs to resume the workflow where it left off.
I have this code so far in the initial page that kicks off the process and an activity in the workflow that sets a bookmark.
static InstanceStore instanceStore;
static AutoResetEvent instanceUnloaded = new AutoResetEvent(false);
static Guid id;
protected void Page_Load(object sender, EventArgs e)
{
SetupInstanceStore();
}
protected void btnStartWorkflow_Click(object sender, EventArgs e)
{
app = Session["applicant"];
Dictionary<string, object> workflowInputs = new Dictionary<string, object>();
workflowInputs.Add("Applicant", app.Applicant);
WorkflowApplication workflowApplication = new WorkflowApplication(new IdentityCheckActivites.IdentityCheckWorkflow(), workflowInputs);
workflowApplication.InstanceStore = instanceStore;
//returning IdleAction.Unload instructs the WorkflowApplication to persist application state and remove it from memory
workflowApplication.PersistableIdle = (a) =>
{
return PersistableIdleAction.Persist;
};
workflowApplication.Unloaded = (a) =>
{
instanceUnloaded.Set();
};
workflowApplication.Completed = (a) =>
{
instanceUnloaded.Set();
};
workflowApplication.Persist();
id = workflowApplication.Id;
workflowApplication.Run();
Session["id"] = id;
workflowApplication.Idle = (a) =>
{
instanceUnloaded.Set();
};
instanceUnloaded.WaitOne();
var bookmarks = workflowApplication.GetBookmarks();
if (bookmarks != null && bookmarks[0].OwnerDisplayName == "CC")
{
workflowApplication.Unload();
Context.Response.Redirect("SecondPage.aspx");
}
Context.Response.Redirect("FinalPage.aspx");
}
private static void SetupInstanceStore()
{
instanceStore = new SqlWorkflowInstanceStore(#"Data Source=xxx;Initial Catalog=SampleInstanceStore;User Id=xxx;Password=xxx;Asynchronous Processing=True");
InstanceHandle handle = instanceStore.CreateInstanceHandle();
InstanceView view = instanceStore.Execute(handle, new CreateWorkflowOwnerCommand(), TimeSpan.FromSeconds(30));
handle.Free();
instanceStore.DefaultInstanceOwner = view.InstanceOwner;
}
This seems to work very well in that it persists the workflow to the database and if the bookmark is set I want to redirect to a second page for the user to enter more data.
This is the part of the code that I am having problems with: -
var bookmarks = workflowApplication.GetBookmarks();
if (bookmarks != null && bookmarks[0].OwnerDisplayName == "CC")
{
workflowApplication.Unload();
Context.Response.Redirect("SecondPage.aspx");
}
Context.Response.Redirect("FinalPage.aspx");
If there's a bookmark set, I redirect to an intermediary page, if not and no user intervention was necessary, the page will just redirect to the final page.
This works if the bookmark is set, but if not the workflowApplication.GetBookmarks() statement throws an exception telling me that the workflow has completed.
I can't seem to find a way to detect at this stage which state the workflow is in so that I can redirect to the relevant page.
Maybe I have the wrong idea in general, as much as I search though, I cannot seem to find a lot of guidance on this subject.
Any ideas?
Thanks,
Jim.
I don't think there is a way to directly determine if the workflow is completed from WorkflowApplication (except for catching and inspecting the exception that is thrown).
But you could set a flag in side your Completed delegate which is executed only if the there is no bookmark set and the workflow is completed. You could then check this flag before calling GetBookmarks().
Not sure if I understand exactly, but it seems that your page controller is looking at the state of the workflow to understand what page to redirect to? The problem is that the state may be non-existent if the WF instance has ended?
If the above is correct then perhaps the approach is wrong. A more appropriate approach might be to have a WCF WF service on AppFabric (correlated by session id) handle the website request directly. (If a user in a particular session visits the site, then the WF determines what page to render, and if the user hits a certain button, then send a WCF WF message using net pipe binding)
instead of
workflow.idle
you need
wfApp.PersistableIdle
and don't forget
instanceUnloaded.Set();
Is it possible to use mixed cookieless sessions with cookie sessions?
I've an application that captured user details and then redirect for payment to an ssl page. I was wondering if this is possible?
http://www.mydomain.com/confirm.aspx
redirects to
https://www.mydomain.com/(S(za1tw2l2k02jer4fiskzlovd))/payment.aspx
Note: the session Id in the latter url.
So in essence, we use the standard cookie session for the majority of the application but when we transfer to an ssl page we pass the SessionId to the https url to pick up the session. I've tried this locally but it starts a new session.
Am I missing a trick?
Thanks
I've found a solution that seems to work
When transfering between http and https i've the following:
As you can see I'm passing the session id manually to the https page.
protected void btnPurchase_Click(object sender, EventArgs e)
{
// Confirm puchase code **
string sslPaymentPath = string.Format("https://{0}/payment.aspx?sid={1}", Request.Url.DnsSafeHost, Session.SessionID);
Response.Redirect(sslPaymentPath);
}
Upon reaching the ssl page, asp.net sees the request as a new session so I use the Start_Session method in the global.asax to abandon the newly created session and add a new session cookie with the session id passed in from the query string. Because the AquireSessionState which populates the session keyValue pair has already been run by this point I need to redirect the page back to itself to repopulate those values.
It seems to work really well :)
void Session_Start(object sender, EventArgs e)
{
bool isPaymentPage = (Request.Path.ToLower().IndexOf("payment.aspx") != -1);
// Code to load session over ssl. When changing between two sessions
if (isPaymentPage && Request.QueryString["sid"] != null && Request.IsSecureConnection)
{
string passedSessionId = Request.QueryString["sid"];
Session.Abandon();
Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", passedSessionId));
Response.Redirect(Request.Url.LocalPath, true);
}
}
Also with regard to somebody clicking on an external link whilst browsing the ssl purchase.aspx page i've written following in the global.asax to redirect traffic back to standard none ssl pages if it's not the payment page.
void Application_BeginRequest(object sender, EventArgs e)
{
bool isPaymentPage = (Request.Path.ToLower().IndexOf("payment.aspx") != -1);
// In the case someone has navigated away from the payment page redirect them back to the none secure protocol.
if (!isPaymentPage && Request.IsSecureConnection)
{
bool isAxdResource = (Request.Path.ToLower().IndexOf(".axd") != -1);
if (!isAxdResource)
{
string url = Request.Url.AbsoluteUri.ToLower().Replace("https://", "http://");
Response.Redirect(url,true);
}
}
}
Hope somebody finds this useful, I was stuck for a while trying to come up with a nice solution.
My inspiration came from this url.
I am developing an online exam application using asp.net. In the start exam page I have created a javascript countdown timer.
How can I move to the next page automatically after the timer reaches 00?
Here is my code:
long timerStartValue = 1000 ;
private int TimerInterval
{
get
{
int o =(int) ViewState["timerInterval"];
if(o==0)
{
return (o);
}
return 50 ;
}
set
{
ViewState["timerInterval"] = value;
}
}
protected void Page_PreInit(object sender,EventArgs e)
{
string timerVal = Request.Form["timerData"];
if(! String.IsNullOrEmpty(timerVal))
{
timerVal = timerVal.Replace(",", String.Empty) ;
this.timerStartValue = long.Parse(timerVal);
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(! IsPostBack)
{
this.timerStartValue = 10000; //3599000;//14400000;
this.TimerInterval = 500;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
this.timerStartValue = 3599000;
}
protected void Page_PreRender(object sender, EventArgs e)
{
System.Text.StringBuilder bldr=new System.Text.StringBuilder();
bldr.AppendFormat("var Timer = new myTimer({0},{1},'{2}','timerData');", this.timerStartValue, this.TimerInterval, this.lblTimerCount.ClientID);
bldr.Append("Timer.go()");
ClientScript.RegisterStartupScript(this.GetType(), "TimerScript", bldr.ToString(), true);
ClientScript.RegisterHiddenField("timerData", timerStartValue.ToString());
}
Thanks in advance,
sangita
It sounds like when you click the "Next" button, you are loading an entirely new page. This of course changes all the content and resets all the javascript. You can't maintain state across pages without a bit of work.
The solution to this could be to save the timer state when the next button is pressed, and pass it to the next stage. You could do this by saving the timer state to a hidden form input and submitting it along with the Next button.
The other option would be to load your questions via AJAX. Instead of moving to a new page every time the next button is clicked, you could simply replace the question portion of the page with a new question, and leave the timer intact. This is probably the solution I would use.
Are u reloading the entire page when clicking on the next button ? That may leads to realod the java script file also.So the variable values will reset.May be you can think about showing the questions /answers via Ajax.You need not reload the entire page when showing the next question.the part when you show the quiz will only be updated.so you can maintain the global variables in your java script too. Check the below link to know about partial page updating using jQuery.
http://www.west-wind.com/presentations/jquery/jquerypart2.aspx
Hope this helps.
You can put the timer in an iframe if you can't get rid of the postback.
You need a way to persist information between pages, and there's really only one possibility: To make it part of the next page request.
Now, this could be subdivided into 2 categories:
1) As part of the url: http://www.example.com/page?timer=123;
2) As part of the headers;
And number 2 opens new possibilities:
a) As part of POST data;
b) As a client-side cookie only;
c) As a cookie tied to information on the server;
Number 1, 2a and 2b can be manipulated by the user. So what you can do is store some value in a cookie, a hash for example or a database row ID, that you'll use to fetch information on the server.
tl;dr? Use a asp "Session object". It lets you keep things on the server-side and users will have no idea what they are.