How do i catch page cannot load message? - c#

Hi i hope someone can help,
In basic terms i am trying to stop the embedded browser, in my Windows Forms app, from navigating to the 'This program cannot display the webpage' page and instead display my own error page.
The C# application is a Web Browser embedded in my Windows Forms, its purpose is allowing the user to click on the provided buttons that navigate the browser to predefined WebService URL's. If the Service is not running on the Machine then instead of the browser saying that it was unable to load i need to to navigate to my custom page instead.
I have looked around and as yet had no luck in finding a solution apparently HttpStatusCodes are a way to go but i have no idea how to use them.
Code Snippet:
private void currentMachineToolStripMenuItem_Click(object sender, EventArgs e)
{
webBrowser1.Navigate("http://localhost:2021/wsservice/status");
}
As you can see, currently very simple program.

You can try this:
Private void WebBrowser1_NavigateError(Object sender, EventArgs e)
{
WebBrowser1.Navigate( App.Path + "\retry.htm");
}

Taken from this link -
You would need to use an HttpWebRequest and an HttpWebResponse object to do
this. Create the HttpWebRequest with the desired URL, using the
WebRequest.Create(url) method. Then use the GetResponse() method to get the
HttpWebResponse. The HttpWebResponse will have the status code returned from
the server. This will tell you if the URL exists or not. 404 indicates "Page
not Found." 200 indicates "Success." Etc.
http://msdn.microsoft.com/en-us/library/8y7x3zz2(vs.71).aspx
Also another link which might help you - http://www.vcskicks.com/check-website.php

You can check the page content for a word that indicates that the page did not load correctly
if(webBrowser1.Document.InnerHtml.Contains("error"))

You can check too the returned document url, find the resource address that webBrowser use to show error page:
if (webBrowser1.Document.Url.ToString().Contains("res://ieframe.dll/dnserrordiagoff.htm") )
...

Related

No WCF service response - C#

I have added a service reference, directed to a WSDL which loaded all existing WSDLs from the location. I am trying to request data by calling one of the methods like this:
protected void Page_Load(object sender, EventArgs e)
{
string fLastname, folder, status, header, responsible;
int date;
PyramidServices.ServiceSoapClient client = new PyramidServices.ServiceSoapClient();
string activity = client.GetUserActivity("xxxx", "xxxx", out fLastname, out folder, out status, out date, out header, out responsible);
}
When debugging, the vars are all null. . I have a hard time understanding trace messages since this is not my field. I don't know what to look for, so here is pretty much all the information I get when tracing (Sorry for the Swedish version!):
Sending:
Receiving:
Answer # Channel:
Stop:
[EDIT]
I tested the method using WCF Test Client and received following:
So it's kind of obvious that I am doing something wrong with the code when parsing the data from the response? My question is, how do I accomplish this?
With a lot of help from #TomW, we finally found out what the problem was. The code for the WSDL is created in a system that lets me add XML nodes surrounding the data like below:
<wrap>
<data1></data1>
<data2></data2>
<data3></data3>
</wrap>
instead of:
<data1></data1>
<data2></data2>
<data3></data3>
<data1></data1>
<data2></data2>
<data3></data3>
<data1></data1>
<data2></data2>
<data3></data3>
Therefor, the code generated by Visual Studio in Service Reference did not like the way I wrapped the data with unwanted tags. After removing the tag from my code in the system, I received exactly what I wanted with the code at the top.

HttpWebResponse returns only one element of the page

Hello i making a simple httpwebrequest and then i read (StreamReader) the response and just want to get the html page of website,but i get only one laber(only one element of the page) in the browser all fine(i see all page) but when i try to set cookies to Deny\disable i also in the browser get this label(only one element of the page) and all is disappear.Sow i getting opinion if after i disabled cookies in browser i get the same page(like in code) that mean my HttpWebRequest is have settings cookies=deny/disable.
You can go to https://www.bbvanetcash.com/local_kyop/KYOPSolicitarCredenciales.html and disable cookies with F12 and you will see the difrance and also this page with one label.
Sow this my code any ideas what i need to change here?
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create("https://www.bbvanetcash.com/local_kyop/KYOPSolicitarCredenciales.html");
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Stream streamResponseLogin = myHttpWebResponse.GetResponseStream();
StreamReader streamReadLogin = new StreamReader(streamResponseLogin);
LoginInfo = streamReadLogin.ReadToEnd();
Your code is receiving complete page content, but it cannot receive the dynamic contents. This is happening because the page you are trying to access relies on Cookies for maintaining session as well as JavaScript (it is using jQuery) for loading dynamic contents and providing rich user experience.
To successfully receive the whole page, your code must
support retrieving, storing and sending cookie objects across various HttpRequest and HttpResponse.
be able to execute JavaScript code to load the dynamic contents/markup of the page
To test 'if your code is receiving proper values or not' visit the site Web Sniffer and put your URL there.
As you can try on web-sniffer site, for www.google.com, the response you are getting is a redirect instruction.... that means, even to access the Google's home page, your code must understand HTTP status messages (302 there).

redirecting to page from inside iframe

I have just now started coding in .NET framework, so my apologies if this issue happens to be of trivial nature.
What I got now
A main.aspx page with simple layout using three iframes
the middle iframe content needs to be dynamic (first a login.aspx page and after logging entryform.aspx)
Issue #1 :
After logging in login.aspx inside the iframe, redirecting to main.aspx
The solution I found:
ClientScript.RegisterStartupScript(this.GetType(),"scriptid",
"window.parent.location.href='main.aspx'", true);
(http://forums.asp.net/t/1273497.aspx)
Issue #2
After redirecting/logging how do I change the middle iframe content from login.aspx to entryform.aspx?
The silly solution I thought of:
Add '#form' to the url and listen to hashchange event in main.aspx. But then, anyone can get to the form using the url itself.
So, basically how do I find a secure way to tell the main.aspx page that it needs to change it's middle iframe content after the redirecting/logging
Or by any chance there is a request.setAttribute and getAttribute in .NET like in java that I have missed and made things difficult for me?
Passing variables or values across pages and domains wont be issue, you can use post method and cross page posting for that
After finding that the use of iframe isn't exactly the best idea in my case, I took Tieson T's advice and looked into HttpClient to fetch content from other web pages. In my case it will be both from same domain and other domains.
Since I have 4.0v .NET instead of HttpClient I used HttpWebRequest
code
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (http://localhost:1706/WebSite3/test.html);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader reader = new StreamReader(response.GetResponseStream(),encode );
string html= reader.ReadToEnd();
myDiv.innerHtml(html);
References
HttpClient does not exist in .net 4.0: what can I do?
http://msdn.microsoft.com/en-us/library/456dfw4f.aspx
http://forums.asp.net/t/1382935.aspx/1
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx
http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.aspx
http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx
Wouldn't it be easier to just pass a parameter to Main.aspx? E.g.
ClientScript.RegisterStartupScript(this.GetType(),"scriptid", "window.parent.location.href='main.aspx?LoadEntry=true'", true);
And client-side JavaScript code inside of 'main.aspx' would read that parameter from 'location.search' and if 'LoadEntry=true' is set - would set SRC of middle frame to "entryform.aspx".
Of course inside of "entryform.aspx.cs" you would need to check if correct login really took place (e.g. some Session variable is set) so nobody would be able to simple set URL manually to "main.aspx?LoadEntry=true" to bypass the login.

best practise for ASP.NET Lifecycle in regards to data loading?

I have a question regarding the best practises in terms of data loading with ASP.NET and C#
As an overview, we have a web page that uses a supporting web service to obtain an fairly large XML file. That file is then translated into client side JavaScript for use of loading ListViews.
protected string clientSideJavaScripts;
protected void Page_Init(object sender, EventArgs e)
{
// code goes here to submit a request and receive an XML Response from the web service
// code goes here to set clientSideJavaScripts = translated Java Script from the XML Document
// other code goes here
}
The ASP file has something along the lines of:
<head>
<title></title>
<script type="text/javascript>
<%=clientSideJavaScripts%>
</scrpit>
</head>
...
However additionally there are several buttons on the form that cause postbacks. These are not directly related to the javascript above.
Everything works well, however I believe (with my limited knowledge of the ASP.NET lifecycle), that that webservice is getting called every postback. So every time anyone clicks on of the few asp:buttons on the webpage, it is doing the overhead of loading that file regardless of the nature of the button, since a postback will cycle through the stages of the lifecyce from Init up to and past the postback event handling.
The obvious thing to do would be to not call the webservice on postback. I.E:
protected string clientSideJavaScripts;
protected void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// code goes here to submit a request and receive an XML Response from the web service
// code goes here to set clientSideJavaScripts = translated Java Script from the XML Document
}
// other code goes here
}
However the result of that is that the server side string 'clientSideJavaScripts' no longer gets instanciated, and therefore client side no longer gets the required javascript after tje first postback.
I am sure that I am missing an obvious (and probably common) method to deal with the persistancy of the javascript in a case like this, however I don't know of it and therefore I am looking to anyones advice regarding this. What would be the best practise to ensure that the Webservice is only called once?
I am also using AJAX and JQuery Mobile, if that makes any difference
Any advice would be greatly appreciated.
Many thanks

How to capture HTML of redirect page before it redirects?

I am trying to read the HTML of a page that contains a non-delayed redirect. The following snippet (C#) will give me the destination/redirected page, not the initial one I need to see:
using System.Net;
using System.Text;
public class SomeClass {
public static void Main() {
byte[] data = new WebClient().DownloadData("http://SomeUrl.com");
System.Console.WriteLine(Encoding.ASCII.GetString(data));
}
}
Is there a way to get the HTML of a redirecting page? (I prefer .NET but a snippet in Java or Python would be fine too. Thx!)
Unless the redirect is done on the client side you can't. If the redirect is done server side, then no html is actually generated to the client, but the header is redirected at the new server.
It would take more work, but rather than using WebClient, use HttpWebRequest and set the AllowAutoRedirect property to False. A redirect will then throw an exception, but you can get any response text (and some pages do have response text along with the redirect) from the exception's response object. After you get the response from the exception, you can issue another HttpWebRequest for the redirect URL (specified in the Location response header).
You might be able to do something similar with WebRequest if you create a derived object, MyWebRequest, where you overload the GetWebRequest method and set the AllowAutoRedirect property. I don't know what kind of exception, if any, the DownloadData method will return if you do something like that.
As somebody said previously, this will only work for those pages that do client-side redirects (typically 301 or 302). If there is server-side redirection going on, you'd never know it.
Simplest answer would be to add the current page onto the QueryString component of the redirect when redirecting, for instance:
Response.Redirect(newPage + "?FromPage=" + Request.Url);
Then the new page could see where you cane from by simply looking at Request.QueryString("FromPage").
If you want to get the source of an html page you can use this tool:
http://www.selfseo.com/html_source_view.php

Categories