Invoke Google Maps API V3 Javascript API from Windows Forms app? - c#

Google has this fine new Google Maps API v3 which is a "Javascript API".
Is there any possibility to invoke this API from a Windows Forms application written in Visual C# .net 3.5?
EDIT:
The goal is to convert addresses to lat/long format using the Google Maps Geocoder.
EDIT 2:
I'd like to use v3 of the API as it doesn't require an API key anymore. API keys should be bound to a webserver which can't be the case for a Windows Forms app.

Edit: Looks like the api key is no longer required.
You can use the REST APIs and parse the response (XML/JSON/CSV).
http://maps.google.com/maps/geo?q=State+St,+Troy,+NY&output=csv&oe=utf8&sensor=false
Would output:
200,6,42.730070,-73.690570
Which is:
200 - G_GEO_SUCCESS
6 - Street level accuracy
42.730070 - Latitude
-73.690570 - Longitude
If you are not familiar with the System.Net APIs, they would go something like this:
const string GeoCodeUrlFormat = "http://maps.google.com/maps/geo?q={0}&output=csv&oe=utf8&sensor=false";
string location = "State St, Troy, NY";
string url = String.Format(GeoCodeUrlFormat, HttpUtility.UrlEncode(location));
HttpRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpResponse response = (HttpResponse)request.GetResponse(); // Can throw an exception
Stream responseStream = response.GetResponseStream();
using (StreamReader reader = new StreamReader(responseStream)
{
string firstLine = reader.ReadLine();
string[] lineParts = firstLine.Split();
GeolocationResult result = GoogleMapper.MapGeolocationResult(lineParts);
// TADA
}
Obviously there's no error handling, it doesn't support multiple return values and I haven't actually implemented MapGeolocationResult, but it should give you a start.

You could host the WebBrowser control on your form and use that to interact with the Google Maps API.
But some more information about what you are really trying to do would be nice.

Related

SnipCart API Authorization returns 401 Unauthorized

I want to use the V3 SnipCart API to get data about specific orders on my thank you page. I am using C# to do this. I keep getting this error when trying to use the API
System.Net.WebException:'The remote server returned an error: (401)
Unauthorized.'
I have tried to follow their documentation by using only the API key with no password as shown here. Below is my code that I wrote that is giving me the error. I wrote this inside my controller. I get the error as soon as the breakpoint hits this line responseObjGet = (HttpWebResponse)requestObjGet.GetResponse();
//Testing API get data begin
string strurltest = String.Format("https://app.snipcart.com/api/orders/c5541254-r8541-8501-0024-juy85vv002154");
WebRequest requestObjGet = WebRequest.Create(strurltest);
requestObjGet.Credentials = new NetworkCredential("HihiukoJOUBVCTYIiijiGiiYTd6tOiUyTYo", "");
requestObjGet.Method = "GET";
HttpWebResponse responseObjGet = null;
responseObjGet = (HttpWebResponse)requestObjGet.GetResponse(); //401 is triggered here
string strresulttest = null;
using (Stream stream = responseObjGet.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresulttest = sr.ReadToEnd();
sr.Close();
}
Concerns that I have as well are the following:
1.The API key that I entered here is my public api key since I am still in the development and testing phase. I am not sure if this api call will work with the test api key or if I have to use the real secret production key. Any thoughts?
2.I am debugging this off my local machine (localhost:) for now before I deploy these API calls to production to test these changes in prod still with the test api key, could that be a reason for the 401? Since the URL that is trying to get the info is my localhost: url and not my actual domain that I added to SnipCart Dashboard. I was thinking maybe I have to try and hit this from prod environment instead? Any thought?
These are the 2 possibilities that come to mind for me. I am not too savvy on APi's yet so I don't know if my call is missing something.
Summary: All I am trying to do is be able to use the API so that I can load the data I want for an order when users reach my custom thank you page with their token.
Our 401 "Unauthorized" status code is returned when the authentication failed to our API with your Authorization header's value.
Here's the documentation about the auth to our APIs. Make sure to return us a base64 value of your secret API key and the trailing single colon character at the end to respect the Basic Authentication Scheme.
And if you are trying to get data for an order that was placed in live mode then you would need to use the live secret API key.

Choosing between accessing WCF via API Endpoint or via Dll reference

I have been contemplating on a dilemma for hours. I have a Visual Studio Solution that contains a WCF, WebForms, UWP, Xamarin and a SharedLibrary Projects.
I intend to use the WCF project as the backend which talks to the database and process Email and SMS integration and feed the other apps.
OPTION A
Currently, The WCF is hosted on an Azure App Service which makes it accessible via POST, GET, etc from the url which is: https://mywcfprojectlink.azurewebsites.net/service1.svc/GetUsers
With such arrangements, I can perform a POST request to get data from the apps:
string response = string.Empty;
string url = "https://mywcfprojectlink.azurewebsites.net/service1.svc/GetUsers";
try
{
var values = new Dictionary<string, string>
{
{ "data", Encryption.EncryptString(dat.ToString()) } //dat is incoming method param
};
string jsonString = JsonConvert.SerializeObject(values);
var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
response = cli.UploadString($"{url}", jsonString);
var result = JsonConvert.DeserializeObject<string>(response);
topic.InnerText = Encryption.DecryptString(result.ToString());
}
catch (Exception)
{
return string.Empty;
}
The method above is a simple one as I have other ones where I Deserialize with Models/Classes.
OPTION B
I equally have access to the methods defined in service1 by adding the project reference to my WebForms which surprisingly is also compatible with xamarin but not with UWP. Nevertheless, I am interested in the WebForms scenario. Below is an example method:
using BackEnd;
//Service1 service1 = new Service1();
//var send = service1.GetUsers(dat.ToString()); //dat is incoming method param
//topic.InnerText = send;
Obviously, using the Option B would eliminate the need to encrypt, decrypt, serialize or deserialize the data being sent. However, I have serious performance concerns.
I need to know the better option and if there is yet another alternative (probably an Azure Resource), you can share with me.
If you decide to use https endpoint of the Azure website, option A is secure because of SSL encryption. So you don't have to encrypt/decrypt it by yourself. The only tip is to create a proper authorization mechanism. For example use TransportWithMessageCredential. An example is provided in below article https://www.codeproject.com/Articles/1092557/WCF-Security-and-Authentication-in-Azure-WsHttpBin

Google PageSpeed API dotnet .net

I have set up a basic C# application to run a PageSpeed test on a website that I specify using the Google.Apis.Pagespeedonline.v2 nuget package.
The set up is simple enough and I have a variable that I can specify the url which is then past in to the Service
// Create the service.
var service = new PagespeedonlineService(new BaseClientService.Initializer
{
ApplicationName = "PageSpeed Sample",
ApiKey = "[API_KEY_HERE]"
});
var url = "URL_TO_TEST";
// Run the request.
var result = await service.Pagespeedapi.Runpagespeed(url).ExecuteAsync();
The problem being the .Runpagespeed method ONLY accepts URL. I need to be able to specify, at minimum, the 'Mobile' strategy so I can obtain scores for both Desktop and Mobile. I know this is possible in other libraries but seems to be missing in .NET. Is anybody aware of a way to do this using the .NET library? In the reference documentation it implies that the method accepts further optional parameters but it does not in the code.
Pagespeedapi: runpagespeed has an optional value called strategy
strategy string The analysis strategy to use
Acceptable values are: "desktop": Fetch and analyze the URL for
desktop browsers "mobile": Fetch and analyze the URL for mobile
devices
Example:
var request = service.Pagespeedapi.Runpagespeed(url);
request.Strategy = Google.Apis.Pagespeedonline.v2.PagespeedapiResource.RunpagespeedRequest.StrategyEnum.Mobile;
var results = request.Execute();

Facebook Retrive Data using Graph API using c#

i have created desktop Facebook application using c# .net. i want to retrieve users message,post and chat history. which is convenient way to retrieve users all information.i have started with Facebook Graph API but i am not getting any example.
can any one help me ?
A bit late to the party but anyway:
Add a reference to System.Net.Http and Newtonsoft.Json
string userToken = "theusertokentogiveyoumagicalpowers";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://graph.facebook.com");
HttpResponseMessage response = client.GetAsync($"me?fields=name,email&access_token={userToken}").Result;
response.EnsureSuccessStatusCode();
string result = response.Content.ReadAsStringAsync().Result;
var jsonRes = JsonConvert.DeserializeObject<dynamic>(result);
var email = jsonRes["email"].ToString();
}
Go to developer.facebook.com -> Tools & Support -> Select Graph API Explorer
Here U get FQL Query, Access Token
Then write code in C#.....
var client = new FacebookClient();
client.AccessToken = Your Access Token;
//show user's profile picture
dynamic me = client.Get("me?fields=picture");
pictureBoxProfile.Load(me.picture.data.url);
//show user's birthday
me = client.Get("me/?fields=birthday");
labelBirthday.Text = Convert.ToString(me.birthday);
http://www.codeproject.com/Articles/380635/Csharp-Application-Integration-with-Facebook-Twitt
I hope this will help you.!!!
you can check the Graph explorer tool on Developer.facebook.com , go to Tools and select graph explorer, its a nice tool which gives you exact idea about what you can fetch by sending "GET" and "POST" method on FB Graph APis
From what i see the app now only uses webhooks to post data to a data endpoint (in your app) at which point you can parse and use this. (FQL is deprecated). This is used for things like messaging.
A get request can be send to the API to get info - like the amt. of likes on your page.
The docs of FB explain the string you have to send pretty nicely. Sending requests can be done with the webclient, or your own webrequests.
https://msdn.microsoft.com/en-us/library/bay1b5dh(v=vs.110).aspx
Then once you have a string of the JSON formatted page you can parse this using JSON.NET library. It's available as a NUGEt package.

How to get friends list from facebook? (Desktop application)

As per this link code from stack overflow i have try this code for getting
friendslist but after login i got this error "requires valid signature"
string APIKey = ConfigurationManager.AppSettings["API_Key"];
string APISecret = ConfigurationManager.AppSettings["API_Secret"];
Facebook.Session.ConnectSession connectsession = new Facebook.Session.ConnectSession(APIKey, APISecret);
Facebook.Rest.Api api = new Facebook.Rest.Api(connectsession);
var friends = api.Friends.GetLists();
foreach (var friend in friends)
{
System.Console.WriteLine(friend.name);
}
guide me to find out the solution
Thanks
ash
If you are starting with a new application, you should definitely use the Graph API and not the old Rest API. The Rest API has been deprecated for quite a while now and there is no guarantee how much longer Facebook will support it.
For an example on using the Graph API try http://csharpsdk.org/docs/web/getting-started
You can obtain the friends list by making a request to me/friends
You can test other requests using the Graph API explorer.

Categories

Resources