How to detect if page load in newly-started browser process fails? - c#

I use Process.Start("firefox.exe", "http://localhost/page.aspx");
And how i can know page fails or no?
OR
How to know via HttpWebRequest, HttpWebResponse page fails or not?
When i use
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("somepage.aspx");
HttpWebResponse loWebResponse = (HttpWebResponse)myReq.GetResponse();
Console.Write("{0},{1}",loWebResponse.StatusCode, loWebResponse.StatusDescription);
how can I return error details?
Not need additional plugins and frameworks. I want to choose this problem only by .net
Any Idea please

Use Watin to automate firefox instead of Process.Start. Its a browser automation framework that will let you monitor what is happening properly.
http://watin.sourceforge.net/
edit: see also Google Webdriver http://google-opensource.blogspot.com/2009/05/introducing-webdriver.html

If you are spawning a child-process, it is quite hard and you'd probably need to use each browser's specific API (it won't be the same between FF and IE, for example).
It doesn't help that in many cases the exe detects an existing instance and forwards the request there (so you can't trust the exit-code, since the page hasn't even been requested in the right exe yet).
Personally, I try to avoid assuming any particular browser for this scenario; just launch the url:
Process.Start("http://somesite.com");
This will use the user's default browser. You have to hope it appears though - you can't (reliably and robustly) check that externally without lots of work.
One other option is to read the data yourself (WebClient.Download*) - but this may have issues with complex cookies, login, user-agent awareness, etc.

Use HttpWebRequest class or WebClient class to check this. I don't think Process.Start will return something if the URL not exists.

Don't start the page in this form. Instead, create a local http://localhost:<port>/wrapper.html which loads http://localhost/page.aspx and then either http://localhost:<port>/pass.html or http://localhost:<port>/fail.html. localhost: is a trivial HTTP server interface implemented by your app.
The idea is that Javascript gives you an API inside the browser, which is far more standard than the APIs on the outside of browsers. Since the Javascript on wrapper.html comes from the same server and even port as the subsequent resources, this should satisfy the same-origin policies in current browsers.

Related

Why IE Keeps sessions alive?

Hy all!
I'm developing a MVC 4.0 web application with C# and came accros the following error.
In major browsers (Chrome, Mozilla Safari, etc...) when i click logout in my web application it does the correct, logout the current user.
When i do the same operation on IE, dosen't work, i login with the new user, and IE keeps the last user until i press ctrl+F5.
The only thing i'm using for authentication is Sessions, nothing more.
Someone came acrros this issue? i've tried clear cache, clear sessions with abadon, clear, removeall and nothing seems to work when i'm on IE.
If you guys need some more info to help me with that, i'll answer as soon as possible!!
I've found the following works:
Session.Clear()
Session.Abandon()
Session.RemoveAll()
If Request.Cookies("ASP.NET_SessionId") IsNot Nothing Then
Response.Cookies("ASP.NET_SessionId").Value = ""
Response.Cookies("ASP.NET_SessionId").Expires = DateTime.Now.AddMonths(-20)
End If
Usually, browsers implement it so that ctrl+f5 means "make an http request for the current url, without the browser cache). So, no matter what you do after the fact in your server-side code, because IE is by default reloading the current page from its local memory without even hitting your server, you will not appear logged out. Then, when it does eventually go back to your server, it's still sending the same cookie because the page that would have logged you out is never actually hit.
One way to test if this is happening, is to set a breakpoint in your logout code. Refresh the page without holding ctrl in IE, and see if the breakpoint is even hit. If it's not, then you know client-side caching is the cause.
Workarounds:
This code on the server will send the page with metadata indicating the browser is not allowed, under any circumstances, to cache the page on their side:
response.Cache.SetAllowResponseInBrowserHistory(false);
response.Cache.SetCacheability(HttpCacheability.NoCache);
response.Cache.SetNoStore();
response.Cache.SetExpires(DateTime.Now);
response.Cache.SetValidUntilExpires(true);
-- or --
When you go to your logout page with a link like this: /logout or /home?logout=1 add an extra paramter like this: /logout?cacheBust=123yt74y5t, making the last part random. This works because most browser caches will cache based on url, so if you randomly mess up an unimportant part of the url, you can get around it. One advantage to this method is that you actually want the browser to cache some pages, but not others, and this is a more client-side way of determining if you want a fresh copy from the server or not.

Control the browser through c# or some other way

Okay I know c# got a vast and very ease to use application development programs but this is what i want to learn now.So when user opens his browser and enters some url in it. Is it possible to send this data or the entered url addressto some other code one such a c# code or some other example c++ which is located on his hard drive.
To be simple when user clicks some link on a webpage or enters some url or closes the browser or when he opens the web browser, Can we detect all his actions that he perform on web browser through c# code or anyother way(I guess add-on or pluins the way it works) but Is it possible to send his actions to c# code and program it and give certain output back to browser so that browser performs it and outputs to user.
Something like browser-->c#code-->website.. I want c# code to act between the browser and webpages.
work I tried so far
I started googling on this and learnt little about how browsers work but still unable to find the solution. However I guess plugins are the way to do such tasks and found firebreath cross platform,a way to develop plugins for browsers. So is this possible by plugins? if so could you suggest me some good tools to develop my own plugins. Thanks
There are several options depending on what you want to achieve:
Proxy
You could implement a http proxy and configure the browser to use that proxy. The proxy sees all traffic and can do whatever it wants... this works rather "browser-agnostic". See the links here and here.
PlugIn
You could implement a plugin... alhtough this a browser-specific... for example IE used to have BHOs to this kind of stuff (not sure whether this is still possible with IE10...). Some options can be found here, here, here, here and here.
You can use FiddlerCore for this
Fiddler.FiddlerApplication.BeforeRequest += sess =>
{
Console.WriteLine("REQUEST TO : " + sess.fullUrl);
sess.bBufferResponse = true;
};
Fiddler.FiddlerApplication.Startup(8877, true, true);
Console.ReadLine();
Fiddler.FiddlerApplication.Shutdown();
System.Threading.Thread.Sleep(750);
After running this code, open your browser and navigate to any page.

Asp.net ajax - losing session variables - Internet Explorer 8 and prior versions

I have been working on a legacy project (although C#) and trying to solve a session problem that have been encovered for years. It hapens on IE8 and prior versions. On IE9, Google Chrome, Firefox and Safari works fine.
In other words, we have a management software that works fine on all browsers. But there is a specific page that makes tons of Ajax requests, and in some point it loses the session data.
I have checked for cookie problems with Fiddle but they are always sent and the same.
These clues make us think that the problem is within the application. But if we remember the problem occurs just in IE8 and prior versions we think the issue is probably in the browsers.
We also use a legacy Ajax library. And the problem mustn't be there as many of our aplications
use it and they doesn't have the same problem.
We are using IIS7 with State Server
I'm almost out of ideas. I hope you have some.
I got it!
Using Fiddler, I saw a very suspect request for "/". There was something requesting for the site base URL. And I remembered that the default page of this particular web application kills the session data, in other words calling the login page also means to log the user off.
After some hours of debugging and sniffing I found what was making such request.
There is a javascript function that creates some image tags. Some times those tag were created with an empty address, in other words the src property of the img tag was a string with 0 legth.
It must be an IE8 and older versions bug, as they request the website root instead of not requesting anything. Maybe it's not a bug, but this behavior is certainly unexpected.
Phew! I still can't believe I found it.
Losing session state can be result of the application error. But if you claim that this happens only on IE8 and older versions, this could not be the case...
So I would suggest you to use page ViewState instead of session state. Let me know if did the trick for you?
Here is sample how to create propety based on page viewstate, just make sure you have enabled viewstate on page level:
public string MyProperty
{
get
{
return ViewState["MyProperty"] as string;
}
set
{
ViewState["MyProperty"] = value;
}
}

Response.Redirect going to wrong destination

I am working on a c# .NET website in which the user can click on a link and get redirected to another web page in a separate website also owned by us. The code is very easy to understand, there is a switch followed by a call to Response.Redirect(the_url_we_want_to_go_to).
I have debugged it numerous times and I can confirm that when the debugger hits this redirect line that the parameter is correct. It points to the QA version of this other website. qa.samplesite.com lets say. However, the browser does not go there. The browser instead hits the test environment instead. Lets call it test.samplesite.com. This is the problem.
I understand there are a million things in between the app servers these two separate websites are on, but maybe one of you has seen something like this before. More specifically, is there a way to catch outbound traffic in the debugger or is there a way to see outbound traffic on the app server itself (in IIS)? I am familiar with intercepting inbound traffic inside of httpmodules. Maybe this isnt a stackoverflow question...
Thanks for your help!
Use the very nice HTTP sniffer "Fiddler". It will allow you to see all HTTP requests. You should verfiy that a) the redirect target is correct (it might be overwritten later in the request pipeline. A Response.Redirect is not the final word) and b) that you don't have a second redirect after the first one.
You can try using the overload of Response.Redirect as
Response.Redirect("url_here", true);
This will stop the response on current page (as endResponse is set to true) and redirect to the url.
If you still have the issue, then this might be some name resolution error.
Check to see you your hosts files in the windows directory found here
C:\Windows\System32\drivers\etc\hosts
Hope this will do it.
I finally figured a similar issue I had. It was quite silly. I had copied some .aspx pages making minor changes. The page where I tried to redirect the client, had it's "CodeBehind" setting wrong. So it redirected to the right page, but loaded the CodeBehind from another page!

Is it possible to fill in an Ajax form programatically?

I'm doing some automation work and can make my way around a site & post to HTML forms okay, but now I'm up against a new challenge, Ajax forms.
Since there's no source to read, I'm left wondering if it's possible to fill in an Ajax form progamatically, in C#. I'm currently using a non-visible axWebBrowser.
Thanks in advance for your help!
Yes, but I recommend using a different approach to requesting/responding to the server pages including the regular pages, and the AJAX handler pages.
In c#, try using the WebRequest/WebResponse or the more specialized HttpWebRequest/HttpWebResponse classes.
Ajax is no more than a "fancy" name for a technology that allows Javascript to make HTTP requests to a server which usually implements some handlers that produce specialized, light-weight content for the Javascript caller (comonly encoded as JSON).
Therefore in order to simulate AJAX calls, all you have to do is inspect your target application (the web page that you want to "post" to) and see what format is used for the AJAX communications - then replicate the page's Javascript behavior from C# using the WebREquest/WebResponse classes.
See Firebug - a great tool that allows you to inspect a web page to determine what calls it makes, to which pages and what those pages respond. It does a pretty good job at inspecting AJAX calls too.
Here's a very simple example of how to do a web request:
HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create("http://www.mysite.com");
using (HttpWebResponse resp = (HttpWebResponse)wReq.GetResponse())
{
// NOTE: A better approach would be to use the encoding returned by the server in
// the Response headers (I'm using UTF 8 for brevity)
using (StreamReader sr = new StreamReader(resp.GetResponseStream(), Encoding.UTF8))
{
string content = sr.ReadToEnd();
// Do something with the content
}
}
A POST is also a request, but with a different method. See this page for an example of how to do a very simple post.
EDIT - Details on Inspecting the page behavior with Firebug
What I mean by inspecting the page you're trying to replicate is to use a tool (I use Firebug - on Firefox) to determine the flow of information between the page and the server.
With Firebug, you can do this by using the "Net" and "Console" panels. The Net panel lists all requests executed by the browser while loading the page. While the "Console" will list communications between the page and the server that take place after the page has loaded. Those communications that take place after the page has loaded are essentially the AJAX calls that you'll want to replicate (Note: Network monitoring has to be enbled in Firebug for this to work)
Check out Michael Sync's tutorial to learn more about Firebug and experiment with the Console panel to learn more about the AJAX requests.
Regarding "replicate the page's behavior from C# using the WebRequest/WebResponse" - what you have to realize is that like I said earlier, the Javascript AJAX call is nothing more than an HTTP Request. It's an HTTP Request that the Javacript makes "behind the scenes", or out-of-band, to the web server. To replicate this, it is really no different than replicating a normal GET or a normal POST like I showed above. And this is where Firebug comes in to play. Using it you can view the requests, as the Javascript makes them - look at the Console panel, and see what the Request message looks like.
Then you can use the same technique as above, using the HttpWebRequest/HttpWebResponse to make the same type of request as the Javascript does, only do it from C# instead.
Gregg, I hope this clarifies my answer a little bit but beyond this I suggest playing with Firebug and maybe learning more about how the HTTP protocol works and how AJAX works as a technology.
Have you looked at using Selenium. AFAIK, you can write the test cases in C# and I know our testers have successfully used it before to UI Test a Ajax enabled ASP.NET site
http://seleniumhq.org/

Categories