Value from Session is lost in IE - c#

All!
I've website with multiples idioms. I can select/change idiom in any page. The idiom is saved in Session, if I change idiom, I changed session value.
The problem is:
If I change my default idiom in Homepage and go to other page, this session value is lost, consequently, this page not translated.
But if I reload this page one or more times, translates current page.
This occur just in Webserver (Pheonix - US). In localhost, session not lost value.
This issue occur to any page, but just in IE. To Chrome works correctly.
Below, my source code to Homepage. To all pages is basically this code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//to set default session value. (first time).
if (Session["idioma"] == null)
{
string idioma = CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToString();
Idioma.MudaCultura(idioma);
Session["idioma"] = idioma;
}
//if I've other session value (Change Idiom).
else if (Session["idioma"] != null)
{
string idioma = Session["idioma"].ToString();
Idioma.MudaCultura(idioma);
}
lblWelcome.Text = Idioma.RetornaMensagem("welcome");
btnRequestAccess.Text = Idioma.RetornaMensagem("btnRequestAccess");
btnTickets.Text = Idioma.RetornaMensagem("btnTickets");
btnManager.Text = Idioma.RetornaMensagem("btnManager");
btnManageFolders.Text = Idioma.RetornaMensagem("btnManageFolders");
IdiomaList.Items.Add("PORTUGUÊS");
IdiomaList.Items.Add("ENGLISH");
IdiomaList.Items.Add("ESPAÑOL");
//Set value that show in DropDown list according to Session value.
if (Session["idioma"].ToString() == "pt")
{
IdiomaList.SelectedValue = "PORTUGUÊS";
}
else if (Session["idioma"].ToString() == "en")
{
IdiomaList.SelectedValue = "ENGLISH";
}
else if (Session["idioma"].ToString() == "es")
{
IdiomaList.SelectedValue = "ESPAÑOL";
}
}
}
protected void Idioma_OnChange(object sender, EventArgs e)
{
if (IdiomaList.SelectedValue == "PORTUGUÊS")
{
Idioma.MudaCultura("pt");
Session["idioma"] = "pt";
}
else if (IdiomaList.SelectedValue == "ENGLISH")
{
Idioma.MudaCultura("en");
Session["idioma"] = "en";
}
else if (IdiomaList.SelectedValue == "ESPAÑOL")
{
Idioma.MudaCultura("es");
Session["idioma"] = "es";
}
lblWelcome.Text = Idioma.RetornaMensagem("welcome");
btnRequestAccess.Text = Idioma.RetornaMensagem("btnRequestAccess");
btnTickets.Text = Idioma.RetornaMensagem("btnTickets");
btnManager.Text = Idioma.RetornaMensagem("btnManager");
btnManageFolders.Text = Idioma.RetornaMensagem("btnManageFolders");
}

I have experienced the same problem with IE losing the session each time the page reloads. In my case it was caused by the server having an out of sync timezone which caused the cookies to already be expired when it reached the client. It seems most browsers still work, whereas IE will destroy the cookies when navigating to the next page.

This can be a browser setting problem.
to solve this problem you can view as below link.
Cookie blocked/not saved in IFRAME in Internet Explorer
I hope it will helpful to you.

Related

Logout user after three unsuccesfull attempts - ASP.NET

I am new to programming. In my web application, user will receive a popup alert when he attempts to access restricted page. After three unsuccessful attempts i want him to be logged-out(i.e redirect to logout page). My question is, how to capture each failed attempts.
My existing code for giving alerts,
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Convert.ToString(Session["StaffID"]) != "1" || Convert.ToString(Session["StaffID"]) == null || Convert.ToString(Session["StaffID"]) == "")
{
Response.Write("<script language='javascript'>window.alert('You are not allowed to view this page');window.location='Mainpage.aspx';</script>");
}
}
You can capture each failed attemped by using another session . Please check below code. I am test this in ASP.NET MVC. Session["StaffID"] is your condition check or any condition so use another session to count attempt. Hope it will help you.
public ActionResult OnInit()
{
base.OnInit(e);
var accessCount = Convert.ToInt16(Session["AccessCount"]);
if (Convert.ToString(Session["StaffID"]) != "1" || Convert.ToString(Session["StaffID"]) == null || Convert.ToString(Session["StaffID"]) == "")
{
//Response.Write("<script language='javascript'>window.alert('You are not allowed to view this page');window.location='Mainpage.aspx';</script>");
accessCount++;
if (accessCount <= 3)
{
Session["AccessCount"] = accessCount;
return Content("<script>alert('You are not allowed to view this page')</script>");
}
else
{
Session["AccessCount"] = 0;
return RedirectToAction("logout");
}
}
}

Inconsistent behavior in asp.net webform during site-level localization

I've setup a web site to be localized using Global resources only. I'm having a hard time figuring out why a page is always giving inconsistent behavior every time I trigger a culture change through a drop down list. Here are my resource files:
Resources:
Setup
Here is the Base Page that is inherited by all pages:
public partial class BaseWebForm : Page
{
protected override void InitializeCulture()
{
if (Session["UserLanguage"] != null)
{
String selectedLanguage = Session["UserLanguage"].ToString();
UICulture = selectedLanguage;
Culture = selectedLanguage;
CultureInfo culture = CultureInfo.CreateSpecificCulture(selectedLanguage);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
base.InitializeCulture();
}
}
I'm using a Session variable, UserLanguage, to manage selected language. My site assumes en-US as default language and the drop down is displayed on the login page. That means the user cannot change language on any page as, upon login page, a service retrieves available languages.
I'm using Master page and I've handled the menus, breadcrumb SiteMapPath, and LTR-RTL there.
On the actual page, here is a brief:
public partial class PublicLogOn : BaseWebForm
{
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (Request.IsAuthenticated)
{
SiteLogger.NLogger.Info("Request Authenticated");
SiteLogin.RedirectToDefaultPage();
}
#region Handle Return URL
if (HttpContext.Current.Request.QueryString["ReturnUrl"] != null && !String.IsNullOrEmpty(HttpContext.Current.Request.QueryString["ReturnUrl"]))
{
var tempUrl = HttpContext.Current.Request.QueryString["ReturnUrl"];
SiteLogger.NLogger.Info("Return URL : " + tempUrl);
if (tempUrl.Contains(#"/SecuredArea/AdminArea/"))
{
buttonLogOn.Visible = false;
// buttonAdminLogOn.Visible = true;
}
else if (tempUrl.Contains(#"/SecuredArea/EmployeeArea/"))
{
buttonLogOn.Visible = true;
// buttonAdminLogOn.Visible = false;
}
else
{
// buttonLogOn.Visible = buttonAdminLogOn.Visible = true;
buttonLogOn.Visible = true;
}
}
#endregion
if (!Page.IsPostBack)
{
SiteLogger.NLogger.Info("Loading Languages and Directories");
// Actual language loading
if (!LoadLanguages() || !LoadDirectories())
{
SiteLogger.NLogger.Info("Loading Languages or Directories failed!");
return;
}
SiteLogger.NLogger.Info("Completed : PublicLogOn.PageLoad");
}
// Don't know why this fails and the drop-down still shows en-US even culture is ur-PK
//if (Session["UserLanguage"] != null)
//{
// DDLLanguages.SelectedValue = Session["UserLanguage"].ToString();
//}
}
catch (Exception ex)
{
SiteLogger.NLogger.Error("Error in PublicLogOn.Page_Load", ex.Message);
}
}
private Boolean LoadLanguages()
{
Boolean methodResult;
try
{
SiteLogger.NLogger.Info("In Load Languages");
// This line also mess up
// Session["UserLanguage"] = null;
DDLLanguages.Items.Clear();
var fetchedLanguages = UserManagePage.GetOrganizationLanguages();
foreach (var oneFetchedLanguage in fetchedLanguages)
{
DDLLanguages.Items.Add(new ListItem(oneFetchedLanguage.LanguageSymbol, oneFetchedLanguage.LanguageSymbol));
}
if (fetchedLanguages.Count() == 1)
{
DDLLanguages.Enabled = false;
}
methodResult = true;
}
catch (Exception exp)
{
SiteLogger.NLogger.Error("Error in load languages : ", exp.ToString());
labelMessage.Text = MessageFormatter.GetFormattedErrorMessage("Error retrieving organization languages.");
methodResult = false;
}
return methodResult;
}
private Boolean LoadDirectories()
{
// Nothing to-do with code-in-question
}
protected void ButtonLogOn_Click(object sender, EventArgs e)
{
// Nothing to-do with code-in-question
}
protected void DDLLanguages_SelectedIndexChanged(object sender, EventArgs e)
{
Session["UserLanguage"] = DDLLanguages.SelectedValue;
// Reload-hack. Was recommended on SO.
Response.Redirect(Request.Url.AbsolutePath);
}
}
After all of this, there one more point where the session variable is used as read-only: I'm using a header to tell my server that the client's using xyz language and that server should return translated data, where applicable:
public class CustomInspectorBehavior : IClientMessageInspector, IEndpointBehavior
{
#region IClientMessageInspector
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
string languageIdentifier;
if (HttpContext.Current.Session["UserLanguage"] != null)
{
languageIdentifier = HttpContext.Current.Session["UserLanguage"].ToString();
}
else
{
languageIdentifier = CultureInfo.CurrentCulture.ToString();
}
var typedHeader = new MessageHeader<string>(languageIdentifier);
var untypedHeader = typedHeader.GetUntypedHeader("LanguageIdentifier", "");
request.Headers.Add(untypedHeader);
return null;
}
#endregion
#region IEndpointBehavior
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
var inspector = new CustomInspectorBehavior();
clientRuntime.MessageInspectors.Add(inspector);
}
#endregion
}
Results
Expected: I change the selected value on the drop-down and the page reload with new language + secure the selection in session. Now upon going to other pages, the new language is presented.
Actual: "LOL". I change the selected value from the default en-US to ur-PK and the web site updates to Urdu. All pages are in Urdu. I try to select en-US again and I realize I'm stuck with Urdu. The base page's InitializeCulture() trigger way too early and it finds Session["UserLanguage"] = ur-PK'. After that thePage_Loadof thePublicLogOnpage triggers effectively putting Drop down's selected value to still ur-PK. After thatDDLLanguages_SelectedIndexChangedof thePublicLogOn` page triggers updating the session variable to the selected value which is set to ur-PK from the recent PageLoad. Issue. The Hack triggers in the end repeating the cycle one more time.
I'm trying a number of things but end in this mini-loop. Any help will be appriciated.
You could do a redirect after your set the new language in the session.
I re-did the whole thing from scratch. Turns out there was one or two variables being static at IIS level which were the cause of all the pain.

Fields re-initialized in PageLoad c#

I am perplexed, and maybe I am just familiar with the properties of pageLoad, IsPostBack, or IsCallback. I created a Boolean variable called "first" and set it to True.
First time through PageLoad, there is a line of code if first = False, if so, write = true.
Then I have a Run_write routine attached to a button, when it runs, if the user response Yes, to the initial question, I make another group of radio buttons visible and set first to false. (i ran this in debug, and I know it hits this line of code) ... so the write to sql is ignored because write == false and the window reappears with the new set of Buttons... Great!
Furthermore, I go through the PageLoad routine again, and it hits the line if (!first), set write to TRUE. my issue is first has been re-set to true? What am I missing?
Note, I was able to work around this by utilizing whether the new set of buttons is checked, but I may not want to go this route, and I do want to understand what is going on.
code is below.
namespace MEAU.Web.Components.SupportCenter
{
public partial class feedback : System.Web.UI.Page
{
String login;
String myurl;
String response;
String s_call;
String p_ship;
String wrnty;
Boolean write;
Boolean first = true;
protected void Page_Load(object sender, EventArgs e)
{
login = Sitecore.Security.Accounts.User.Current.Profile.Email;
myurl = Request.QueryString["value"];
s_call = "No";
p_ship = "No";
wrnty = "No";
// Hide the question Buttons
scall.Visible = false;
parts.Visible = false;
wrnt.Visible = false;
lit.Visible = false;
write = false;
if (!first)
write = true;
}
protected void Run_Write(object sender, EventArgs e)
{
// Get Reponse
if (yes.Checked)
{
response = "Yes";
// Display the quesiton buttons, and Hide the NO button
scall.Visible = true;
parts.Visible = true;
wrnt.Visible = true;
lit.Visible = true;
no.Visible = false;
first = false;
// Did this Prevent a Service call?
if (scall.Checked)
{
s_call = "Yes";
write = true;
}
// Did this Prevent a parts shipment?
if (parts.Checked)
{
p_ship = "Yes";
write = true;
}
// Is this under warranty?
if (wrnt.Checked)
{
wrnty = "Yes";
write = true;
}
// write = true;
}
if (no.Checked)
{
response = "No";
write = true;
}
if (write == true)
{
SqlConnection conn = new SqlConnection(Sitecore.Configuration.Settings.GetConnectionString("feedback"));
SqlCommand cmd = new SqlCommand("Insert_fb", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#login", login);
cmd.Parameters.AddWithValue("#url", myurl);
cmd.Parameters.AddWithValue("#response", response);
cmd.Parameters.AddWithValue("#dateTime", DateTime.Now);
cmd.Parameters.AddWithValue("#serviceCall", s_call);
cmd.Parameters.AddWithValue("#partsShipment", p_ship);
cmd.Parameters.AddWithValue("#warranty", wrnty);
try
{
conn.Open();
cmd.ExecuteNonQuery();
Response.Write("<script type='text/javascript'>parent.$.fancybox.close();</script>");
Response.Write("<script type='text/javascript'>return false;</script>");
}
catch (Exception ex)
{
throw new Exception("Error on file update" + ex.Message);
}
finally
{
conn.Close();
}
}
}
}
}
Every HTTP request to your site creates a new instance of your page class.
Instance state is not preserved.
Instead, you need to store the state in session or ViewState, depending on what you want to apply to.
Page_Load will be called every time your server is requested for the page. This includes post-backs.
You can check IsPostBack to see if the current Page_Load execution is for the first display of the page, or a subsequent post-back.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
// Do first-time things
}
else
{
// Do non-first-time things
}
}
Note that the particular instance of your page object will not persist from access to access. So there may be some information that you need to initialize every time the page is called.
Every time you visit the page, you're creating a new instance of the class.
To distinguish a page load from a user clicking a button vs. a user arriving on the page for the first time, you want to check the IsPostBack property.
So rewrite your if along the lines of
// Code that always executes
if (IsPostBack)
{
// Code that only executes on initial page load
}
else
{
// Code that only executes when a postback event occurs
// e.g. A user clicks on a button.
}
There are some ways by which you can maintain the state or value of the controls, so I have been maintaining the Viewstate of the controls in the not is postback, as check of
(!IspostBack) // means when page loads first time
and whatever written in the else means when postback occurs in which you can maintain the viewstate of the objects.
Also we can use the session, if Viewstate is not used.
Rykiel,
the basic concept of the web is (state-less), and that why you have to handling, but anyway you can read about page life cycle I recommend you read it http://www.codeproject.com/Articles/20659/The-ASP-NET-Page-Lifecycle-A-Basic-Approach
you can use
if(!isPostBack)
{
first=true;
this portion of code only run when the page is requested first time
}else
{
first = false;
}
if you change the value of control in the page or click a button isPostBack will be true. but if you refresh the page or hit F5 you page will be requested again and isPostBack will be false;.
also you can use cookies or session variable (I also recommend do not load too much the Session Variable). try to read the prior link and you will be more clear where put your code to get the best performance.
J.S.
The answers on here are good, but technical. I will try to explain a little of what is happening.
When a browser requests your page, and on the server, a new instance of your class is created.
ASP.NET then runs the rest of the page, starting with your page_load. This will call all your other functions and then render the HTML as a response to your request and send it back to the browser. I like to explain this as a disconnected environment. Once the response is sent, everything is disposed of in a sense. Your variables, previous work, etc... are all gone. The Server as far as it is concerned, never expects to get anything from the browser again... its done its job. It took your request for a page, created a result and posted it back to the browser. Done.
So, think of your code as a new request each time it is called.
You can use the IsPostback as stated by ThatBlairGuy, because that will return true if you are responding to a postback from the browser, meaning that it has already served up this page to the browser on the previous postback.

How to detect page refresh in .net

I have a Button_click event. While refreshing the page the previous Postback event is triggering again. How do I identify the page refresh event to prevent the Postback action?
I tried the below code to solve it. Actually, I am adding a visual webpart in a SharePoint page. Adding webpart is a post back event so !postback is always false each time I'm adding the webpart to page, and I'm getting an error at the else loop because the object reference is null.
if (!IsPostBack){
ViewState["postids"] = System.Guid.NewGuid().ToString();
Cache["postid"] = ViewState["postids"].ToString();
}
else{
if (ViewState["postids"].ToString() != Cache["postid"].ToString()){
IsPageRefresh = true;
}
Cache["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Cache["postid"].ToString();
}
How do I solve this problem?
using the viewstate worked a lot better for me as detailed here. Basically:
bool IsPageRefresh = false;
//this section of code checks if the page postback is due to genuine submit by user or by pressing "refresh"
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
IsPageRefresh = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
This article could be of help to you
http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET
you are adding a Guid to your view state to uniquely identify each page. This mechanism works fine when you are in the Page class itself. If you need to identify requests before you reach the page handler, you need to use a different mechanism (since view state is not yet restored).
The Page.LoadComplete event is a reasonable place to check if a Guid is associated with the page, and if not, create one.
check this
http://shawpnendu.blogspot.in/2009/12/how-to-detect-page-refresh-using-aspnet.html
This worked fine for me..
bool isPageRefreshed = false;
protected void Page_Load(object sender, EventArgs args)
{
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
isPageRefreshed = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
}
Simple Solution
Thought I'd post this simple 3 line solution in case it helps someone. On post the session and viewstate IsPageRefresh values will be equal, but they become out of sync on a page refresh. And that triggers a redirect which resets the page. You'll need to modify the redirect slightly if you want to keep query string parameters.
protected void Page_Load(object sender, EventArgs e)
{
var id = "IsPageRefresh";
if (IsPostBack && (Guid)ViewState[id] != (Guid)Session[id]) Response.Redirect(HttpContext.Current.Request.Url.AbsolutePath);
Session[id] = ViewState[id] = Guid.NewGuid();
// do something
}
If you want to detect a refresh on an HTTP GET rather than only POSTs, here's a hacky work-around that, in modern browsers, mostly works.
Javascript:
window.onload = function () {
// regex for finding "loaded" query string parameter
var qsRegex = /^(\?|.+&)loaded=\d/ig;
if (!qsRegex.test(location.search)) {
var loc = window.location.href + (window.location.search.length ? '&' : '?') + 'loaded=1';
window.history.replaceState(null, document.title, loc);
}
};
C#:
public bool IsPageRefresh
{
get
{
return !string.IsNullOrEmpty(Request.QueryString["loaded"]);
}
}
When the page loads, it will change add a QueryString parameter of loaded=1 without reloading the page (again, this--window.history.replaceState--only works in post-archaic browsers). Then, when the user refreshes the page, the server can check for the presence of the loaded parameter of the query string.
Caveat: mostly works
The case where this doesn't work is when the user clicks the Address Bar and presses enter. That is, the server will produce a false-positive, detecting a refresh, when odds are, the user actually meant to reload the page fresh.
Depending on your purposes, maybe this is desirable, but as a user, it would drive me crazy if I expected it to reset the page.
I haven't put too much thought into it, but it might be possible to write some magic in order to distinguish a refresh from a reset via the address bar using any/all of:
SessionState (assuming SessionState is enabled) and the value of the loaded QueryString parameter
the window.onbeforeunload event listener
keyboard events (detecting F5 and Ctrl + R to quickly change the URL back to removing the loaded QueryString parameter--though this would have a false-negative for clicking the browser's refresh button)
cookies
If someone does come up with a solution, I'd love to hear it.
Another way to check page refresh. I have written custom code without java script or any client side.
Not sure, it's the best way but I feel good work around.
protected void Page_Load(object sender, EventArgs e)
{
if ((Boolean)Session["CheckRefresh"] is true)
{
Session["CheckRefresh"] = null;
Response.Write("Page was refreshed");
}
else
{ }
}
protected void Page_PreInit(object sender, EventArgs e)
{
Session["CheckRefresh"] = Session["CheckRefresh"] is null ? false : true;
}

Asp.net c# 301 redirect when page has expired

I have an expiry date in my database and I would like to redirect a web page when the expiry date for that page has been reached.
How would I do this?
Thanks
You can do that using a cache for your pages. I'm obviously not familiar how you store the expire dates, but I'll presume you have [exp_date: url].
So:
protected void Application_Start(object sender, EventArgs e)
{
Dictionary<Datetime, string> pages = Read_from_database();
Context.Cache.Insert("ExpireCache", pages, new CacheDependency(m_strPath),
System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration,
CacheItemPriority.Default);
}
And in
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.Url.AbsolutePath == "page_expired.aspx")
{
return;
}
var cache = HttpContext.Current.Cache["ExpireCache"];
if (cache.ContainsKey(HttpContext.Current.Request.RawUrl) &&
cache[HttpContext.Current.Request.Url.AbsolutePath] < DateTime.Now)
{
HttpContext.Response.Current.Redirect("page_expired.aspx");
}
}
You can additionally add a SqlDbDependency to the Cache, so that it get updated when you modify the expire dates in the Database...
You could put a Trigger on you database.
That fires off after a certain time or action and then test the date to make sure it's not expired.
If it is a simple code block like this could do the job.
if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(
"http://mySite.com"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location",
Request.Url.ToString().ToLower().Replace(
"http://mySite.com",
"http://www.myNewSite.com"));
}
Hope it helps
You can use this code to permanently redirect. #phadaphunk solution redirect Uppercase letters to small letters.
string authority = Request.Url.Authority;
if (authority.IndexOf("www.") != 0)
{
Response.StatusCode = 301;
Response.RedirectPermanent("http://www." + authority + Request.Url.AbsolutePath, true);
}
Note that Response.RediectPermanent method is only available for .Net 4.0 I think, otherwise you should use Redirect()

Categories