Clear bt-click method function when the page is updated - c#

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

Related

Click button after webBrowser1_DocumentCompleted event

I have a C# 4.0 WinForms application, which has a WebBrowser control and 2-buttons.
Clicking the first button sends a URL to the browser to navigate to a specified webSite.
Clicking the second button parses the OuterHtml of the webBrowser1.Document, looking for an "https://..." link for File Download.
The code then uses a webClient.DownloadFileAsync to pull down a file for further use in the application.
The above code successfully works, if I manually click those buttons.
In an effort to automate this for the end-user, I place the first button's click event, i.e. btnDisplayWeb.PerformClick(); in the form's Form1_Load event. This also works, allowing the webBrowser1 to populate its Document with the desired webSite.
However, I am unable to programatically click the 2nd button to acquire the web link for file download.
I have tried to place the 2nd buttons click event within the browser's DocumentCompleted event, as shown below.
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
btnMyUrl.PerformClick();
}
However, from what I've read on StackOverFlow and other sites, it's possible that this particular event gets called more than once, and hence it fails.
I've also attempted to loop for a number of seconds, or even use a Thread.Sleep(xxxx), but the browser window fails to populate until the sleep or timer stops.
I attempted to use the suggestions found on the following StackOverFlow site shown below.
How to use WebBrowser control DocumentCompleted event in C#?
private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string url = e.Url.ToString();
if (!(url.StartsWith("http://") || url.StartsWith("https://")))
{
// in AJAX
}
if (e.Url.AbsolutePath != this.webBrowser.Url.AbsolutePath)
{
// IFRAME
}
else
{
// REAL DOCUMENT COMPLETE
}
}
However, in parsing the OuterHtml, nothing is returned in the first two sections, and in the third section, other elements are returned instead of the desired "https://..." link for File Download.
Interestingly, if I use a webBrowser1.ReadyState event, as shown below, and place a MessageBox inside DocumentCompleted, this seems to allow the browser document to complete, because after clicking the OK button, the parsing is successful.
if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
MessageBox.Show("waiting", "CHECKING");
btnMyUrl.PerformClick();
}
However, I then have the difficulty of finding a way to click the OK button of the MessageBox.
Is there another event that occurs after the DocumentCompleted event.
OR, can someone suggest how to programmatically close the MessageBox?
If this can be done in code, then I can perform the buttonClick() of the 2nd button in that section of code.
After finding that the addition of a MessageBox allows the webBrowser1.Document to complete, and using webBrowser1.ReadyState event within the webBrowser_DocumentCompleted event, all I needed to do, was to find a way to programmatically close the MessageBox.
Further searching on StackOverFlow revealed the following solution on the site below.
Close a MessageBox after several seconds
Implementing the AutoClosingMessageBox, and setting a time interval, closed the MessageBox and allowed my button click, i.e. btnMyUrl.PerformClick(); to successfully parse the OuterHtml and now the code works properly.
Hopefully, if someone else discovers that placing a MessageBox within the webBrowser_DocumentCompleted event allows the document to complete; the aforementioned AutoClosingMessageBox will assist them as well.

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);
}
}

How to handle a Web Browser back and forward navigation in a Wp7 app

I am using a web-browser in my windows phone 7 application.
I just want to know that how to handle its back and forward navigation just like any desktop browser.
And also how to block a particular navigation.
I referred here and many others but couldn't find anything working for me.
Please help.
You can cancel navigation by handling the OnNavigating event
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
//cancel navigation
e.Cancel = true;
}
To go back, you can execute javascript on the page.
webBrowser.InvokeScript("eval","history.go(-1)");
and move forward:
webBrowser.InvokeScript("eval","history.go(1)");
If eval is blocked on the page, this site might be useful for alternatives. Don't forget to set webBrowser.IsScriptEnabled to true.
To make it work like a desktop browser you can implement a stack.
You will put two buttons back and forward. As the user navigate to next URL in browser you push them into history stack and when he wants to get back by pressing back button you navigate to the first url in the history stack programmatically and pop it up from the history stack so he can navigate back till stack has some URLs in it. Similarly for forward you push URLs into forward stack as he navigates back and and whenever he presses forward button you navigate to first element in forward stack and pop it up and so on till you have urls left in forward stack. Once he navigates to some url which is not navigated from forward stack by you then you empty the forward stack and fill it again when he moves back.
This way you can even show history urls in a list or however you like.
About navigation cancel, here is the code from the link to question in the comments under your question, it should work.
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
//cancel navigation
e.Cancel = true;
}
Previous answer will work, but you can make a workable solution even simpler, since the WebBrowser control has an internal navigation stack.
Add forward and back button controls to your UI. In the action routine for each of them:
private void forwardButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
WebBrowser editWB = sender as WebBrowser;
if (editWB != null && editWB.CanGoForward)
editWB.GoForward();
}
You can get fancier: in the WebBrowser.LoadComplete event (not the FrameworkElement.Loaded event), you could test .CanGoForward and .CanGoBack and selectively enable or disable the buttons appropriately.
I tried to implement the idea proposed by BobHy but failed as in my WP7 / VS2010 Express I did not find the method CanGoForward for WebBrowser. I am using it inside of a canvas in user control which might impact the experience.
However, I found a straight forward detailed example at http://developer.nokia.com/community/wiki/WebBrowser_Control_Techniques_in_Windows_Phone implementing a stack as suggested by Parveen that works for me fine.

How to detect if Refresh button(F5) is pressed

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.

Alert on Back Key Press, Confirm Exit

I'm writing a windows phone app, and I want to know how to alert and make sure the that user really wants to exit the app on the back key press. Pretty simple.
Thanks.
I assume your navigation is set up such that the user can only exit from the first page. If so, in that page, you can override the OnBackKeyPress event and cancel the button press. I haven't tested this code, but seems like it should work:
protected override void OnBackKeyPress(CancelEventArgs e)
{
if(MessageBox.Show("Are you sure you want to exit?","Exit?",
MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
e.Cancel = true;
}
}
Edit - I'll leave this here as an example of overriding the back button, but the correct answer in this context is to not implement the feature.
While the previous answer about cancelling OnBackKeyPress may technically work, it could cause your app to fail certification requirements. See the following link:
http://msdn.microsoft.com/en-us/library/hh184840(v=VS.92).aspx
5.2.4.2 – Back Button: First Screen
Pressing the Back button from the first screen of an application must close the application.
I would recommend not implementing this functionality.

Categories