Detect browser refresh - asp.net

How can I find out if the user pressed F5 to refresh my page (Something like how SO implemented. If you refresh your page, the question counter is not increased). I have tested many code snippets mentioned in a dozen of tutorials, but none worked correctly.
To be more clear, suppose that i have an empty web form and would like to detect whether the user has pressed F5 in client-side (causing a refresh not submit) or not.
I can use session variables, but if the user navigates to another page of my site, and then comes back , I'd like to consider it as a new visit, not a refresh. so this is not a session-scope variable.
Thanks.
Update: The only workaround I could find was to inherit my pages from a base page, override the load method like below:
public class PageBase : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Session["LastViewedPage"] = Request.RawUrl;
}
}
and in every page if I was interested to know if this is a refresh:
if (this.Session["LastViewedPage"].ToString() == Request.RawUrl)
{
// This is a refresh!
}

I run into this problem and use the following code. It works well 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();
}
}

The only sure solution is to make a redirect to the same page , and here is a similar question: Post-Redirect-Get with ASP.NET
But there are also some other tricks, by adding some ticket on the page and see if this is the same or have change, see the full example and code at:
http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET
and one more:
http://dotnetslackers.com/community/blogs/simoneb/archive/2007/01/06/Using-an-HttpModule-to-detect-page-refresh.aspx

Related

ASPX page loading data from last session

I'm creating a C# application with a ASP.net frontend, however I'm having a problem at the moment. I want to the user to enter some information, which once submitted, will be displayed within a listbox on the page which works fine. However, once I close the page, stop debugging the program and run it again - the information is still displayed but I want it to start off blank. Here if the ASPX page that I think if causing the issue, it's driving me mad.
public partial class CarBootSaleForm : System.Web.UI.Page, ISaleManagerUI
{
private SaleList saleList;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack && Application["SaleList"] != null)
{
LoadData();
}
else
{
saleList = (SaleList)Application["SaleList"];
}
if (saleList != null)
{
UpdateListbox();
}
}
private void UpdateListbox()
{
lstSales.Items.Clear();
if (saleList != null)
{
for (int i = 0; i < saleList.Count(); i++)
{
lstSales.Items.Add(new ListItem(saleList.getSale(i).ToString()));
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Application.Lock();
Application["SaleList"] = saleList;
Application.UnLock();
Response.Redirect("AddSaleForm.aspx");
}
}
Forget the LoadData() within the page load as it's not actually loading anything at the moment :)
Any help is really appreciated!
The variables stored in Application state are not flushed unless you restart the web server, so you will need to use the iisreset commmand (on command-line) if you are using IIS, or you will need to stop the ASP.NET web server (use the tray icons) after each debugging session.
if it is not postback you can add
Session.Abandon(); in the else block in Page_load.
Kill Session:
How to Kill A Session or Session ID (ASP.NET/C#)

Logout button doesn't work properly in ASP.NET

My logout button's code looks like this:
protected void ButtonLogout_Click(object sender, EventArgs e)
{
Session["login"] = null;
}
And my page's onLoad event looks like this:
protected void Page_Load(object sender, EventArgs e)
{
if ((string)Session["login"] != null)
{
ButtonLogout.Visible = true;
// (...)
}
else
{
ButtonLogout.Visible = false;
// (...)
}
}
I'm having problem with this thing working properly. I didn't know what's going on so I've setted up break points in both ButtonClick and PageLoad events. What I found out is that PageLoad event executes first (sic!) and that's why ButtonLogout wasnt hiding after clicking it. I could simply refresh page in ButtonClick event but I'm not sure whether Loading Page twice after 1 button click is OK. Isnt there any other way to solve this?
Thanks.
The issue is that the page life cycle executes in a specific way. In basic terms it goes:
Page_Load
Events fire
Pre_Render
More details can be found - http://msdn.microsoft.com/en-us/library/ms178472.ASPx
If you're setting the visibility of a control you can set this in the Pre_Render page event and at that point the button event will have fired and set what you require.
I recommend you to use asp.net LoginStatus to handle that. And dont forget to clear the session when the user logs out. Checking Using LoginName and LoginStatus Controls will help you.
protected void HeadLoginStatus_LoggingOut(object sender, LoginCancelEventArgs e)
{
Session.Clear();//It clears the session when the user logged out.
Session.Abandon();
FormsAuthentication.SignOut();
}

How to make sure the user just logged in?

I have a web control panel with links to sensitive informations (like credit card number).
When the user clicks (who got logged in before) on one of these link, I need to check his credntials.
How can I make sure on the server side when he requests ("/sensitive-informations.aspx") that he just entered his credentials ?
EDIT : the main problem here is the "he just entered his credentials" , I need to make sure that he comes DIRECTLY from the login page.
There are a few ways to do this. For instance, after the user enters his credentials, save them in the Session object.
Then, in the Page_Load of sensitive-informations.aspx make sure the Session object exists.
To better illustrate this:
In your login.aspx.cs page:
protected btnLoginClick(...)
{
// CHECK USERNAME and PASSWORD
if (UserIsAuthenticated)
{
Session["UserName"] = user;
}
}
Then in your sensitive-informations.aspx.cs
protected page_load(...)
{
// If UserName doesn't exist in Session, don't allow access to page
if (Session["UserName"] == null)
{
Response.Redirect("INVALID_USER.aspx");
}
}
Edit:
Based on OPs comments, if you want to know which page you came from, you can either use:
Page.PreviousPage like this:
protected void Page_Load(object sender, EventArgs e)
{
var x = this.Page.PreviousPage;
Or use Request.UrlReferrer like this:
protected void Page_Load(object sender, EventArgs e)
{
var x = Request.UrlReferrer;
In both cases make sure x isn't null first...
You can check the UrlReferrer in the Page_Load event of sensitive-informations.aspx:
if (Request.UrlReferrer != null)
{
if (Request.UrlReferrer.AbsolutePath.ToLower().Contains("you-login-page"))
{
//User came from the login page
}
}
UPDATE
Based on your comment, you should check the LastLoginDate property of the MembershipUser class
This will give you the, well, last login date of the current user. You can compare that with the current date/time to make sure that the user "just entered their credentials". Couple this with the checking where the user came from (either with Request.UrlReferrer or Page.PreviousPage).

login validation on asp page

Since I'm a newbie for asp, I'm trying to take a name as input,trying to put that name in list, then check the list to find a match. I'm doing this as basics keeping the log in procedure in mind, which I will try to implement later. I have the following code:
I have made a class like this:
public class Login
{
public string name { get; set; }
}
The two button events are as follows:
List<Login> list;
protected void Button1_Click(object sender, EventArgs e)
{
list = new List<Login>(){
new Login { name = TextBox1.Text },
new Login { name = "Badhon"}
};
Label1.Text = "Inserted";
}
protected void btnLogIn_Click(object sender, EventArgs e)
{
foreach (var s in list)
{
if (s.name == TextBox1.Text)
{
Label1.Text = "Found";
break;
}
else
Label1.Text = "Not Found";
}
}
when I'm trying to insert,its working fine, but when clicking on the login button showing any error message like "Object reference not set to an instance of an object."
When you press the login button you're in a different scope to when you pressed the first button, so the list is not initialised (Each time you press an ASP button you get a new state: The web is designed to be stateless).
Why not use the asp:login control?
You code is not exactly what it is supposed to be. You'd better go searching for some (of the various) examples on how to hanle logins in ASP.NET.
Each click is a new HTTP request. The list initialized in the first request is not the same with the list in the other request because each request will use its own instance of the Page object.
You need to read & understand the life cycle of a ASP.net page: http://msdn.microsoft.com/en-us/library/ms178472.aspx
make protected properties to store list of logins
It should looks like this:
protected List<Login> LoginStore
{
get{ return ViewState["store"] =! null ? (List<Login>)ViewState["store"] : new List<Login>; }
set{ ViewState["store"]=value; }
}
You can use Session as well as ViewState. It will make your list doesn't disapear every time you make PostBack.
then in event btnLogIn
create List<Login> list = LoginStore;
then make the rest of your code.
click on here
why do go forloop, use session variables in Global.asax, try googlin you can find many example..

asp.net set sessions before postback

is there an easy way, to store all needed global variables in sessions at once, before the PostBack starts? Or have I to store them in each step where I change them?
I will do something like:
// Global variable.
bool test = true;
// Store all needed information in a session.
protected void Before_globalvariable_is_set_to_default_value(...)
{
Session["Test"] = test;
...
}
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
//if(Session["Test"] != null)
//{
test = (bool)Session["Test"];
Session.Contents.Remove("Test");
//}
}
}
Is something like that possible?
Additional Information
At the Page_Load (!IsPostBack) I check if the user gets more vision, if he gets, I set a global var to true. Later in my code I check if that var is true and add additional columns to a GridView.
Now if a PostBack occurs, I can’t check that var, because I lose the information. I knew that I need to store the information in a Session. If I set the Session at the time where I set the global var to true, I get problems with the session timeout (If the user is on the site, but doesn’t do something for a while). So I thought it will be good, if I set the Session shortly before I lose the information of the global var and delete the Session after reinitialization.
That’s my idea, but I don’t know if something like that is possible.
Edit2:
If I do following it works:
//Global variable
bool test = false;
protected void Page_PreRender(object sender, EventArgs e)
{
Session["Test"] = test;
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
test = (bool)Session["Test"]; // Session is true!!!
Session.Contents.Remove("Test");
}
else
{
test = true; // Set at the PageLoad the var to true.
}
}
I’m a little bit confused, I thought PreRender is after the PageLoad, why suddenly the test var is true and if I remove the PreRender it isn’t?
Greetz
If you're worried about losing a specific value between requests, because you've maintained the state of that variable in the Session object and it might have been cleared by a timeout, you could consider using another, more durable, mechanism to save the state: for example, cookies or database.
If the value only needs to live during that one Request, you can use class-level fields of the code-behind class. Set them in the Init or Load phase, then you can use those values in all other phases.
For a lifetime of just a single request:
public partial class MyPage: Page
{
private bool test = true;
public void Page_Load(...)
{
// maybe set 'test' to another value
}
public void Button_Click(...)
{
// you can still access 'test'
}
public void Page_PreRender(...)
{
// you can still access 'test'
}
}
If however you need that value to live from request to the next postback, you can use ViewState instead of Session. Advantage: no timeout as it is stored in the html and posted back from the browser along with other data. Disadvantage: it only works in postback-scanario's, not when you link to a different page.

Resources