Using google's api to list result of search - c#

Hey i want to list the results from a google search, i saw that you can query google's api by using urls like this one
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Earth%Day
In the asp.net framework i have no idea how to query this url without exiting the page. I know Response.Redirect(myquery); would work but it makes the browser leave the current page, how do i get the JSON result from that query without leaving the page ?
Thanks !
ps: I did do alot of searches before asking.

Use the HttpWebRequest and HttpWebResponse classes in the .Net Framework:
var request = (HttpWebRequest)WebRequest.Create("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Earth%Day");
var response = (HttpWebResponse)request.GetResponse();
var responseText = (new StreamReader(response.GetResponseStream())).ReadToEnd();
http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

Related

Get a company followers count on LinkedIn

I'm trying to get the number of followers of a company on Linked in.
I use this code:
HttpWebRequest request = WebRequest.Create("http://api.linkedin.com/v1/companies/?id=SomeCompanyID:(num-followers)") as HttpWebRequest;
request.Method = "Get";
request.Credentials = new NetworkCredential("MyAppClientID", "MyAppClientSecret");
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) // I'm getting "(401) Unauthorized" exception at this line.
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string result = reader.ReadToEnd();
System.IO.File.WriteAllText(#"WriteText.txt", result);
Console.WriteLine(reader.ReadToEnd());
}
I'm not sure about my syntax and the way I provide credentials, but I don't know how to do so correctly, and documentation is not clear at this point.
Your help is appreciated.
It looks like you haven't registered your application or more accurately you haven't updated the code sample with your own ClientKey and Secret value.
You obtain them from https://www.linkedin.com/developer/apps/
You can also find more information about it here https://developer.linkedin.com/support/faq
Where can I find my API key?
Click on the My Apps link in the top navigation menu to manage your
LinkedIn applications.
From here, you can create a new application if you don't already have
one or view the details of your existing applications. You will find
your Client ID (otherwise known as API Key/ID or Consumer Key/ID)
listed in the "Authentication" side nav link, underneath the header
"Authentication Keys".
Alternatively, you may be using an old format of Rest API call, accoring to this page (https://developer.linkedin.com/docs/company-pages), the new format is as follows
https://api.linkedin.com/v1/companies/{id}/num-followers?format=json
Get a company's followers, by segment
If you choose to target content that you share on behalf of a company,
there is a minumum number of followers that must make up the segment
you are targeting before you will be able to successfully share the
targeted content. This request allows you to get a follower-count for
a specific segment to ensure you are at or over the minimum
requirement for the target segment for the company specified by the
{id} value in the request. Optional Parameters
https://api.linkedin.com/v1/companies/{id}/num-followers?format=json
sample response
1147037

Issues retrieving facebook social plugin comments for page, C# HttpWebRequest class

I'm hoping I've done something knuckle-headed here and there is an easy answer. I'm simply trying to retrieve the list of comments for a page on my site. I use the social plug-in and then retrieve the comment id via the edge event. Server side I send the page id back and do a simple request using a HttpWebRequest. Worked well back in October, but now I get an 'internal error' response from FB. I can use the same url string put it into a browser and get the comments back in the browser in json.
StringBuilder url = new StringBuilder();
url.Append("https://graph.facebook.com/comments/?ids=" + comment.page);
string requestString = url.ToString();
HttpWebRequest request = WebRequest.Create(requestString) as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Ideas? Thanks much in advance.
Since you're using the Facebook C# SDK (per your tag), try:
var url = "{your url}";
var api = new Facebook.FacebookClient(appId,appSec);
dynamic commentsObj = api.Get("/comments/?ids=" + url);
dynamic arrayOfComments = commentsObj[url].data

How to read returned xml value from google maps

I am trying to call google maps geocode and am following the example on their webpage to try and apply it to mine
http://code.google.com/apis/maps/documentation/geocoding/index.html
in this example, the Geocoding API requests an xml response for the
identical query shown above for "1600 Amphitheatre Parkway, Mountain
View, CA":
http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false
The XML returned by this request is shown below.
Now i am trying to run that url like this in my c# winforms application
string url = "http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false";
WebRequest req = HttpWebRequest.Create(url);
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
try
{
Match coord = Regex.Match(sr.ReadToEnd(), "<coordinates>.*</coordinates>");
var b = coord.Value.Substring(13, coord.Length - 27);
}
finally
{
sr.Close();
}
However it doesnt seem to be returning anything and as such my var b line gives an index out of bounds error. Can anyone point me in the right direction for at least getting the example to work so i can apply the logic to my own application?
Thanks
If you visit your link "http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false" directly in a browser you can see what it's returning. It's giving me a REQUEST DENIED error.
The problem is caused by the sensor=true_or_false parameter. You have to choose if you want it to be true or false. Google put it this way in their example so that you have to explicitly decide for yourself. This setting indicates if your application is using a location sensor or not. In your case, I'm guessing not, so set it to false.
If you change the link you're using to http://maps.googleapis.com/maps/api/geocode/xml?address=1600%20Amphitheatre%20Parkway,%20Mountain%20View,%20CA&sensor=false, I think you'll get the results you were expecting.

C# HTTP programming

i want to build a piece of software that will process some html forms, the software will be a kind of bot that will process some forms on my website automatically.
Is there anyone who can give me some basic steps how to do this job...Any tutorials, samples, books or whatever can help me.
Can some of you post an working code with POST method ?
Check out How to: Send Data Using the WebRequest Class. It gives an example of how create a page that posts to another page using the HttpWebRequest class.
To fill out the form...
Find all of the INPUT or TEXTAREA elements that you want to fill out.
Build the data string that you are going to send back to the server. The string is formatted like "name1=value1&name2=value2" (just like in the querystring). Each value will need to be URL encoded.
If the form's "method" attribute is "GET", then take the URL in the "action" attribute, add a "?" and the data string, then make a "GET" web request to the URL.
If the form's "method" is "POST", then the data is submitted in a different area of the web request. Take a look at this page for the C# code.
To expand on David and JP's answers':
Assuming you're working with forms whose contents you're not familiar with, you can probably...
pull the page with the form via an HttpWebRequest.
load it into an XmlDocument
Use XPath to traverse/select the form elements.
Build your query string/post data based on the elements.
Send the data with HttWebRequest
If the form's structure is known in advance, you can really just start at #4.
(untested) example (my XPath is not great so the syntax is almost certainly not quite right):
HttpWebRequest request;
HttpWebResponse response;
XmlDocument xml = new XmlDocument();
string form_url = "http://...."; // you supply this
string form_submit_url;
XmlNodeList element_nodes;
XmlElement form_element;
StringBuilder query_string = new StringBuilder();
// #1
request = (HttpWebRequest)WebRequest.Create(form_url));
response = (HttpWebResponse)request.GetResponse();
// #2
xml.Load(response.GetResponseStream());
// #3a
form_element = xml.selectSingleNode("form[#name='formname']");
form_submit_url = form_element.GetAttribute("action");
// #3b
element_nodes = form_element.SelectNodes("input,select,textarea", nsmgr)
// #4
foreach (XmlNode input_element in element_nodes) {
if (query_string.length > 0) { query_string.Append("&"); }
// MyFormElementValue() is a function/value you need to provide/define.
query_string.Append(input_element.GetAttribute("name") + "=" + MyFormElementValue(input_element.GetAttribute("name"));
}
// #5
// This is a GET request, you can figure out POST as needed, and deduce the submission type via the <form> element's attribute.
request = (HttpWebRequest)WebRequest.Create(form_submit_url + "?" + query_string.ToString()));
References:
Link
http://www.developerfusion.com/forum/thread/26371/
http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.getattribute.aspx
http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.selectnodes.aspx
If you don't want to go the HttpWebRequest route, I would suggest WatiN. Makes it very easy to automate IE or Firefox and not worry about the internals of the HTTP requests.

Determine Final Destination of a Shortened URL

I'm trying to find the best way (in code) to determine the final destination of a shortened URL. For instance http://tinyurl.com redirects to an eBay auction. I'm trying to get the URL for the eBay auction. I'm trying to do this from within .NET so I can compare multiple URLs to ensure that there is no duplicates.
TIA
While I spent a minute writing the code to ensure that it worked the answer was already delivered, but I post the code anyway:
private static string GetRealUrl(string url)
{
WebRequest request = WebRequest.Create(url);
request.Method = WebRequestMethods.Http.Head;
WebResponse response = request.GetResponse();
return response.ResponseUri.ToString();
}
This will work as long as the short url service does a regular redirect.
You should issue a HEAD request to the url using a HttpWebRequest instance. In the returned HttpWebResponse, check the ResponseUri.
Just make sure the AllowAutoRedirect is set to true on the HttpWebRequest instance (it is true by default).
One way would be to read the URL and get the result code from it. If it's a 301 (permanent redirect) then follow where it's taking you. Continue to do this until you reach a 200 (OK). When using tinyurl it could happen that you will go through several 301 until you reach a 200.
Assuming you don't want to actually follow the link, for TinyURL you can append /info to the end of the url:
http://tinyurl.com/unicycles/info
and it gives you a page showing where that tinyurl links to, which I assume would be easy to parse using xpath or similar.
Most other URL shortening services have similar features, but they all work differently.

Categories