How to Track F5/Refresh in ASP.Net - asp.net-2.0

I am using VS 2005, C# 2, ASP.Net 2.0
I am unable to find out how to track that user pressed F5/Ctrl+F5/ Open a new Window(Ctrl + N) in ASP.Net.
I know that there is a Page.IsPostBack property, which tells that a page is loaded in response to an action taken by user.
I am just curious to know, that why isn't there a property as IsRefresh or Page.IsRefresh in ASP.Net, which will return true,
whenever user takes any of the above actions.
Is there a way to know this?
Actually my problem is that i have a DLL using which all of my aspx pages are inherited, I have to
insert some values in a table whenever the page is opened for the first time that's it, if user just opens the page or do not take any action,
an entry should be inserted into the database, but as far as I have tried, I controlled it anyhow using the Page.IsPostBack property, but I got stuck
in the refresh case, as it is inserting records unconditionally.

Similar to using a function in Global.asax (as others have suggested) you could use a session variable "flag". When the page first loads set a session variable and then just check against it in your page load function:
if (Session("visited") != "true"
//page has not been visited, log visit to DB
Just make sure you set the session flag sometime after the above check during the page load.
It won't be exact (sessions can timeout while a page is active, users can completely leave the site and come back in the same browser and the session stays alive, etc) but for your tracking it is much better than counting every page hit in the DB.

Perhaps you want the Session_Start method in the Global.asax file, which will be triggered once at the start of each user session?
In your Global.asax file, add or edit the method:
void Session_Start(object sender, EventArgs e)
{
}

why isn't there a property as IsRefresh or Page.IsRefresh in ASP.Net
Because ASP.NET cannot possibly know. The browser does not send any information that could allow it to determine whether the page is being requested due to a refresh or normal load. You will need to reconsider your requirements: what is the actual purpose of the database logging?

Session_Start method in Global.asax file is fired every time when a browser session is started. You can use this method to count number of unique users on your website.
Session_End method in Global.asax is fired when a session ends (explicitly or timedout). So you can decrement the count here.
Hope the above to example uses of these methods helps you understand how you can use them.

Because of the stateless nature of HTTP protocol there is no way to tell apart the initial load from the refresh

As has already been said. This isn't possible. A request issued due to a refresh is no different to a request issued the first time the page is loaded.
It sounds to me like you are trying to track page views somehow. This is certainly possible though it will require some work on your part. Your best bet is probably to log the URL of the page. You may also want to include the query string in order to differentiate between page loads for different pieces of data (if this happens in your application). You will also want to log the ID of the current user, and the ID of their session.
You can then make sure that you don't insert two page views for the same user for the same page in the same session, effectively filtering out any reloads of a page.
You do need to be aware that this isn't the same as detecting a refresh, what you are detecting is two page views in the same session, this could be a refresh, or it could be use of the back button, or just reloading from the address bar.

My suggestion would be to create a cookie on very first load, then on Page_Load check to see if the cookie exists. If it does, don't insert the record. You can use Session_End to destroy or create the cookie as someone suggested if that works with your application's architecture.

Related

Asp.net output cache substitution with postback in user control

We have a site where all pages are output cached, i.e. the caching is on aspx-level with VaryByParam="*". Now there is a requirement to make a gallup control, i.e. a small "How is this site working for you?" and then when the user clicks an answer the results are shown.
The gallup is implemented as a usercontrol that is added to the master page so gallups can be added to any page to which a gallup is created in the cms. The problem is that output cache naturally caches all clicks so when user no 2 votes he sees the results that where calculated after the first vote on that alternative.
Now I'm trying to use cache substition. I added an asp:Substition tag where the user control used to be, load the control dynamically and render it (using this approach http://coderwall.com/p/4ajzqq). The problem is that the postbacks that voting triggers is never fired. Apparently the method that the substition control executes is loaded outside the page life cycle or too late.
Any ideas?
Regards,
Mathias
I solved this by skipping the substitution control and just used the user control as normal, so the gallup/question view was output cached. Then in the click handler for the answer alternatives I added
Response.Cache.SetNoServerCaching();
which exempted the results view from output cache and hence it was updated as it should.
It is also possible to use Response.Cache.SetNoServerCaching() in Global.asax, using VaryByCustom. It merely requires sensing in Global.asax whether the page is a post-back or not. Here is a code example.

Page hangs when leaving it for a while using ASP.NET Ajax

I'm working on a business application using ASP.NET Ajax , NHibernate and Spring.Net, I've got an annoying problem. The problem is that when I leave page for about 5 minutes and then return back and try to make any action that posts back, it displays wrongly (if there are controls hidden by style it became visible). In addition, the page didn't post back to the server.
Also the problem happens when opening two different tabs, different pages (Each page uses session but different keys )
Thanks in advance
As you describe the problem, its sounds that connect the content of the page with the user cookie and session, and when the session expired the application did not take care to recreate it.
So the post back fail because the session data have been lost when the page ask for them / need them to work and display correct the results.
This is the issue that I diagnose, how you fix that is up to you :)
Possible solutions
Change the logic of the page creation.
While the user is on page do not let the session ends (not good practice)
Store the user data of the page, on a database - connected with the user, and delete it after some days if not have been updated.

ASP.NET Page Life Cycle Issues

Apparently I am not familiar with the Life Cycle of a page in ASP.NET. This became apparent when I wanted to dispose of a Session variable after I left the page. I did what made the most sense:
protected void Page_Unload(object sender, EventArgs e)
{
Session.Remove("ServiceSearch");
}
What I didn't know is that this would be called when I go from AND to the page. What I am wanting to do is dispose of that Session variable whenever the user leaves the page. How do I do this?
Page_Unload refers to unloading the Page object right before it is disposed after parsing and creating the page. It has nothing to do with leaving the page. Like #Nick says, there is really no good way to tell that, except to control every exit path. And you can't, because you can't control when the user hits back, or goes to google.com and then pastes in the url they were just at into the browser, etc.
If you want to remove the Session variable just so it doesn't get re-used unintentionally, a better solution is to overwrite the Session variable every time you enter the page, and just let it be disposed with the session on its own time when the session expires.
Session data is useful for storing data beyond the lifetime of a page. If you don't want to store it beyond the life of a page then Session data is not for you here.
If the user leaves the page via a link you could possibly create a link button that is hooked up to a method on the same page. That method would remove the session and do the redirect.
I would hope there is a better solution though. Although, from my understand, there is no page event to use in your case because the page would have to reload to execute the remove session code. When the user leaves via some link the page is not reloaded.
You may possibly be able to handle it via javascript. I've been in situations where I wanted to leave and I got a popup box about some bs. You could probably use the same technique to fire AJAX to remove the session.
I faced a similar situation on php login- a logged-in user could use the arrow back and forth to login page. So, I simply add :
session_start();
session_unset();
session_destroy();
above the html script of the login page so that if the logged-in user arrowed back, the session is both unset and destroyed. Any attempt to arrow forward will only lead to the login page-requesting user login credentials-essentially, the user is logged out any time they arrow back!
Hope this helps!
Alfred

How to stop unwanted postback

I work on ASP.NET C#. Under button click event I want to save something it's work fine, but after press the refresh button of browser, this event occurs again I want to stop this event.
An article on this subject.
Preventing Duplicate Record Insertion on Page Refresh
Approach 1
A simple solution is to
Response.Redirect back to the same
page after the INSERT command is
called. This will call up the page
without transmitting any post headers
to it. Using Request.Url.ToString()
as the first parameter of
Response.Redirect will cause both the
URL and the page's querystring to be
included in the redirect. The use of
false as the second parameter will
suppress the automatic Response.End
that may otherwise generate a
ThreadAbortedException. A
disadvantage of this approach is that
any ViewState that had been built up
will be lost.
Approach 2
A related approach would be for the form to submit to an intermediate processing page and then Response.Redirect back to the calling page, similar to the classic ASP approach to form processing. This has the same effect as simply using the Response.Redirect in the Button_Click event so it has the same disadvantages, with the added disadvantage of creating another page for the website developer to manage.
Approach 3
The next batch of solutions works by
determining whether the user has
refreshed the page in the browser
instead of pressing the form's submit
button. All of these solutions depend
on the ability of the website to use
Session variables successfully. If
the website uses cookie-based
Sessions, but the user's browser does
not permit the use of cookies, these
solutions would all fail.
Additionally, should the Session
expire these solutions would also
fail.
Approach 4
Should the user somehow manage to
circumvent the above mentioned solutions described
above, the last line of defense is at
the database. There are two methods
that can be employed to prevent a
duplicate record from being inserted
into the database. For each method,
I've moved the SQL code into a stored
procedure, since there are now more
processing steps involved and these
are easier to illustrate in a separate
stored procedure. Note however that a
stored procedure is not strictly
required in order for these methods to
work.

ViewState lost on refresh in UpdatePanel?

Rather than using the Session object or storing to the database, I am storing temporary variables that I need persisted to custom ViewState variables. For example, ViewState("MyField1") = 1
When the user hits the browser Rrefresh button, Page.IsPostback is back to False and the ViewState is gone.
My question is. If the user can blow away the Viewstate by refreshing, why would anyone use it?
I know that a Refresh reposts the last submitted page, by why is Page.IsPostback reset to False and the ViewState blown away?
Flame me if you want for creating a potential dup question, but I've read other postings here, and it ain't sinking in...
Update to original post:
I now think that it has to do with postbacks that are performed as a result of clicking on Buttons that are within an UpdatePanel. Can someone help shed some light on this?
When a client refreshes their browser, it re-submits the last full page request issued by the client (which may be a GET or a POST). It does not ever resubmit AJAX requests such as those produced by update panel event triggers ("partial page postbacks").
The fact that Page.IsPostback is false when you refresh the page means that your original request is a GET, so here's what's probably happening:
1) During the initial request, the client sends no form data to the server - hence no hidden field containing view state data (Understanding ASP.NET View State is pretty detailed, but a great read if you want to really understand what's going on). While processing this request, ASP.NET may send some view state back to the client, but the original request is just a URL.
2) When the user clicks a button within an UpdatePanel, they trigger a partial postback during which MyField is set to 1. The UpdatePanel changes the client's view state to reflect the new value.
At this point, if the user submits a POST request by normal means, such as clicking a button, the view state will contain the updated information.
If the user clicks 'Refresh' though, they re-submit the original request from step 1, with no form data and therefore no view state.
Where do you set your ViewState? And where do you re-read your ViewState value? Maybe oyu check its content before asp.net calls the LoadViewState() method.
User hitting refresh and using updatepanel will not work together very well. I quess this is why people say that WebForms provides a leaky abstraction on web programming and some are moving to mvc.
If you're not interested in migrating, I'd give you the advice that do not use updatepanel for too long or big operations, where you can assume that user might refresh the page. Use it for small things like dropdown2 items changing when selection on dropdown1 changes.
Wrapping lots of functionality in one updatepanel will cause trouble, if you just depend on viewstate.
Your question is, "Why would anybody use it."
Viewstate comes in handy for data you know is generated by a post back. Hitting refresh is not a post back, but a fresh request.
So lets say you are browsing a datagrid and you need to know certain bits of data about what they have clicked, on the click event you could store that data in the viewstate and process it during other times in the page life cycle, or subsequent post backs.
ViewState's advantage is that it is just embedded into the HTML, so it is all client side. Where as SessionState is server side, and if you store a great amount of data in the session you can cause your web or db server to work harder to handle that data.
Hope this helps.
Don't know why it works but I had a similair problem and solved it by putting this line in the form_load:
me.myProperty = me.myProperty
where
Public Property myProperty() as String
Get
If Not IsNothing(ViewState("data")) Then
Return CType(ViewState("data"), String)
Else
Return String.Empty
End If
End Get
Set(value As String)
ViewState("data") = value
End Set

Resources