how to convert string data to html in richtextbox - c#

I am fetching the response using httpwebrequest in winform now i want to display it as html page in my winform for this i am using richtextbox but it is simply displaying me text not html please tell me how can do it here is my code for this
Uri uri = new Uri("http://www.google.com");
if (uri.Scheme == Uri.UriSchemeHttp) {
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
richTextBox1.Text = tmp;
}

There is a .Net control which allows editing of html in winforms,
Take a look http://winformhtmltextbox.codeplex.com/

Related

Read data from parse.com does not work

I have this code to read JSON data from the parse.com
protected void Button4_Click(object sender, EventArgs e)
{
string URL = "https://api.parse.com/1/classes/SecondObject";
// string DATA = jsonString;
string text;
var request = WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json";
request.Headers.Add("X-Parse-Application-Id", "aa");
request.Headers.Add("X-Parse-REST-API-Key", "bb");
WebResponse response = request.GetResponse();
Stream responsestream = response.GetResponseStream();
StreamReader reader = new StreamReader(responsestream);
//IEnumerable<parseo
}
unfortunately i get 400 bad request.
what i want is to read all the json that exist there is my class that called "secondobject".
can anyone help me to figure this issue ?
Thank you.
When you created your object, you got back a full url containing an identifier for your particular instance of SecondObject in the Location header. You need to access that full url.
For example, when you posted your object, you got back the following headers
Status: 201 Created
Location: https://api.parse.com/1/classes/SecondObject/E234jdnsl
Moreover, you also received the following json in the body:
{
"createdAt": [timestamp],
"objectId": "E234jdnsl"
}
That E234jdnsl bit is the object identifier of your particular instance. You then need to point your WebRequest to the url https://api.parse.com/1/classes/SecondObject/E234jdnsl to retrieve it.
As mentioned in the comments, your code is 99% correct. The only problem is you're using a POST command to retrieve data when you should use a GET command instead.
Here's some slightly updated code using a GET command that should work for you. I added some code at the end to read the stream into a StringBuilder and display it in a textbox but you can change that to whatever you need.
private void Button4_Click(object sender, EventArgs e)
{
string URL = "https://api.parse.com/1/classes/SecondObject";
var request = WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("X-Parse-Application-Id", "YOUR_APP_ID");
request.Headers.Add("X-Parse-REST-API-Key", "YOUR_REST_API_KEY");
WebResponse response = request.GetResponse();
Stream responsestream = response.GetResponseStream();
StreamReader reader = new StreamReader(responsestream);
StringBuilder sbTempData = new StringBuilder();
while (reader.Peek() > -1)
{
sbTempData.AppendLine(reader.ReadLine());
}
txtResults.Text = sbTempData.ToString();
}
Note that this will retrieve every object in that class. If you only want to retrieve certain objects in the class, then you can modify your url like https://api.parse.com/1/classes/ClassName/ObjectID
For more information see https://parse.com/docs/rest/guide#queries
I have solve the problem
string URL = "https://api.parse.com/1/classes/SecondObject";
// string DATA = jsonString;
string text;
var request = WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("X-Parse-Application-Id", "aa");
request.Headers.Add("X-Parse-REST-API-Key", "bb");
WebResponse response = request.GetResponse();
Stream responsestream = response.GetResponseStream();
StreamReader reader = new StreamReader(responsestream);
string strResponse = null;
if (!reader.EndOfStream)
{
strResponse = reader.ReadToEnd();
}
Now the strResponse contains all the data that exist in the "SecondObject".
Thank you

How can i get the html of the page? [duplicate]

This question already has answers here:
How to get Url Hash (#) from server side
(6 answers)
Closed 9 years ago.
Here is the code I use to perform a web request. I'm getting all of the HTML except for the comments section in the URL.
HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(
"http://u-handbag.typepad.com/uhandblog/2013/11/choosing-bag-fabrics.html#comment-6a00d8341c574653ef019b022fc96f970d"
);
StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream());
htl = reader.ReadToEnd();
Can anyone explain why?
Use this chunk of code. Variable result should have the html code.
System.Net.WebClient webClient = new System.Net.WebClient();
string result = webClient.DownloadString(URL);
Getting HTML code from a website page. You can use code like this.
string urlAddress = "http://u-handbag.typepad.com/uhandblog/2013/11/choosing-bag-fabrics.html#comment-6a00d8341c574653ef019b022fc96f970d";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == null)
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
string data = readStream.ReadToEnd();
response.Close();
readStream.Close();
}
or better to use WebClient
using System.Net;
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString("http://u-handbag.typepad.com/uhandblog/2013/11/choosing-bag-fabrics.html#comment-6a00d8341c574653ef019b022fc96f970d");
}

Get webpage page content and HTTP status code in C#

In a C# Windows Forms application I can get the contents of a webpage using:
string content = webClient.DownloadString(url);
And I can get the HTTP header using:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
string response = ((HttpWebResponse)request.GetResponse()).StatusCode.ToString();
Is there a way to get both the contents and the HTTP status code (if it fails) in one trip to the server instead of twice?
Thanks.
You can read the data from the Stream inside the HttpWebResponse object:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
HttpStatusCode statusCode = ((HttpWebResponse)response).StatusCode;
string contents = reader.ReadToEnd();
}
In this way you will have to detect the encoding by hand, or using a library to detect encoding. You can read the encoding as a string from the HttpWebResponse object as well, when one exists, it is inside the ContentType property. If the page is Html, then you will have to parse it for a possible encoding change in the top of the document or inside the head.
Read handling the encoding from ContentType header
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
string content;
HttpStatusCode statusCode;
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
var contentType = response.ContentType;
Encoding encoding = null;
if (contentType != null)
{
var match = Regex.Match(contentType, #"(?<=charset\=).*");
if (match.Success)
encoding = Encoding.GetEncoding(match.ToString());
}
encoding = encoding ?? Encoding.UTF8;
statusCode = ((HttpWebResponse)response).StatusCode;
using (var reader = new StreamReader(stream, encoding))
content = reader.ReadToEnd();
}
WebClient
I assume you use WebClient because its easy webrequest-to-string handling. Unfortunately, WebClient does not expose the HTTP response code. You can either assume the response was positive (2xx) unless you get an exception and read it:
try
{
string content = webClient.DownloadString(url);
}
catch (WebException e)
{
HttpWebResponse response = (System.Net.HttpWebResponse)we.Response;
var statusCode = response.StatusCode;
}
Or if you're really interested in the success code you can use reflection as explained here.
HttpClient
You can also use HttpClient if you're on .NET 4.5, which does expose the response code, as explained here:
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
string content = await response.Content.ReadAsStringAsync();
var statusCode = response.StatusCode;
}
HttpWebRequest
Alternatively, you can just use HttpWebRequest to get the status and response as explained here:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
var response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
string content = reader.ReadToEnd();
var statusCode = response.StatusCode;
}
I think, you have not realised, that in the second case you have access to the content as well (although it takes a little more effort to get as a string).
Look at the Microsoft documentation: http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.getresponsestream(v=vs.110).aspx which shows you how to ge a response stream from the web response, and then how to get the string data from that stream.
And I can get the HTTP header using:
request.Method = "GET";
Method GET returns HEAD and BODY sections in response.
HTTP also support a method HEAD - which returns HEAD section only.
You can get BODY from HttpWebResponse using GetResponseStream method.

Trying to login to a website clicking a button

I've just started playing around with C# few weeks ago. i got a task i am trying to perform and not sure if the way i do it now is the right approach.
I am trying to login to a website(in my case WordPress website- for lake of better options) and navigating in admin panel using C#
So far what I've done was creating a new project - Windows Form Application.
The following code - send a request to the website with password/username and other parameters as POST
private void button2_Click(object sender, EventArgs e)
{
CookieContainer cookieJar = new CookieContainer();
CookieContainer cookieJar2 = new CookieContainer(); // will use this later
string testaa = ""; // will use this later
string paramaters = "log=xxxx&pwd=xxxx&testcookie=1&redirect_to=http://www.example.com/wp-admin/&wp-submit=Log In";
string strResponse;
HttpWebRequest requestLogin = (HttpWebRequest)WebRequest.Create("http://www.lyndatobin-howes.com/wp-login.php");
requestLogin.Method = "POST";
requestLogin.AllowAutoRedirect = false;
requestLogin.ContentType = "application/x-www-form-urlencoded";
requestLogin.CookieContainer = cookieJar;
requestLogin.ContentLength = paramaters.Length;
StreamWriter stOut = new StreamWriter(requestLogin.GetRequestStream(), Encoding.ASCII);
stOut.Write(paramaters);
stOut.Close();
}
I then have this code to to take the cookie of the response.
HttpWebResponse response = (HttpWebResponse)requestLogin.GetResponse();
foreach (Cookie c in response.Cookies)
{
cookieJar2.Add(new Cookie(c.Name, c.Value, c.Path, c.Domain));
}
then i have this to read the response + close some streams.
StreamReader stIn = new StreamReader(requestLogin.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
string responseFromServer = stIn.ReadToEnd();
webBrowser1.DocumentText = responseFromServer;
stIn.Close();
response.Close();
And then i try using the above cookie for the page i am trying to access as follows :
HttpWebRequest requestLogin2 = (HttpWebRequest)WebRequest.Create("http://www.example.com/wp-admin/");
requestLogin2.Method = "POST";
requestLogin2.AllowAutoRedirect = false;
requestLogin2.ContentType = "application/x-www-form-urlencoded";
requestLogin2.CookieContainer = cookieJar2;
requestLogin2.ContentLength = paramaters.Length;
StreamWriter stOut2 = new StreamWriter(requestLogin2.GetRequestStream(), System.Text.Encoding.ASCII);
stOut2.Write(paramaters);
stOut2.Close();
StreamReader stIn2 = new StreamReader(requestLogin2.GetResponse().GetResponseStream());
strResponse = stIn2.ReadToEnd();
string responseFromServer2 = stIn2.ReadToEnd();
webBrowser1.DocumentText = responseFromServer2;
richTextBox2.Text += "\n\n\n" + responseFromServer2;
stIn.Close();
Well it doesn't work for some reason I've been trying this for a week now.
I tried displaying the header - after the first request to see what headers i get back. and then looked at the cookie i built (cookieJar2) and it seem they aren't the same..
Anyways any help on the matter would be awesome and highly appreciated. i tried to give as much details as i could.
The first thing I notice about your code is that you call GetResponse() twice in your initial login:
HttpWebResponse response = (HttpWebResponse)requestLogin.GetResponse();
and
StreamReader stIn = new StreamReader(requestLogin.GetResponse().GetResponseStream());
As a result, you're making the login request twice and will be getting back two different cookies. This will be why the cookie in cookieJar2 doesn't match what you're outputting later. Reuse your response object:
StreamReader stIn = new StreamReader(response.GetResponseStream());
Next, when you try to load the admin page, don't POST to it. Your second request should be a GET to retrieve the content of the page.

Sending a string to a PHP page and having the PHP Page Display The String

What I'm trying to do is have my PHP page display a string that I've created through a function in my C# application, via System.Net.WebClient.
That's really it. In it' s simplest form, I have:
WebClient client = new WebClient();
string URL = "http://wwww.blah.com/page.php";
string TestData = "wooooo! test!!";
byte[] SendData = client.UploadString(URL, "POST", TestData);
So, I'm not even sure if that's the right way to do it.. and I'm not sure how to actually OBTAIN that string and display it on the PHP page. something like print_r(SendData) ??
ANY help would be greatly appreciated!
There are two halves to posting. 1) The code that posts to a page and 2) the page that receives it.
For 1)
Your C# looks ok. I personally would use:
string url = "http://wwww.blah.com/page.php";
string data = "wooooo! test!!";
using(WebClient client = new WebClient()) {
client.UploadString(url, data);
}
For 2)
In your PHP page:
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
$postData = file_get_contents('php://input');
print $postData;
}
Read about reading post data in PHP here:
http://us.php.net/manual/en/wrappers.php.php
http://php.net/manual/en/reserved.variables.httprawpostdata.php
Use This Codes To Send String From C# With Post Method
try
{
string url = "";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
string Data = "message="+str;
byte[] postBytes = Encoding.ASCII.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream resStream = response.GetResponseStream();
var sr = new StreamReader(response.GetResponseStream());
string responseText = sr.ReadToEnd();
}
catch (WebException)
{
MessageBox.Show("Please Check Your Internet Connection");
}
and php page
<?php
if (isset($_POST['message']))
{
$msg = $_POST['message'];
echo $msg;
}
?>

Categories