Requests POI from a location using Xamarin (Android) - c#

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...

Related

Webbrowser control not displaying web pages correctly

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;
}
}

how to get Google plus access token in windows application C#.net

I am preparing a windows application in that I want to use oAuth2 to access info from google plus.
But I am getting bad request for my following code.. I am able to create app in google console and fetch the "code" for application access.
WebRequest request = WebRequest.Create(
GoogleAuthenticationServer.Description.TokenEndpoint
);
// You must use POST for the code exchange.
request.Method = "POST";
// Create POST data.
string postData = FormPostData(code);
byte[] byteArray = Encoding.UTF8.`enter code here`GetBytes(postData);
// Set up the POST request for the code exchange.
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
// Perform the POST and retrieve the server response with
// the access token and/or the refresh token.
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
// Convert the response JSON to an object and return it.
return JsonConvert.DeserializeObject<OAuthResponseObject>(
responseFromServer);
Now, I am trying to use that code to get the access token. .which is giving me BAD request.
I also followed few post on stackoverflow. but none of them working for me.
Thanks
EDIT:
Thanks for the reply. I was able to do it my own somehow :)
i think you can begin this way :
Google plus OAuth
For web applications, I would strongly recommend you use a one-time-code flow as demonstrated in the Google+ Quickstart sample. Please try working through the Quickstart instructions to make sure you're not missing any steps. When you do Google+ Sign-In this way, you will be able to get over-the-air installs of Android apps (if you have one for your site) and will be applying best practices for authorization.
All of the code for doing this is available in the sample which also demonstrates integration with the Google client libraries - this opens up access to all of the Google APIs and product integrations.
From Windows apps or installed apps, you would need to do more of the heavy lifting yourself. The following blog article covers how you could do the authorization in legacy scenarios:
http://gusclass.com/blog/2012/08/31/using-the-google-net-client-library-with-google/
There is an example as well:
http://gusclass.com/projects/PlusDotNet.zip
A couple notes:
When you create your client ID, make sure it's for an installed application.
The authorization code is taken from the window title after the user authorizes; this is a little dodgy and you should be doing this in a window you host in your app.
Performing authorization this way will not allow you to have over-the-air installs to Android. For doing this, you could possibly host a webview inside of the application and use that for a one-time-code flow but I have never seen this working from Windows.
I was able to do it my own using following code..
private void button2_Click(object sender, EventArgs e)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
authLink.AppendFormat("code={0}", code);
authLink.AppendFormat("&client_id={0}", "996688211762.apps.googleusercontent.com");
authLink.AppendFormat("&client_secret={0}", "nprfJuBUOyU2hsb3tqt1XDnB");
authLink.AppendFormat("&redirect_uri={0}", "urn:ietf:wg:oauth:2.0:oob");
authLink.Append("&grant_type=authorization_code");
UTF8Encoding utfenc = new UTF8Encoding();
byte[] bytes = utfenc.GetBytes(authLink.ToString());
Stream os = null;
try // send the post
{
webRequest.ContentLength = bytes.Length; // Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); // Send it
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
try // get the response
{
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse == null) { MessageBox.Show("null"); }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
textBox1.Text = sr.ReadToEnd().Trim();
//MessageBox.Show(sr.ReadToEnd().Trim());
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
private void button1_Click(object sender, EventArgs e)
{
StringBuilder authLink = new StringBuilder();
authLink.Append("https://accounts.google.com/o/oauth2/auth");
authLink.AppendFormat("?scope={0}", "https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile");
authLink.AppendFormat("&client_id={0}", "xxxxxx.apps.googleusercontent.com");
authLink.AppendFormat("&redirect_uri={0}", "urn:ietf:wg:oauth:2.0:oob");
authLink.Append("&response_type=code");
string u = #"https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=code&client_id=xxxxxxxx.apps.googleusercontent.com";
webBrowser1.Navigate(u);
}
I am assuming to have two button on window.. button1 is used to get CODE from google and button2 uses that code and get the access_token which is what I was looking for.

Check URL exists using c#

i have been trying to find out either provide URL is available or not. Available doesnt mean domain availability i mean either URL is accessible or its not accessible
i have tested code
var webrequest = (HttpWebRequest)WebRequest.Create(
"http://localhost:64519/TestPage.aspx");
webrequest.Method = "HEAD";
HttpWebResponse response = webrequest.GetResponse() as HttpWebResponse;
and there is some code on pageload of Testpage
protected void Page_Load(object sender, EventArgs e)
{
StreamReader stream = new StreamReader(Request.InputStream);
XDocument xmlInput = XDocument.Load(stream);
}
now issue is even i added HEAD in request yet it goes in to PageLoad and throws exception.
Scenario:
i have been trying to send XML to provided URL. in XML case its working fine but when i try to check that either Link is live or not it throws exception because XDocument.Load(stream); dont have XML\
surely i can solve the issue by using
if (stream.BaseStream.Length != 0)
{
XDocument xmlInput = XDocument.Load(stream);
}
but its not appropriate. i just want to know the link is live or not based on my research is just Add headers but even with adding headers my problem is yet there
so please some one can help me out with this or any kind of help will be appreciated
You could use the HttpWebRequest and HttpWebResponse classes and set the request's Method to "HEAD".
List of other possible Methods.
var request = (HttpWebRequest)WebRequest.Create("http://localhost:64519/TestPage.aspx");
request.Method = "HEAD";
var response = (HttpWebResponse)request.GetResponse();
var success = response.StatusCode == HttpStatusCode.OK;
I've made a function on the fly. Hope that it works for you :)
public bool isValid(string url) {
Stream sStream;
HttpWebRequest urlReq;
HttpWebResponse urlRes;
try {
urlReq = (HttpWebRequest) WebRequest.Create(url);
urlRes = (HttpWebResponse) urlReq.GetResponse();
sStream = urlRes.GetResponseStream();
string read = new StreamReader(sStream).ReadToEnd();
return true;
} catch (Exception ex) {
//Url not valid
return false;
}
}
Use the GET method
If the Website Respond your Query then Get the Response Data...
If there is no such URL then it throws the WebException Error...
Yoiu Can catch that and do something on that...
Here i list my idea. I think it solve ur problem
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://localhost:64519/TestPage.aspx");
webRequest.Method = "GET";
string responseData = string.Empty;
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
}
catch (System.Net.WebException ex)
{
//Code - If does not Exist
}

Calling Webservices in WP7

I am working on Windows Phone 7 platform and want to call the webservices for login, and other details.
But i am not getting the way to call the webserives. Can you please help me about how to call webservice in WP7.
Currently i m using this
public string GetXmlResponse(string Url)
{
try
{
wr = WebRequest.Create(Url);
hwr = (HttpWebRequest)wr;
hwr.Method = "GET";
hwr.ContentType = "text/xml";
//hwr.Timeout = 2147483647;
//hwr.ContentLength = URL.Length;
IAsyncResult ar = null;
ar = (IAsyncResult)hwr.BeginGetResponse(AsyncResponse, hwr);
}
catch
{
resp = null;
}
return resp;
}
public void AsyncResponse(IAsyncResult ar)
{
try
{
WebResponse ws = hwr.EndGetResponse(ar);
StreamReader streader = new StreamReader(ws.GetResponseStream());
resp = streader.ReadToEnd();
}
catch
{
resp = null;
}
}
But as it makes AsyncResponse, it returns me the null value, while calling the function GetXmlResponse.
Please help me for any thing.
Thanks
have you checked out the XNA site? http://create.msdn.com/en-US/
There is a link that goes to channel 9's Windows phone 7 development tutorials. One of the lessons that is on the second day I believe has a really good video of how to use web services.
By creating the delegate i have handled this.
In AsyncResponse i fire the delegate and on my form that fires the event for me.
This is how i am able to manage this.
i refered this link to create the delegate.
Thanks
BHAVIK GOYAL
Try using HttpWebRequest.Create
wr = HttpWebRequest.Create(Url);
Also if the 'Method' is "GET", ContentType is not required.

JSON Data posted by Silverlight is not reaching the server

I have a web client I'm creating in Silverlight. I am trying to get it to communicate it with my web services on my server through GET and POST requests and JSON. The GET requests work fine and I'm able to parse the JSON on the Silverlight end. The POST requests however dont seem to work. The server reads that there is a POST request, but the POST array is empty.
Ive tried two pieces of code to send the POST requests, but both are resulting in the same response - an empty array.
The first Silverlight code I tried was:
public MainPage()
{
InitializeComponent();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri("http://www.dipzo.com/game/services.php"));
request.Method = "POST";
request.ContentType = "application/json";
request.BeginGetRequestStream(new AsyncCallback(OnGetRequestStreamCompleted), request);
}
private void OnGetRequestStreamCompleted(IAsyncResult ar)
{
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
using (StreamWriter writer = new StreamWriter(request.EndGetRequestStream(ar)))
{
writer.Write("name=david");
}
request.BeginGetResponse(new AsyncCallback(OnGetResponseCompleted), request);
}
private void OnGetResponseCompleted(IAsyncResult ar)
{
//this.GetResponseCoimpleted.Visibility = Visibility.Visible;
// Complete the Flickr request and marshal to the UI thread
using (HttpWebResponse response = (HttpWebResponse)((HttpWebRequest)ar.AsyncState).EndGetResponse(ar))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string results = reader.ReadToEnd();
}
}
}
The second piece I tried was:
private void WebClient_Click(object sender, RoutedEventArgs e)
{
Test t1 = new Test() { Name = "Civics", Marks = 100 };
DataContractJsonSerializer jsondata = new DataContractJsonSerializer(typeof(Test));
MemoryStream mem = new MemoryStream();
jsondata.WriteObject(mem, t1);
string josnserdata = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient cnt = new WebClient();
cnt.UploadStringCompleted += new UploadStringCompletedEventHandler(cnt_UploadStringCompleted);
cnt.Headers["Content-type"] = "application/json";
cnt.Encoding = Encoding.UTF8;
cnt.UploadStringAsync(new Uri("http://www.dipzo.com/game/services.php"), "POST", josnserdata);
}
void cnt_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
var x = e;
}
The code on the server to consume the service is in PHP and is essentially:
var_dump($_POST)
This should output whatever is coming into the post array. I've tested it with a simple PHP client and it works. Just can't get it to work in silverlight. In silverlight I just keep getting an empty array.
You should change the Content-type to application/x-www-form-urlencoded and not application/json which is not a known type yet.
Not that I think anyone is still paying attention tot his old question, but I'm betting that the problem was that it actually WAS getting to the server, but that the server routed the result back to the SL application. This is the behavior I'm seeing with a similar situation from SL5 usingWebClient.UploadStringAsync.
I'm about to implement/test a technique I ran across yesterday which uses a dynamically built, "real" page post from SL; I'll report my findings shortly.
UPDATE -- THIS SOLUTION WORKS:
http://www.codeproject.com/Tips/392435/Using-HTTP-Form-POST-method-to-pass-parameters-fro
I've just tested it in my application (SL5 inside MVC) and it works just fine. Make sure you check the HttpContext.Request.Form["fieldname"] to get the value(s) that you want. I used this technique to submit JSON and was able to return a generated Word document for the user.
Once I implemented this I was able to get rid of the unnecessary WebClient that I was attempting to use before.

Categories

Resources