How to detect if Refresh button(F5) is pressed - c#

I have the below code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//do something
}
else
{
// do something else
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//do something
}
}
The point is that a post back happens if I press F5/refresh button or a button click. How will I prevent the code from doing any action if F5/refresh button is clicked?
I have checked Detect F5 being pressed and Refresh but the solution of mine will be different as I need to do this in C# code.
Thanks

You are trying to capture something on the client - so it must be client side script (as discussed in the link).
It's not a postback in ASP.Net terms - your page is simply being requested again (GET). You cannot stop this - its just like going to some other page on your web site and clicking back through some navigation.
If you are saying you want to prevent some type of server side code you have from being run (more than x times) then you can think about sessions or cookies and read them in before you run whatever process. A simplistic sample:
visit page 1 - set session or cookie that identifies page 1 process was run
visit page 2 - set session or cookie that identifies page 2 process was run
return to page 1 - check for existence of session or cookie variable, and if exists, don't run page 1 process.
Another option, if viable is to use ASP.Net caching.

Related

How to go to previous page in windows phone 8 when back button is pressed

I have a home page or landing page in my windows phone c# based app where user enters login details and upon successful login user is redirected to page2 . Here the user will see a list box with few items . Upon selecting an item from this list box a new page called "Threadx" opens.(where x is the each page that opens upon clicking the x item in the list box)
While user is on this Thread page "Threadx" he may receive the toast notifications and the thread gets updated with new replies or answers on that thread.
But When user clicks on back button the "ThreadX" page doesn't get closed and instead it goes to its previous state where it has less number of messages , and so on until the app gets closed.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.NavigationMode == NavigationMode.Back)
{
return;
}
}
I would like to know if this "Threadx" page can be closed upon clicking back button without affecting other "Threadx+1","Threadx+2"..."Threadx+n" pages.
Any help would be really appreciated.
Normally windows keeps the pages on it's stack when you leave a page and navigate to another page. If you want to navigate to the previous page on pressing the Back Button you can do following things:
Add following line to OnNavigatedTo method:
Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
Add definition for HardwareButtons_BackPressed method:
private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
e.Handled = true;
if (Frame.CanGoBack)
Frame.GoBack();
}
Don't forget to add Windows.Phone.UI.Input to the namespace list.
The other way I got it worked was using the below code in the onnavigateto method in my "thread" page and it worked for me. Let me know if there is an elegant way of doing it or better way of doing it .
if (e.NavigationMode == NavigationMode.Back)
{
NavigationService.Navigate(new Uri("/View/Page2.xaml", UriKind.Relative));
}

Button onClick event nothing is happening

I have a problem where my button click will not work whatsoever. I think all the code is right but why is nothing happening when it's clicked? Is the code right for displaying the message and is the code right for redirecting to a website/webpage? Any help much appreciated!
public delegate void myDelegate();
public event myDelegate FindInfo;
protected void btnOne_Click(object sender, EventArgs e)
{
FindInfo += new myDelegate(showFindInfoMessage);
FindInfo += new myDelegate(showWebsite);
FindInfo();
}
public void showFindInfoMessage()
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptkey", "<script>alert('You will now be redirected to the website!');</script>");
}
public void showWebsite()
{
string web = "https://facebook.com/";
Response.Redirect(web);
}
HTML
<asp:Button ID="btnOne" runat="server" Text="Find Info" OnClick="btnOne_Click" />
Your code looks a little strange, but it should work as you expect. I don't see anything that could immediatelly stop it from working.
Easiest things first - are there any exceptions thrown? Run the site from within VisualStudio in Debug mode, click the button on the site, and check out the "Output" window. If you see any "First Chance Exception" lines showing up after you clicked it, then try to chase and solve them, or write them down and show them to us. Make sure that those were really recorded only after you clicked the button. There might be some exceptions recorded when the site starts up. After starting up the site, be sure that the Output window stops chattering before you click the button.
Next, does any other buttons you create work as expected at all? On this page? How's that on other pages? Have you tried placing a breakpoint to see if this code runs at all? Place a breakpoint on the first line of btnOne_Click method (click there and press F9, assuming you have typical hotkeys), and also try placing some other breakpoints in other methods, like Page's constructor. Then try running your site in "debug" mode and click on the button. Check which breakpoints get triggered.
In case NO breakpoint gets hit at all, then either your VisualStudio and webserver are not configured for debugging (oops), or the page might not be compiled at all (for example, you may be running an old copy of it).
If some breakpoints are triggered but that one button handler is not, then try observing what your page does or tries to do when you click that button. If you are using any modern browser, it should have a "developer tools" panel somewhere. For example, in Chrome, press F12. In those dev-tools, find some tab or window that will show you the "Network operations". Display or refresh your page, check if some netwrok operations are captured. You should notice at least the page itself being downloaded with "200" status code. After observing that, when everything gets silent, "Clear" the log (there should be a button for that somewhere) so you get a fresh&clean view again, and press the button. Observe what happens.
If the button works on client-side, you will see a request being sent to the server. Observe the response code. Is it 200? 404? 500? All of those will mean different things. Report back with the code. Also, if there are any error (status code != 200) try to read/copy all of the details you can.
If the button and the server work ok or almost ok, then after clicking the button you would see a request sent back to the same page, followed by a status=200. However if IIS and ASPX are OK, this would run the xxx_Click handler. So probably you won't see this scenario.
If the button doesn't work at all and no requests are sent, then there's some problem with the HTML code that was rendered. Go back to the dev-tools in the browser, find a tab/window that allows you to see the raw HTML code of the site, and find that button. Check what click actions are set on it. If you don't see any, check which FORM tag is the parent of that button and check if its "method" and "action" attributes are set properly. If the method/action are generated wrong, the browser may try to send the 'click' to a wrong place, or even it may not try sending it at all.
If all of that does not show anything useful, then try ... temporarily replacing your code with something that should work in any case. Check out the example at MSDN site. Backup your page code somewhere and replace it with the example from this site. Paste all of that as the ASPX file, and remove everything from the code behind (ASPX.CS file), and run your site. This example shows a simple button and attaches one handler to that button. Check if it works. It should. Also you may observe all of the things I wrote above again. If the example does not work, then, again, I'd guess your IIS or ASP installation(s) are broken.
Your code works correctly. I put it in a test project and it redirects. If you are asking why you do not see the alert, that is because the page would need to post back to register the script, however you redirect to facebook.com before it has a chance to do so. You can register the script on page load, then call the JavaScript function to display the alert.
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
showFindInfoMessage();
}
public delegate void myDelegate();
public event myDelegate FindInfo;
protected void btnOne_Click(object sender, EventArgs e)
{
FindInfo += new myDelegate(showFindInfoMessage);
FindInfo += new myDelegate(showWebsite);
FindInfo();
}
public void showFindInfoMessage()
{
Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "scriptkey", "alert('You will now be redirected to the website!')");
}
public void showWebsite()
{
string web = "https://facebook.com/";
Response.Redirect(web);
}
}

ASP.NET Redirect and End Page

So I read up a lot about how to properly use Response.Redirect without causing some errors.
Response.Redirect(url, false);
Context.ApplicationInstance.CompleteRequest();
Situation: A user logs in the site and visits a page that lists forms. The user sits on that page for an hour doing nothing (which would log them out). The user clicks a button to edit a title (which requires a postback). This results in the user object being null since it logged him out of the session.
What I have done: In the page load, check if the user object is null and if it is, redirect to the login page. That is what should happen right?
Problem: The button event is STILL firing. Is it because I have the following line of code?
Context.ApplicationInstance.CompleteRequest();
How can I stop the event from being firing when I simply want to redirect to the login page?
I know I can provide true in the redirect code, but that will cause an error too right?
Response.Redirect(url, true);
What I currently do (which is not the best way I know): In the button event, I again check to see if the user object is null. If it is not null, proceed with the code to edit the title (recording who edited it). This is a bad way of handling this.
What I have seen: Wrap all events with Response.IsRequestBeingRedirected. But if I have several pages and lots of button events, this can get a bit annoying. Is this the only way to handle this situation?
Example:
protected void Page_Load(object sender, EventArgs e)
{
Account account = Session["Account"] as Account;
if (account == null)
{
Response.Redirect("WebForm1.aspx?NewSession=true", false);
Context.ApplicationInstance.CompleteRequest();
return;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Account account = Session["Account"] as Account;
Label1.Text = account.userID.ToString();
}
Again, if I am already on the page, and the session expired, and I click Button1, the Button1_Click method is still being called. What I provided will give me a "NullReferenceException". Page_Load IS being called, and it is making the redirect. However, Button1_Click is still being called even with the return statement in Page_Load.
Thanks!
You are correct about Response.Redirect(url, true). It is kind of expensive because it throws ThreadAbortException causing the current thread to terminate which is not what you want most of the times.
There is even a KB exists on this topic KB312629.
And yes, with your code it is not possible to prevent events from firing for the current IHttpHandler (which Page class implements) using built-in classes/methods.
So I would suggest to create base page class and add a bool field indicating about request completion request plus method that will call ApplicationInstance.CompleteRequest and will set the flag to true. Also you'll need to override RaisePostBackevent method to take control over controls (not Page) events invocation on page.
public abstract class BasePage : Page
{
private bool shouldNotRaiseEvents;
protected void CompleteRequest()
{
shouldNotRaiseEvents = true;
Context.ApplicationInstance.CompleteRequest();
}
protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)
{
if (shouldNotRaiseEvents)
{
return;
}
base.RaisePostBackEvent(sourceControl, eventArgument);
}
}
Your updated code would be:
Response.Redirect(url, false);
CompleteRequest();
Also please note that if you have something inside LoadComplete, PreRender, SaveViewState, Render, Unload event handlers and you don't want this code to execute after redirect call you'll need to override that methods also.

Clear bt-click method function when the page is updated

Here is my button:
protected void Button_Click(object sender, EventArgs e)
{
...//things it does
}
When I update the page, google chrome (for ex) asks me if I want to redo the action above. Lay people will press continue and the action is gonna happen, but it cant happen. How can I clear this action from "memory" for it don't happens again?
thanks a lot!
After you have done your processing in the button click event you can then do a Response.Redirect back to the same page.
When you click F5 browser resend to server last request. If the last request was a POST it will show a pop up asking user if he wants to resend the information. That's a standard behavior for every browser and you can't change it.
An existing pattern to avoid this problem is /Post/Redirect/Get

set session timeout after inactivity

I want to redirect back to the home page when there is no activity.
However, i dont have a user login or the need to have one. However, i want to be able to redirect back to the home page when theres no activity.
I set this in the web.conf
<system.web>
<sessionState mode="InProc" timeout="2">
then, i set this in the homepage
Session["UserId"] = 1;
I also tried this but the function doesnt even fire.
protected void Page_Init(object sender, EventArgs e)
{
CheckSession();
}
private void CheckSession()
{
if (Session["UserId"] == null)
{
Response.Redirect("KioskHome.aspx");
}
}
Could i use the global.asax file?
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
}
What is the simple solution? Thank you
If I understand your question, you want to redirect the user's browser if the user hasn't performed any action in some period of time.
In that case - server-side behaviour won't help you. The connection has already closed. The global.asax Session_end will fire when the session is ending, and there won't be a client connected at that time.
Perhaps you should read more about the ASP.NET Page Lifecycle.
What you may want, however, is some form of client-side behavior such as Javascript, which after a specific timeout, can redirect the user.
Note that there's a number of issues with this, including that a user may use multiple tabs, so knowing accurately when the session has timed out is difficult.

Categories