I want to recover the posts of my Facebook account to simple table, but I am facing some problems - facebook

I am using C# and ASP.NET to code this. I don't want the user to be forced to log in and authorize my facebook app, so I wrote this code to get my token that works fine:
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/oauth/access_token?client_id=MYID&client_secret=MYSECRET&user_id=MYUSERID&grant_type=client_credentials");
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result1 = sr.ReadToEnd();
sr.Close();
myResponse.Close();
string token = result1.Substring(13, result1.Length - 13);
Then I wrote this code to get my recent posts:
HttpWebRequest myRequest1 = (HttpWebRequest)WebRequest.Create(string.Format("{0}{1}","https://graph.facebook.com/app/posts?access_token=",token));
myRequest1.Method = "GET";
WebResponse myResponse1 = myRequest1.GetResponse();
//StreamReader sr1 = new StreamReader(myResponse1.GetResponseStream(), System.Text.Encoding.UTF8);
StreamReader sr1 = new StreamReader(myResponse1.GetResponseStream());
string result2 = sr1.ReadToEnd();
sr1.Close();
myResponse1.Close();
How can I quickly transform this JSON object into a table?

Related

making a REST calls from unity3d - Need to pass JSON object using HTTPWebRequest

How to make a REST call in unity3d? especially POST method. I have tried with GET request. Pls see the below get request. so i need to write POST request in Unity3d. The post rquest should be in JSON format. I tried with below code. It's hit the my service but the receiving JSON object is null. Hope your support.
var httpWebReq = WebRequest.Create("http://localhost:6091/UserService.svc/RegisterUser/") as HttpWebRequest;
httpWebReq.ContentType = "text/json;charset=utf-8";
httpWebReq.Method= "POST";
using(var streamWriter = new StreamWriter(httpWebReq.GetRequestStream()))
{
string user = "{UserID:0," +
"Email:'ruwan#gmail.com'," +
"Password:'ruwan123'," +
"NickName:'ruwa'," +
"Age:35" +
"}";
byte[] formData = UTF8Encoding.UTF8.GetBytes(user);
httpWebReq.ContentLength = formData.Length;
streamWriter.Write(formData);
}
var httpResponse = (HttpWebResponse)httpWebReq.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
Debug.Log(responseText);
}
use WWW for GET,
use WWW with WWWForm for POST.
Finally i got the solution thanks to all for help.
Actually the easiest way to make rest call for WCF is we have to add the Newtonsoft.Json. Finally my code is-
GET --
WebClient myWebClient = new WebClient();
myWebClient.Encoding = Encoding.UTF8;
myWebClient.Headers.Add("Content-Type", "text/json");
var json = JsonConvert.DeserializeObject<Room[] >(new WebClient().DownloadString("Your URL"));
List<yourclass> test1= new List<yourclass>();
foreach (var test in json)
{
test1.Add(new yourclass()
{
yourclass.property1 = test.property1
});
}
Debug.Log(test1);
POST---
WebClient myWebClient = new WebClient();
var Test = JsonConvert.SerializeObject(new
{
YourProperty= 0
}, new JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.None });
myWebClient.Encoding = Encoding.UTF8;
myWebClient.Headers.Add("Content-Type", "text/json");
string responsebody = myWebClient.UploadString("Your URL", "POST", Test );
//if(responsebody == true)
Debug.Log(responsebody);

Facebook API: error 400 when posting with test user, but works with administrator

I have facebook integrated on my login page, and now I'm trying to call a build-in action: books.rates using a Test App.
My app gets a valid access_token, and creates new feed items without problems. But when I'm tryng to make a books.rates API call, only works if the logged user is a real person (in my tests is me, also the App administrator), and fails allways with Error 400 when I try to rate a book with a Test User.
In both cases, the code is the same (only access_token and userid changes) and has "publish_actions" premission enabled. I think I'm missing something on Test App configuration, but I'm really lost right now.
Thanks!
Update 1
This is the code that makes the action. It's a test code so its very basic
Dictionary<string, string> postInfo = new Dictionary<string, string>();
postInfo["book"] = "http://www.whakoom.com/comics/6jMl7/52/4";
postInfo["rating:value"] = "4";
postInfo["rating:scale"] = "5";
postInfo["fb:explicitly_shared"] = "true";
string graphUrl = string.Format("https://graph.facebook.com/v2.1/{0}/books.rates?access_token={1}", FbUserID, FbAccessToken);
string fbResp = PostPageContent(graphUrl, postInfo);
private static string PostPageContent(string url, Dictionary<string,string> postData)
{
string postInfo = string.Empty;
foreach(string key in postData.Keys)
{
if (postInfo.Length > 0)
postInfo += "&";
postInfo += string.Format("{0}={1}", HttpContext.Current.Server.UrlEncode(key), HttpContext.Current.Server.UrlEncode(postData[key]));
}
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postInfo.Length;
StreamWriter streamOut = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(postInfo);
streamOut.Close();
string retValue = string.Empty;
WebResponse response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
retValue = reader.ReadToEnd();
reader.Close();
return retValue;
It seems that Test App with Test Users is unable to make books.rates calls until the main App is approved. The same api calls targeting a real App with a Test User works without problems.

Azure REST WebClient PUT Blob

I'm trying to simply upload a new blob to an Azure Storage countainer using WebClient like this :
var sas = "[a new generated sas with Read, Write, List & Delete permissions]";
var sData = "This is a test!";
var sEndPoint = "http://myaccount.blob.core.windows.net/mycontainer/MyTest.txt" + sas;
var clt = new WebClient();
var res = await clt.UploadStringTaskAsync(sEndPoint, "PUT", sData);
This is giving me a "(400) Bad Request." error. Am I doing anything wrong here?
Thanks
(By the way, I need to use REST instead of Client API since I'm in a Silverlight project)
You would need to define a request header (x-ms-blob-type) for blob type and set it's value to BlockBlob. Also for Put requests you would need to define the Content-Length request header as well. I wrote a blog post on Shared Access Signatures and performing some blob operations using that (with both REST API and Storage Client library) which you can read here: http://gauravmantri.com/2013/02/13/revisiting-windows-azure-shared-access-signature/.
and here's the code from that post on uploading blob. It uses HttpWebRequest/HttpWebResponse instead of WebClient:
static void UploadBlobWithRestAPISasPermissionOnBlobContainer(string blobContainerSasUri)
{
string blobName = "sample.txt";
string sampleContent = "This is sample text.";
int contentLength = Encoding.UTF8.GetByteCount(sampleContent);
string queryString = (new Uri(blobContainerSasUri)).Query;
string blobContainerUri = blobContainerSasUri.Substring(0, blobContainerSasUri.Length - queryString.Length);
string requestUri = string.Format(CultureInfo.InvariantCulture, "{0}/{1}{2}", blobContainerUri, blobName, queryString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Method = "PUT";
request.Headers.Add("x-ms-blob-type", "BlockBlob");
request.ContentLength = contentLength;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(Encoding.UTF8.GetBytes(sampleContent), 0, contentLength);
}
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
}
}
When testing against the blob emulator this is the code I need to get it working:
var connection = ConfigurationManager.AppSettings["AzureStorageConnectionString"];
var storageAccount = CloudStorageAccount.Parse(connection);
var client = new WebClient();
client.Headers.Add("x-ms-blob-type", "BlockBlob");
client.Headers.Add("x-ms-version", "2012-02-12");
client.UploadData(string.Format(#"{0}/$root/{1}{2}", storageAccount.BlobEndpoint, myFileName, sharedAccessSignature), "PUT", _content);

Set Express Checkout method returning an failure in the ack

I want to do the express checkout process in the paypal for the customers without redirecting the browser. I have written the code like
string sAPIUser = apiuser;
string sAPIPassword = password;
string sAPISignature = "signature";
string sAPIEndpoint = "https://api-3t.sandbox.paypal.com/nvp";
string sAppID = "APP-80W284485P519543T";
StringBuilder sRequest = new StringBuilder();
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = ("&METHOD=SetExpressCheckout");
postData += ("&VERSION=63.0");
postData += ("&PAYMENTREQUEST_0_AMT=10.00");
postData += ("&PAYMENTREQUEST_0_CURRENCYCODE=USD");
postData += ("&PAYMENTREQUEST_0_PAYMENTACTION=Sale");
postData += ("CANCELURL=http://www.google.com");
postData += ("RETURNURL=http://www.google.com");
byte[] data = encoding.GetBytes(postData);
// Prepare web request...
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(sAPIEndpoint);
myRequest.Method = "POST";
myRequest.Headers.Add("X-PAYPAL-SECURITY-USERID", sAPIUser);
myRequest.Headers.Add("X-PAYPAL-SECURITY-PASSWORD", sAPIPassword);
myRequest.Headers.Add("X-PAYPAL-SECURITY-SIGNATURE", sAPISignature);
myRequest.Headers.Add("X-PAYPAL-SERVICE-VERSION", "1.3.0");
myRequest.Headers.Add("X-PAYPAL-REQUEST-DATA-FORMAT", "NV");
myRequest.Headers.Add("X-PAYPAL-RESPONSE-DATA-FORMAT", "NV");
myRequest.Headers.Add("X-PAYPAL-APPLICATION-ID", sAppID);
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = data.Length;
// Send the request, read the response
Stream newStream = myRequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
Stream responseStream = response.GetResponseStream();
Encoding encoding2 = Encoding.GetEncoding("utf-8");
StreamReader reader = new StreamReader(responseStream, encoding2);
string theResponse = reader.ReadToEnd();
theResponse = HttpUtility.HtmlDecode(theResponse);
But i am getting the failure message in the theResponse variable. What error i am doing. The error is like
TIMESTAMP=2013%2d03%2d05T05%3a55%3a38Z&CORRELATIONID=5c10035aca937&ACK=Failure&VERSION=63%2e0&BUILD=5331358&L_ERRORCODE0=10002&L_SHORTMESSAGE0=Authentication%2fAuthorization%20Failed&L_LONGMESSAGE0=You%20do%20not%20have%20permissions%20to%20make%20this%20API%20call&L_SEVERITYCODE0=Error
How can i rectify this.
Make sure that the credentials you are using are for your sandbox account and not your live account. Your code looks like it is pointing to the sandbox, so you would need to use your sandbox credentials. Also, if this is not all of your code, make sure you are not passing across a variable called "SUBJECT" and populating it with an email address.

Upgrading POST request from HttpClient to HttpComponents. What's going wrong here?

I inherited some old code that uses the now-deprecated Apache Commons HttpClient. I was tasked with upgrading it to use the newer Apache HttpComponents. However, I can't seem to get this POST request to function properly. The server keeps complaining that Content-Length = 0. I'm fairly certain that it's a problem with my conversion of how parameters are added.
The old HttpClient code looks something like this:
PostMethod postMethod = null;
int responseCode = 0;
try{
HttpClient httpClient = new HttpClient();
postMethod = new PostMethod(getServiceUrl()); //The url, without a query.
...
postMethod.addParameter(paramName, request);
responseCode = httpClient.executeMethod(postMethod);
...
}
And here are my HttpComponents replacements:
HttpPost postMethod = null;
int responseCode = 0;
HttpResponse httpResponse = null;
try{
HttpClient httpClient = new DefaultHttpClient();
postMethod = new HttpPost(getServiceUrl()); //The url, without a query.
...
BasicHttpParams params = new BasicHttpParams();
params.setParameter(paramName, request);
postMethod.setParams(params);
httpResponse = httpClient.execute(postMethod);
responseCode = httpResponse.getStatusLine().getStatusCode();
...
}
The servlet my code it talking to is using Apache Commons FileUpload. Here is the code it catches on when it receives my request:
ServletRequestContext src = new ServletRequestContext(request);
if (src.getContentLength() == 0)
throw new IOException("Could not construct ServletRequestContext object");
It used to pass this test just fine. Now it doesn't. I've tried all kinds of alternatives, such as using the header, or passing request as a URLEncoded query. Have I made a mistake in my upgrade, somewhere?
Note: I can't just change how the servlet receives my request, because then I'll have to change a number of other apps that talk to it, and that's too big a job.
To set the request body, you can use HttpPost's setEntity() method. You can explore the available entity types here. This would replace the BasicHttpParams code.
To send a form entity, for example:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://someurl");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("name", "value"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(formEntity);
HttpResponse httpResponse = client.execute(httpPost);