Prevent Page Caching and Back Button - c#

I am trying to prevent the back button being used by expiring the pages.
I have been trying to find an article on here to help and nothing works.
I have the function below that I call as the first thing on all my pages.
I call it in the Page_Load handler, is that the right place ?
I see no errors which is good, but my application just reacts as if there is no change. The back/forward buttons work and the pages display as normal and don't expire.
UPDATE:
As an added layer of security, what I want is the page to time out so if they use the "back" button they won't get the previous page. I have F5 covered so that doesn't repeat posts, and login is covered, if as I abandon the Session when they log out. But I want to stop the back button showing the previous page and force them to use the app navigation to get around my application.
I've known this functionality to fail penetration testing so I want to cover that off before I get to that point.
J
protected void Page_Load(object sender, EventArgs e)
{
MyWebApplication.SetPageStatus(Response);
....
}
internal static void SetPageStatus(System.Web.HttpResponse oResponse)
{
oResponse.ClearHeaders();
oResponse.ExpiresAbsolute = DateTime.Now;
oResponse.Expires = 0;
oResponse.CacheControl = "no-cache";
oResponse.Buffer = true;
oResponse.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
oResponse.Cache.SetExpires(DateTime.UtcNow);
oResponse.Cache.SetNoStore();
oResponse.Cache.SetRevalidation(System.Web.HttpCacheRevalidation.AllCaches);
}

Related

Stop Action on Navigating event of WebBrowser Control

I have created a little Win Form App in C# and added the WebBrowser component to it. What i am trying to achieve is a little app that can load a local html page from a file which has "custom" protocols in it and can of course also navigate to a web address.
For example i would have entry as follows in my webpage
'Close Company</TD></TR>' which would open a task in a program.
The way i tried to achieve this was via the Navigating event as shown below
private void webBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
if ((webBrowser.StatusText.Contains("Special")))
{
//For some reason the stop doesn't do much it still tries to proceed to special:123
//diplaying can not load page..
webBrowser.Stop();
//Launch program here.
MessageBox.Show("Special Command Found");
}
}
Problem is that it still navigates and says it can't find of course the page.
I swapped Stop with GoBack which for some reason has the same issue the first time i run it and when i then select backward in the browser it works from thereon.
I also tried navigated and use of GoBack, besides having a flashing in the app from going back the event does not fire again after the first time anymore.
Has anyone any ideas how to solve this or what i am doing wrong here ?
Instead of using WebBrowser.Stop();
just set e.cancel = true;

Multiple frames of the same type Windows 8 c#

I have an application for Windows 8 with a page (Frame) for displaying a list of items and a page for downloading & displaying the items details. I am also using MVVM Light for sending notifications.
Application use goes something like this:
Open Main Page
Navigate to List Page
Frame.Navigate(typeof(MyPage));
Choose Item
//Complete logic
Frame.GoBack();
Back on Main Page, I start downloading the file in the view model, I send ONE NotificationMessage saying BeginDownloadFile and after it is downloaded ONE NotificationMessage saying EndDownloadFile.
The first time I do steps 2,3, & 4 my NotificationReceived method is hit once, the second twice and so forth.
private async void NotificationMessageReceived(NotificationMessage msg)
{
if (msg.Notification == Notifications.BeginDownloadFile)
{
FileDownloadPopup.IsOpen = true;
}
else if (msg.Notification == Notifications.EndDownloadFile)
{
FileDownloadPopup.IsOpen = false;
}
}
Additional information: I only have one FileDownloadPopup, yet each time, an additional popup is shown each time the NotificationMessageReceived method is called.
My only conclusion is that between navigating forwards and backwards in my app, there are multiple MainPages being created and never closed. This results in many NotificationsMessageReceived methods just waiting for a notification to come their way so they can show their popup.
I have two questions:
1. Does this sound like normal behaviour for a Windows 8 app?
2. How can I close all instances of the MainPage or return to the previous instance without creating a new instance?
Please let me know if I have missed something important out before marking my question down.
This sounds normal to me. The default navigation behaviour in Windows 8 is to create a new page instance each time you navigate to a new page, regardless of whether this is forward or back navigation.
Try setting the NavigatinCacheMode on MainPage to Required. See the MSDN documentation for details of how page caching works.
It sounds like you are registering eventhandlers in the page and then not removing them. Each time you navigate to the page again the handler is being added again in addition to the one you previously added. Try to add your event handler in OnNavigatedTo, and make sure you unregister it in OnNavigatedFrom.
protected override void OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
{
MyEvent.OnDownloadRequest += MyLocalDOwnloadHandler; // add the handler
}
protected override void OnNavigatedFrom(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
{
MyEvent.OnDownloadRequest -= MyLocalDOwnloadHandler; // remove the handler
}

How to do things while the page is busy with asp.net?

I have an asp.net web application that when you click a button it excecutes all my stuff but it is slow it takes 10 to 15 seconds to work and i dont want users to spam click the button while the site is busy. So my plan was to disable the button and have the label below it become buesy and say "Running" and after it was done the button would reactivate and the label would say "Done" but this dident work as planned here is my code for the button listener.
protected void SubmitButton_Click(object sender, EventArgs e)
{
SubmitButton.Enabled = false;
RunStatus.Text = "Running";
RunStatus.Visible = true;
ErrorField.Visible = false;
//i deleted all my code that actually does the stuff that takes time from here
RunStatus.Text = "Done";
SubmitButton.Enabled = true;
}
the problem is that all the visual stuff happens after the method is run so while it is running nothing changed but after it has the text feild show done. I would also be happy to have a busy cursor but that is of secondary importance.
Wrap your button in an UpdatePanel and use the UpdateProgress control to show the client that an AJAX call is taking place. See this tutorial for more information.
I'm really sorry but you have a fundamental gap in your knowledge about the ASP.NET page lifecycle. It's really very different from Windows Forms - which is what the kind of code you've posted would be applicable to.
I respectfully suggest you grab a decent book on ASP.NET and try to build up a basic understanding about ASP.NET's abstraction over HTTP/HTML.

Winform App - Webpage Interaction

Windows Form Application – Manipulating input-elements in WinForm WebBrowser
Although I am familiar with HttpWebResponse/HttpWebRequest to login to a website, I was trying it now via using the mshtml library and found some weird behavior and I would like to see if someone else might be able to help me out here..
I have an HTML login page with a java backend with a Username field, a Password field and a Button.
The logic is very basic, I have a built a winform app with a built in webbrowser.
At the Document_Completed event I use the following code to enter my settings and to click the button.
private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser.Url.ToString() == #"MyWebPage/signin")
{
HTMLDocument hdc = new HTMLDocumentClass();
hdc = (HTMLDocument)webBrowser.Document.DomDocument;
IHTMLElement elb = hdc.getElementById("login_button");
IHTMLInputElement elu = (IHTMLInputElement)hdc.getElementById("username");
IHTMLInputElement elp = (IHTMLInputElement)hdc.getElementById("password");
try
{
elu.value = "MyID";
elp.value = "MyPwd";
elb.click();
}
catch { }
}
}
Apart for this code being very quick and without error handling, it should do the trick and it does, partially..
There are two scenario's:
I launch the tool, it loads the webpage.
The tool populates the UserID field and the Password field correctly
The tool fails to click the button
I click the button manually, I am logged in, I click logout, I am back at login page
I immediatly logged in again, the tool enters the information
The tool immediatly clicks the button as well.
Is there anyone who might be able to explain me why this happens and how I could get around this with the current setup (hence not using HttpWebRequest). I don't see the difference between loading the page at startup or being redirected after logout, but apparently there is a difference in there or I am doing something wrong.
Any feedback on this matter is very much appreciated.
Thanks,
Kevin
EDIT:
I added a Button to my Windows Form that bas the same backend Code as below in order to click the button on the webpage, this works perfectly.
I triggered clicking this button in the webBrowser_Completed event but it doesn't work.
For some reason, everything I add to the webBrowser_DocumentCompleted event does not allow me to trigger the click event for the button in my WebBrowser control. Once that entire event has completed, if I then try to trigger it it works but I would like to automate this.. Any advice?
This might be a long shot and not the most elegant workaround but how about letting a backgroundworker run for a second in your DocumentCompleted event that then triggers the button that you clicked from it's seperate thread. This might just get this automated.
As this will run from a different thread, keep in mind that you might have to invoke certain controls so this might be another downside to this workaround..
If this doesn't work then, as Regfor previously suggested, Watin.org can help you out.
how about this :
HtmlElement button = webBrowser.HtmlDocument.GetElementById("login_button");
button.InvokeMember("click");
it works in my program.

Changing button event after button click in C#

I've a form that navigates webpage and access data. It looks like something below.
private void LoginButton_Click(object sender, EventArgs e)
{
if(LoginButton.Text == Login)
{
LoginButton.Text = "Logging in...";
....
...
Login process goes here...
..
if(Login Successed)
{
LoginButton.Text ="Download";
}
else
{
LoginButton.Text = "Login";
}
}
else if(LoginButton.Text==Download)
{
Download data here...
}
}
Same button(And same event too), doing two process and seems like different events with a label.
1) If there any problem like inefficiency run?
2) Any alternate ways to do this like different flag schemes?
3) Any method to have with more than one event for same button to achieve same idea?
Thanks.
1) If there any problem like inefficiency run?
Button clicks run at human time. You can burn half a billion cpu instructions without inconveniencing the user.
2) Any alternate ways to do this like different flag schemes?
Using the Text property of the button is fragile, your code will break when somebody decides to change the button text or when you localize your app to another language. A simple private bool field in your class is much better.
3) Any method to have with more than one event for same button to achieve same idea?
No. You could of course use two buttons, placed on top of each other and one of them always hidden. Makes localization much simpler and you'll get that bool field for free.
like Daniel A. White said
have two buttons
may be on some event like oncreate/onload do check..jst a pseudo code
if process is login then
do
//then showLoginButton
btnlogin.visible
else
//download
btndonload.visible
inside the login button
if(Login Successed)
{
btndonload.visible
}
else
{
LoginButton.Text = "Login";
}
this may be better with two buttons then single..and cleaner also
Write custom event handlers for the mouseClick
Write separate methods for login and download.
Register your custom event handlers to the button click event
I assume there is some logic that decides that the button text should be "download" or "login". At that point, set the button text of course, but also register the appropriate event handler.
This will allow you to have a single button that does anything
protected void Login_MouseClickHandler (object obj ,MouseClickEventArgs e) {
// login logic
// this would be the logic you say is "inside the login button"
}
protected void Download_MouseClickHandler (object obj ,MouseClickEventArgs e) {
// download logic
}
// pseudo code
// note that there is only one button
if process is login then
theButton.text = "login"
theButton.MouseClick += new MouseClickEventHandler(Login_MouseClickHandler)
else
button.text = "download"
theButton.MouseClick += new MouseClickEventHandler (Download_MouseClickHandler)
end if
Software Design Thoughts
Easier to extend. We don't need another button for every new thing to do
Separation of Concerns - All login code, for example, is in a separate method that does only login stuff.
Change is isolated and minimized. Writing new, separate methods is less error prone than in-lining that code in your if else structure. And consequently the if else structure is kept simple and comprehensible.
It is generally a bad idea use the text as the state. Ideally, you should have 2 buttons that fire different events and call out the main logic to a presenter in the MVP pattern.
Use control containers such as Panel and GroupBox. You can have a whole bunch of Panels for controls in different states.

Categories

Resources