am trying to use webbrowser control in my windows form application to display web pages like youtube, BBC etc. Am seeing that in some of the sites the CSS is totally out of place and scripts are not being executed. Can some help me resolve this. Also is there any possible method with which i can open IE in kiosk mode inside and windows form?
Below is the code that am currently using to launch my sites.
private void browser_Load(object sender, EventArgs e)
{
this.ControlBox = false;
this.WindowState = FormWindowState.Maximized;
toolStripButton1.Text = etext;
toolStripLabel1.Text = webnamedisplayname;
browser.ScriptErrorsSuppressed = true;
browser.Navigate(NavUrl);
}
After years of using the WebBrowser Control I never had a problem until recently! In my case, I was being served a Mobile version of the Pages I was requesting! A real pain, all due to a little app called: "Mobvious"
I managed to get around this issue by using the following code:
private void GetWebPage()
{
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(this.AddressTextBox.Text);
Request.Method = "GET";
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
string Server = Response.Server;
HttpStatusCode StatusCode = Response.StatusCode;
if (StatusCode == HttpStatusCode.OK)
{
Stream ResponseStream = Response.GetResponseStream();
StreamReader Reader = new StreamReader(ResponseStream);
this.webBrowser1.DocumentText = Reader.ReadToEnd();
}
else
{
this.BadURI = this.BadURI + 1;
}
}
Related
Im trying to create an android app with xamarin.I want the user to be able to input an address/location and receive POI (Points of Interest) near it (within a certain radius).
I know google places api can do this, does xamarin have built in capability for something like this? Can I somehow interface with the Google Places api?
Or is there something I don't know about? Thanks for the help!
Use HTTPWebRequest class to create a request to Google API, code snippet:
private void button1_Click(object sender, EventArgs e)
{
HttpWebRequest webRequest = WebRequest.Create(#"https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=7500&types=library&sensor=false&key=AIzaSyD3jfeMZK1SWfRFDgMfxn_zrGRSjE7S8Vg") as HttpWebRequest;
webRequest.Timeout = 20000;
webRequest.Method = "GET";
webRequest.BeginGetResponse(new AsyncCallback(RequestCompleted), webRequest);
}
private void RequestCompleted(IAsyncResult result)
{
var request = (HttpWebRequest)result.AsyncState;
var response = (HttpWebResponse)request.EndGetResponse(result);
using (var stream = response.GetResponseStream())
{
var r = new StreamReader(stream);
var resp = r.ReadToEnd();
}
}
copy over from here... pretty straightforward and simple...
I'm trying to load a page in WebBrowser thorugh responseStream sent by the server. I tried setting, its DocumentStream property but the browser is not navigating. This is my code:
private void btnFbConnect_Click(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create("http://www.facebook.com");
request.Method = "GET";
WebResponse response = request.GetResponse();
StreamReader rdr = new StreamReader(response.GetResponseStream());
webBrowser1.DocumentStream = rdr.BaseStream;// after this line, I'm expecting the browser to display the facebook login page.
MessageBox.Show(rdr.ReadToEnd());
rdr.Close();
response.Close();
}
Am I missing an intermediate step or something??? If not, what might be causing the browser not to cause navigation???
Don't close the stream before the WebBrowser accesses it.
WebRequest request = WebRequest.Create("http://www.facebook.com");
request.Method = "GET";
WebResponse response = request.GetResponse();
StreamReader rdr = new StreamReader(response.GetResponseStream());
webBrowser1.DocumentStream = rdr.BaseStream;// after this line, I'm expecting the browser to display the facebook login page.
MessageBox.Show(rdr.ReadToEnd());
//rdr.Close();
//response.Close();
Additionally, you might encounter a error because the relative path resources on the server cannot be resolved. So, I recommend you use:
webBrowser1.Navigate("http://www.facebook.com");
i have written a program to search value from google every thing works fine but first time when page is loaded then i encounter error.after words if i click any link it is working fine no errors further.
Code is as follow
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string raw = "http://www.google.com/search?hl=en&q={0}&aq=f&oq=&aqi=n1g10";
string search = string.Format(raw, HttpUtility.UrlEncode(searchTerm));
//string search = "http://www.whatismyip.com/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(search);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
{
browserA = reader.ReadToEnd();
this.Invoke(new EventHandler(IE1));
}
}
}
This error didn't come from Http webrequest,it's from the web browser control on your form.
It's a javascript error raised by web browser control,you can suppress it by:
webBrowser.ScriptErrorsSuppressed = true;
Disable Internet Explorer notification for script errors
see http://www.tech-faq.com/internet-explorer-script-error.html
I need to write a simple C# app that should receive entire contents of a web page currently opened in Firefox. Is there any way to do it directly from C#? If not, is it possible to develop some kind of plug-in that would transfer page contents? As I am a total newbie in Firefox plug-ins programming, I'd really appreciate any info on getting me started quickly. Maybe there are some sources I can use as a reference? Doc links? Recommendations?
UPD: I actually need to communicate with a Firefox instance, not get contents of a web page from a given URL
It would help if you elaborate What you are trying to achieve. May be plugins already out there such as firebug can help.
Anways, if you really want to develop both plugin and C# application:
Check out this tutorial on firefox extension:
http://robertnyman.com/2009/01/24/how-to-develop-a-firefox-extension/
Otherwise, You can use WebRequest or HttpWebRequest class in .NET request to get the HTML source of any URL.
I think you'd almost certainly need to write a Firefox plugin for that. However there are certainly ways to request a webpage, and receive its HTML response within C#. It depends on what your requirements are?
If you're requirements are simply receive the source from any website, leave a comment and I'll point you towards the code.
Uri uri = new Uri(url);
System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri.AbsoluteUri);
req.AllowAutoRedirect = true;
req.MaximumAutomaticRedirections = 3;
//req.UserAgent = _UserAgent; //"Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; Searcharoo.NET)";
req.KeepAlive = true;
req.Timeout = _RequestTimeout * 1000; //prefRequestTimeout
// SIMONJONES http://codeproject.com/aspnet/spideroo.asp?msg=1421158#xx1421158xx
req.CookieContainer = new System.Net.CookieContainer();
req.CookieContainer.Add(_CookieContainer.GetCookies(uri));
System.Net.HttpWebResponse webresponse = null;
try
{
webresponse = (System.Net.HttpWebResponse)req.GetResponse();
}
catch (Exception ex)
{
webresponse = null;
Console.Write("request for url failed: {0} {1}", url, ex.Message);
}
if (webresponse != null)
{
webresponse.Cookies = req.CookieContainer.GetCookies(req.RequestUri);
// handle cookies (need to do this incase we have any session cookies)
foreach (System.Net.Cookie retCookie in webresponse.Cookies)
{
bool cookieFound = false;
foreach (System.Net.Cookie oldCookie in _CookieContainer.GetCookies(uri))
{
if (retCookie.Name.Equals(oldCookie.Name))
{
oldCookie.Value = retCookie.Value;
cookieFound = true;
}
}
if (!cookieFound)
{
_CookieContainer.Add(retCookie);
}
}
string enc = "utf-8"; // default
if (webresponse.ContentEncoding != String.Empty)
{
// Use the HttpHeader Content-Type in preference to the one set in META
doc.Encoding = webresponse.ContentEncoding;
}
else if (doc.Encoding == String.Empty)
{
doc.Encoding = enc; // default
}
//http://www.c-sharpcorner.com/Code/2003/Dec/ReadingWebPageSources.asp
System.IO.StreamReader stream = new System.IO.StreamReader
(webresponse.GetResponseStream(), System.Text.Encoding.GetEncoding(doc.Encoding));
webresponse.Close();
This does what you want.
using System.Net;
var cli = new WebClient();
string data = cli.DownloadString("http://www.heise.de");
Console.WriteLine(data);
Native messaging enables an extension to exchange messages with a native application installed on the user's computer.
Although i can grasp the concepts of the .Net framework and windows apps, i want to create an app that will involve me simulating website clicks and getting data/response times from that page. I have not had any experience with web yet as im only a junior, could someone explain to me (in english!!) the basic concepts or with examples, the different ways and classes that could help me communicate with a website?
what do you want to do?
send a request and grab the response in a String so you can process?
HttpWebRequest and HttpWebResponse will work
if you need to connect through TCP/IP, FTP or other than HTTP then you need to use a more generic method
WebRequest and WebResponse
All the 4 methods above are in System.Net Namespace
If you want to build a Service in the web side that you can consume, then today and in .NET please choose and work with WCF (RESTfull style).
hope it helps you finding your way :)
as an example using the HttpWebRequest and HttpWebResponse, maybe some code will help you understand better.
case: send a response to a URL and get the response, it's like clicking in the URL and grab all the HTML code that will be there after the click:
private void btnSendRequest_Click(object sender, EventArgs e)
{
textBox1.Text = "";
try
{
String queryString = "user=myUser&pwd=myPassword&tel=+123456798&msg=My message";
byte[] requestByte = Encoding.Default.GetBytes(queryString);
// build our request
WebRequest webRequest = WebRequest.Create("http://www.sendFreeSMS.com/");
webRequest.Method = "POST";
webRequest.ContentType = "application/xml";
webRequest.ContentLength = requestByte.Length;
// create our stram to send
Stream webDataStream = webRequest.GetRequestStream();
webDataStream.Write(requestByte, 0, requestByte.Length);
// get the response from our stream
WebResponse webResponse = webRequest.GetResponse();
webDataStream = webResponse.GetResponseStream();
// convert the result into a String
StreamReader webResponseSReader = new StreamReader(webDataStream);
String responseFromServer = webResponseSReader.ReadToEnd().Replace("\n", "").Replace("\t", "");
// close everything
webResponseSReader.Close();
webResponse.Close();
webDataStream.Close();
// You now have the HTML in the responseFromServer variable, use it :)
textBox1.Text = responseFromServer;
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}
}
The code does not work cause the URL is fictitious, but you get the idea. :)
You could use the System.Net.WebClient class of the .NET Framework. See the MSDN documentation here.
Simple example:
using System;
using System.Net;
using System.IO;
public class Test
{
public static void Main (string[] args)
{
if (args == null || args.Length == 0)
{
throw new ApplicationException ("Specify the URI of the resource to retrieve.");
}
WebClient client = new WebClient ();
// Add a user agent header in case the
// requested URI contains a query.
client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
Stream data = client.OpenRead (args[0]);
StreamReader reader = new StreamReader (data);
string s = reader.ReadToEnd ();
Console.WriteLine (s);
data.Close ();
reader.Close ();
}
}
There are other useful methods of the WebClient, which allow developers to download and save resources from a specified URI.
The DownloadFile() method for example will download and save a resource to a local file. The UploadFile() method uploads and saves a resource to a specified URI.
UPDATE:
WebClient is simpler to use than WebRequest. Normally you could stick to using just WebClient unless you need to manipulate requests/responses in an advanced way. See this article where both are used: http://odetocode.com/Articles/162.aspx