What is google's character encoding? - asp.net

Apparently Google's encoding is UTF-8 as it's stated in it's html meta tag.
But when I open a search page for scharfes+s with ASP WebRequest.GetResponse(), it's full of unrecognized characters. Does someone know what's going on there?
For your convenience, code is pasted below
Asp Page
<form id="form1" runat="server">
<div>
<div runat="server" id="output"/>
</div>
</form>
Codebehind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Text;
public partial class SearchEngineCaller : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpWebRequest queryPage = (HttpWebRequest)WebRequest.Create("https://www.google.com/search?q=scharfes+s");
queryPage.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)queryPage.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
output.InnerHtml = readStream.ReadToEnd();
}
}
What encoding should I use?

You have to set some HTTP headers for the HttpWebRequest object:
HttpWebRequest queryPage = (HttpWebRequest)WebRequest.Create("https://www.google.com/search?q=scharfes+s");
queryPage.Credentials = CredentialCache.DefaultCredentials;
queryPage.Accept = "text/html";
queryPage.Headers["Accept-Charset"] = "utf-8";
queryPage.UserAgent = "Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20100101 Firefox/21.0";
IMPORTANT: Setting the Accept-Charset is not enough, it's important to set the User-Agent, too (I copied the above user agent string from here). I tried this solution, and it works for me (test code).

Related

How i fix this error? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have error in
plz help to convert json to rcpts.
string json = JsonConvert.SerializeObject(rcpts);
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace sdd.Contact
{
public partial class Cantact : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SabtButton_Click(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create("http://ippanel.com/services.jspd");
string[] rcpts = new string[] { "981111111" };
string json = JsonConvert.SerializeObject(rcpts);
request.Method = "POST";
string postData = "op=send&uname=aaaa&pass=0000&message=hello Test&to=" + json + "&from=+9810001010";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
System.Diagnostics.Debug.WriteLine(responseFromServer);
}
}
}
You can try Parse or DeserializeObject for this:
JObject json = JObject.Parse(rcpts);
Or
dynamic json = JsonConvert.DeserializeObject(rcpts);

How to get data from API on POST method

I have to accesss an get some data from one of API.This API has only mentoned this method.No documentation showing how to acess and all.Data will be returned as Json.
This is the product API
1. GetAllProducts
POST
http://api.domain.com/api/Products/All
Content-Type: application/json; charset=utf-8
{"Token":"EncryptedToken"}
I have generated the Token and I tried to access it like this.But nothing is recieving.I found an example and tried to do like this.May be this is wrong.Can any one show me how to access and get the data.Please see my code below and thanks in advanced.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Web.Script;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Text;
public partial class Products : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All?Token=U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_");
request.Method = "POST";
string postData = "Data to post here";
byte[] post = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = post.Length;
Stream reqdataStream = request.GetRequestStream();
reqdataStream.Write(post, 0, post.Length);
reqdataStream.Close();
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (Exception ex)
{
Response.Write("Error Occured.");
}
}
}
I think you should change these things:
content type
request.ContentType = "application/json";
the post data
string postData = "{\"Token\":\"U5Y1oPjI4DqwZgZkp-pVSmbIpP9XuXquKGYuREGwSNDX5OUhHAQVzI3exVOVzDD3|qlFREqiRHuKDG3gN5Zk05M5YjtWOhD8A11oxT7wolQ0gSLyKzXxNHgj94idAm4Wy6|CVnC2pguIbugAfqxSSJvf1KE_\"}";
the URI
WebRequest request = WebRequest.Create("http://api.domain.com/api/Products/All");

How to add connection string dynamically in web.config

I have to create one application which will add connection string in web.config when user clicks on some control.
actually it runs fine,
But now together with it i have to run one SQL script which will create new database.
for that i have write following code..
now it gives me error as
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Web.Configuration;
using System.Collections.Generic;
public partial class connectionString : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnadd_Click(object sender, EventArgs e)
{
try
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
// System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
var section = config.GetSection("connectionStrings") as ConnectionStringsSection;
section.ConnectionStrings.Add(new ConnectionStringSettings(txtNAme.Text, txtNAme.Text, "System.Data.SqlClient"));
config.Save();
string sqlConnectionString = #"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ccwebgrity;Data Source=SURAJIT\SQLEXPRESS";
FileInfo file = new FileInfo(#"G:\AAA\SCRIPT.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
file.OpenText().Close();
}
catch (Exception ex)
{
}
}
}
Define the connection string in web.config
<ConnectionStrings>
<add name="student" connectionString="Server=student;Max Pool Size=300;Initial Catalog=studentDB;User ID=student;Password=st123dent;" providerName="System.Data.SqlClient"/>
</Connectionstrings>
Configuration is read only so you can not do it in obvious way like
ConfigurationManager.ConnectionStrings["student"].ConnectionString = "new value";

using functions in code behind on webpage

Disclaimer: I'm pretty new to ASP.NET, so I'm figuring it out as I go along.
I'm trying to output the results of a function in my code behind page on the webpage itself.
Example:
Code Behind:
public string POSTResult(string e) { ... return TheResult; }
ASPX Page:
Output is: <%=POSTResult("argument")%>
However, loading the page errors, saying "The name 'POSTResult' does not exist in the current context."
I'm apparently doing something a bit off with how I'm getting to the code behind page from the ASPX page. My ASPX page has this at the top:
<%# Page Title="" Language="C#" MasterPageFile="~/master/default.Master" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="Bitfork.login" %>
The listed CodeBehind value is the name of the code behind page.
ETA:
Contents of my code behind (login.aspx.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
namespace Bitfork.master
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string POSTResult(string e)
{
// variables to store parameter values
string url = "https://accounts.google.com/o/oauth2/token";
// creates the post data for the POST request
string postData = (e);
// create the POST request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postData.Length;
// POST the data
using (StreamWriter requestWriter2 = new StreamWriter(webRequest.GetRequestStream()))
{
requestWriter2.Write(postData);
}
// This actually does the request and gets the response back
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
string responseData = string.Empty;
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
// dumps the HTML from the response into a string variable
responseData = responseReader.ReadToEnd();
}
return responseData;
}
}
}
Example of argument being passed, with API secret keys redacted:
code=[redacted]&client_id=[redacted]&client_secret=[redacted]&redirect_uri=http://localhost:60284/login.aspx&grant_type=authorization_code
ETA2:
I don't know if it's related, but it seems like my code behind page and my webpage are not communicating with each other at all. For instance, I can't access DIVs by ID in my code behind page to change their contents.

How to get label's text by HTTP handler (.ashx) in repeater control

I have a label within a <table> in a repeater. I have an HttpHandler named "NameShow.ashx" to return the "name" as "text/plain" by passing an "id" to the handler.
I want to retrieve the "name" (similar to retrieving "image" from handler).
Here is my code:
<asp:Label ID="Label1" runat="server" Text='<%#""NameShow.ashx?id="+Eval("id") %>'>
</asp:Label>
I am getting the text of this label as ->> NameShow.ashx?id=123
Please help in finding where I am doing mistake.
Here is my Haldler code.
using System;
using System.Web;
public class NameShow : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
string strid = context.Request.QueryString["id"];
long pro_id = int.Parse(strid);
string name = DBHelpername.name(pro_id);
context.Response.ContentType = "text/plain";
context.Response.Write(name);
}
public bool IsReusable {
get {
return false;
}
}
}
Here is my DBHelper code:
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
/// <summary>
/// Summary description for DBHelpername
/// </summary>
public class DBHelpername
{
public DBHelpername()
{
//
// TODO: Add constructor logic here
//
}
public static string name(long id)
{
SqlConnection connect = new SqlConnection
("Data Source=DELL-36B3EF6E9F;Integrated Security=True;Initial Catalog=pool");
connect.Open();
SqlCommand sc =
new SqlCommand("SELECT name FROM Profile WHERE profile_id=" + id + "", connect);
SqlDataAdapter da = new SqlDataAdapter(sc);
DataSet ds = new DataSet();
da.Fill(ds);
string nameret = ds.Tables[0].Rows[0][0].ToString();
return nameret;
connect.Close();
}
}
If you are not married to the idea of using an HTTP Handler, then I suggest making a method in your .aspx page's code-behind that does the same logic your handler is doing minus the content-type stuff, like this:
protected string GetName(int pro_id)
{
return DBHelpername.name(pro_id);
}
Now in your markup you can use this method, like this:
<asp:Label ID="Label1" runat="server" Text='<%# GetName((int)Eval("id")) %>'>
</asp:Label>
<%# new System.Net.WebClient().DownloadString("http://www.yoursite.com/NameShow.ashx?id="+Eval("id"))) %>
Something like this may work, although you might need to re-think your approach as you are going do a http request for each item in your repeater - and that isn't going to scale well! It looks like this is all in one application/website, so can you not call the code that looks up the name in the codebehind of this page?

Resources