Foursquare SDK for .net - c#

may i know is there any foursquare sdk for .NET C#.
I am doing based on the developer reference but i failed to do it during request for token, i keep on getting the error.
I am using VS 2008 and under development server. I search before this error because of url rewriting, but i'm not hosted in IIS and i also have check the web.config, no luck also. Please help, thanks.
This is my error:
The HTTP verb POST used to access path '/login' is not allowed.
This is my implementation:
HttpWebRequest request = null;
HttpWebResponse response = null;
StreamReader responseStream = null;
ASCIIEncoding ascii = null;
string key = ConfigurationManager.AppSettings["key"];
string secret = ConfigurationManager.AppSettings["secret"];
string callback = ConfigurationManager.AppSettings["callback"];
string obtainTokenUrl = ConfigurationManager.AppSettings["obtainTokenUrl"];
try
{
string postData = "client_id=" + key + "&response_type=code&redirect_uri=" + callback;
ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postData);
try
{
request = WebRequest.Create(obtainTokenUrl) as HttpWebRequest;
}
catch (UriFormatException)
{
request = null;
}
if (request == null)
{
throw new ApplicationException("Invalid URL: " + obtainTokenUrl);
}
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postBytes.Length;
//add post data to request
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Close();
response = (HttpWebResponse)request.GetResponse();
Encoding encode = Encoding.GetEncoding("utf-8");
responseStream = new StreamReader(response.GetResponseStream(), encode);
Response.Write(responseStream.ReadToEnd());

Well, this may be a roundabout sort of answer. But maybe you could check out the open source 4square app for windows phone 7:
http://4square.codeplex.com/
Since you can look at the source code, you can see how they are interfacing with the 4sq API :-)

SharpSquare - FourSquare SDK for .NET http://www.igloolab.com/sharpsquare/

Related

c# PayPal Acess Token does not return anything although connection is "OK"

I am using .net to connect to PayPal to get access token. I was following the documentary provided on PayPal. https://developer.paypal.com/docs/api/overview/#make-your-first-call
This is what I have so far. Mostly go it from here. Although it connects, it does not return anything back. I tried it on the Postman and I am getting a json object with access token, but nothing is returned here.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(clientId + ":" + clientSecret));
request.Accept = "application/json";
request.Headers.Add("Accept-Language", "en_US");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
byte[] postBytes = Encoding.ASCII.GetBytes("grant_type=client_credentials");
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
postStream.Flush();
postStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
This is what I am getting from on breakpoints.
response.CharacterSet = ""
response.ContentLength = 899
response.StatusCode = OK
Found the answer. The following code provides the json object.
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString); // This will display the answer as JSON, now just parse it.
Follow PayPal's .NET SDK Quick Start guide. You can authenticate and get your access token as follows:
using PayPal.Api;
// Authenticate with PayPal
var config = ConfigManager.Instance.GetProperties();
var accessToken = new OAuthTokenCredential(config).GetAccessToken();

HttpWebRequest get 404 page only when using POST mode

First of all: I know this has been asked over 100 times, but most of these questions were eigher caused by timeout problems, by incorrect Url or by foregetting to close a stream (and belive me, I tried ALL the samples and none of them worked).
So, now to my question: in my Windows Phone app I'm using the HttpWebRequest to POST some data to a php web service. That service should then save the data in some directories, but to simplify it, at the moment, it only echos "hello".
But when I use the following code, I always get a 404 complete with an apache 404 html document. Therefor I think I can exclude the possibility of a timeout. It seems like the request reaches the server, but for some reason, a 404 is returned. But what really makes me be surprised is, if I use a get request, everything works fine. So here is my code:
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp(server + "getfeaturedpicture.php?randomparameter="+ Environment.TickCount);
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0";
webRequest.Method = "POST";
webRequest.ContentType = "text/plain; charset=utf-8";
StreamWriter writer = new StreamWriter(await Task.Factory.FromAsync<Stream>(webRequest.BeginGetRequestStream, webRequest.EndGetRequestStream, null));
writer.Write(Encoding.UTF8.GetBytes("filter=" + Uri.EscapeDataString(filterML)));
writer.Close();
webRequest.BeginGetResponse(new AsyncCallback((res) =>
{
string strg = getResponseString(res);
Stator.mainPage.Dispatcher.BeginInvoke(() => { MessageBox.Show(strg); });
}), webRequest);
Although I don't think this is the reason, here's the source of getResponseString:
public static string getResponseString(IAsyncResult asyncResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse webResponse;
try
{
webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
}
catch (WebException ex)
{
webResponse = ex.Response as HttpWebResponse;
}
MemoryStream tempStream = new MemoryStream();
webResponse.GetResponseStream().CopyTo(tempStream);
tempStream.Position = 0;
webResponse.Close();
return new StreamReader(tempStream).ReadToEnd();
}
This is tested code work fine in Post method with some body. May this gives you an idea.
public void testSend()
{
try
{
string url = "abc.com";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/plain; charset=utf-8";
req.BeginGetRequestStream(SendRequest, req);
}
catch (WebException)
{
}
}
//Get Response and write body
private void SendRequest(IAsyncResult asyncResult)
{
string str = "test";
string Data = "data=" + str;
HttpWebRequest req= (HttpWebRequest)asyncResult.AsyncState;
byte[] postBytes = Encoding.UTF8.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();
request.BeginGetResponse(SendResponse, req);
}
//Get Response string
private void SendResponse(IAsyncResult asyncResult)
{
try
{
MemoryStream ms;
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
HttpWebResponse httpResponse = (HttpWebResponse)response;
string _responestring = string.Empty;
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
_responestring = reader.ReadToEnd();
}
}
catch (WebException)
{
}
}
I would suggest you to use RestSharp for your POST requests in windows phone. I am making an app for a startup and i faced lots of problems while using a similar code as yours. heres an example of a post request using RestSharp. You see, instead of using 3 functions it can be done in a more concise form. Also the response can be handled efficiently. You can get RestSharp from Nuget.
RestRequest request = new RestRequest("your url", Method.POST);
request.AddParameter("key", value);
RestClient restClient = new RestClient();
restClient.ExecuteAsync(request, (response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
StoryBoard2.Begin();
string result = response.Content;
if (result.Equals("success"))
message.Text = "Review submitted successfully!";
else
message.Text = "Review could not be submitted.";
indicator.IsRunning = false;
}
else
{
StoryBoard2.Begin();
message.Text = "Review could not be submitted.";
}
});
It turned out the problem was on the server-side: it tried it on the server of a friend and it worked fine, there. I'll contact the support of the hoster and provide details as soon as I get a response.

Get access token from google oauth from code

i used following code to get the access token from code as below
String code = HttpContext.Current.Request["code"];
string redirecturl = HttpContext.Current.Request["url"];
string Url = "https://accounts.google.com/o/oauth2/token";
string grant_type = "authorization_code";
string redirect_uri_encode = UrlEncodeForGoogle(url);
string data = "code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type={4}&access_type={5}";
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
string param = string.Format(data, code,configurationInfo.oauthclientid , configurationInfo.oauthclientsecretid, redirect_uri_encode, grant_type, "offline");
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
i am getting response as
The remote server returned an error: (400) Bad Request.
i do not know where i went wrong
waiting for your valuable comments
Google also provides a higher level library for accessing its services. I find it makes it much easier to work with its APIs.
http://code.google.com/p/google-api-dotnet-client/

Unauthorized when calling Google GCM

I trying to use Google GCM for sending push notifications. But get a WebException that says that the remote server returns 401 unautorized. I can't foung why it doen't work.
Anyone that knows why it doesn't work?
Here is my code:
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
string postData = "{ 'registration_ids': [ '"+registrationId+"' ], 'data': {'message': '"+message+"'}}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
Request.ContentType = "application/json";
//Request.ContentLength = byteArray.Length;
//Request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + AuthString);
Request.Headers.Add(HttpRequestHeader.Authorization, "Authorization: key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y");
//-- Delegate Modeling to Validate Server Certificate --//
//-- Create Stream to Write Byte Array --//
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//-- Post a Message --//
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
var text = "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadLine();
Reader.Close();
Daniel - Dude there is an issue with the GCM documentation ! Use Browser key as the authorization key at the place of Server API key . It will work.
OK, i am just shooting in the dark here. Take a look at this line:
Request.Headers.Add(HttpRequestHeader.Authorization, "Authorization: key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y");
Shouldn't it be:
Request.Headers.Add(HttpRequestHeader.Authorization, "key=AIzaSyCEygavdzrNM3pWNPtvaJXpvW66CKnjH_Y");
Since you're telling it this is a Authorization header, there's no need to add 'Authorization: ' again, does it?
Also, make sure the string constant 'HttpRequestHeader.Authorization' is 'Authorization'.

HttpWebRequest error 403

I am new in C# and have requirement to retrieve a url from C#. Most of case it’s working fine but in one case its throws an error. url is as follows
http://whois.afrinic.net/cgi-bin/whois?searchtext=41.132.178.138
Error is:
Exception in the HTTP request for url: http://whois.afrinic.net/cgi-bin/whois?searchtext=41.132.178.138 The remote server returned an error: (403) Forbidden.
My code is as
void MyFUnction(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = ".NET Framework Test Client";
request.ContentType = "application/x-www-form-urlencoded";
Logger.WriteMyLog("application/x-www-form-urlencoded");
// execute the request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Encoding.ASCII.GetString(buf, 0, count);
if (httpData == null)
httpData = tempString;
else
httpData += tempString;
}
}
while (count > 0); // any more data to read?
}
Remove your ContentType line.
request.ContentType....
You're not doing a form post, only retrieving the page with "GET".
request.Method = "GET"; //this is the default behavior
And also set the Accept property to "text/html".
request.Accept = "text/html";
Set request.Accept = "text/html"; as well and it will work.
I don't know why they are configured that way, might be deliberate to discourage some bots. You might want to check their terms of service whether you may query their site automatically.
Edited to add: Still convinced that my answer was correct in this case, I can reproduce the 403 every time if I don't set the Accept header. The ContentType is superfluous, but not harmful.
In any case, you'll also want to change your function to properly dispose the response, and to read the response with the correct character encoding:
void MyFunction(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = ".NET Framework Test Client";
request.Accept = "text/html";
Logger.WriteMyLog("application/x-www-form-urlencoded");
// execute the request
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(
resStream,
Encoding.GetEncoding(response.CharacterSet)
);
httpData = streamReader.ReadToEnd();
}
}

Categories