In my Desktop application, I want to read the Wall posts,Messages, Like counts etc for a particular Facebook page (not for a facebook user)
I went through this post get user data(on stackoverflow). I want to achieve the same thing but for a FB page.
I am ready to create a facebook application to achieve this and have the user to give permission to pull the data.
Please advice on the above.
You need an access token to get page data from Facebook.
First get an access token using below URL with your facebook application's parameters:
https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={yourappid}&client_secret={yourappscret}
Then you can call the Facebook Graph API with returning token
General: https://graph.facebook.com/wikipedia?access_token={token}
Posts: https://graph.facebook.com/wikipedia/posts?access_token={token}
An example code would be;
class Program
{
static void Main(string[] args)
{
var client = new WebClient();
string oauthUrl = string.Format("https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={0}&client_secret={1}", "appid", "appsecret");
string accessToken = client.DownloadString(oauthUrl).Split('=')[1];
string pageInfo = client.DownloadString(string.Format("https://graph.facebook.com/wikipedia?access_token={0} ", accessToken));
string pagePosts = client.DownloadString(string.Format("https://graph.facebook.com/wikipedia/posts?access_token={0} ", accessToken));
}
}
After researching i have developed this code
class Posts
{
public string PostId { get; set; }
public string PostStory { get; set; }
public string PostMessage { get; set; }
public string PostPictureUri { get; set; }
public Image PostImage { get; set; }
public string UserId { get; set; }
public string UserName { get; set; }
}
private List<Posts> getFBPosts()
{
//Facebook.FacebookClient myfacebook = new Facebook.FacebookClient();
string AppId = "--------";
string AppSecret = "----------";
var client = new WebClient();
string oauthUrl = string.Format("https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={0}&client_secret={1}", AppId, AppSecret);
string accessToken = client.DownloadString(oauthUrl).Split('=')[1];
FacebookClient myfbclient = new FacebookClient(accessToken);
string versio= myfbclient.Version;
var parameters = new Dictionary<string, object>();
parameters["fields"] = "id,message,picture";
string myPage="fanPage"; // put your page name
dynamic result = myfbclient.Get(myPage +"/posts", parameters);
List<Posts> postsList = new List<Posts>();
int mycount=result.data.Count;
for (int i = 0; i < result.data.Count; i++)
{
Posts posts = new Posts();
posts.PostId = result.data[i].id;
posts.PostPictureUri = result.data[i].picture;
posts.PostMessage= result.data[i].message;
var request = WebRequest.Create(posts.PostPictureUri);
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
posts.PostImage = Bitmap.FromStream(stream);
}
postsList.Add(posts);
}
return postsList;
}
You can also use a Nuget package called Facebook to fetch data from Facebook graph. Also, Json.NET helps you map the data directly into objects:
public class FacebookPageInfo
{
public long Id { get; set; }
public string Name { get; set; }
}
public class FacebookPost
{
public string Message { get; set; }
// ReSharper disable once InconsistentNaming
public string Created_Time { get; set; }
public string Id { get; set; }
}
public class FacebookPagingInfo
{
public string Previous { get; set; }
public string Next { get; set; }
}
public class FacebookPostData
{
public List<FacebookPost> Data { get; set; }
public FacebookPagingInfo Paging { get; set; }
}
public class Friend
{
public string Id { get; set; }
public string Name { get; set; }
}
// get access token
string oauthUrl = $"https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={appId}&client_secret={appSecret}";
string accessToken = client.DownloadString(oauthUrl).Split('=')[1];
// get data and deserialize it
var fbClient = new FacebookClient(accessToken);
var fbData = fbClient.Get("/wikipedia/").ToString();
var info = JsonConvert.DeserializeObject<FacebookPageInfo>(fbData);
fbData = fbClient.Get("/wikipedia/posts").ToString();
var posts = JsonConvert.DeserializeObject<FacebookPostData>(fbData);
Related
I am using an asp.net api to query from my xamarin app to SQL Server. Below is how I am querying the API, and setting up the return type, but I am getting an error of
Can not convert List to List
What do I need to change in my code so that this will execute as desired?
public List<string> GetApprovalGrid()
{
string URI = "XXXXXXX/api/Xamarin/properties";
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString(URI);
var message = JsonConvert.DeserializeObject<List<string>>(json);
return message;
}
}
public class ApproveUsers
{
public int ID { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public string phone { get; set; }
public string company { get; set; }
public string approveduser { get; set; }
}
private void LoadApproveUserGrid()
{
List<ApproveUsers> ApprovedUser = new List<ApproveUsers>();
//this line throws the error
ApprovedUser = dal.GetApprovalGrid();
//more code here
}
ApprovedUser is of type List<ApproveUsers> but GetApprovalGrid() returns List<string>
EDIT:
JsonConvert.DeserializeObject<List<ApproveUsers>>(json);
if your json is correctly formatted
EDIT2: you need to change the method signature to this too:
public List<ApproveUsers> GetApprovalGrid()
Via an http Post, I send html FormData to my Web Api2 controller.
The FormData contains one or more images, as well as client properties.
My front end Angular 5 service sends the http post (working fine):
var url = this.host + 'import/MediaUpload';
return this.http.post(url, formData, options)
.map((result: any) => result._body)
.catch(this.handleError);
I would like to convert the FormData to a generic List of MediaInfo class (defined below this MediaUpload() method) :
public async Task<HttpResponseMessage> MediaUpload(int projectId, int sectionId)
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var provider = await Request.Content.ReadAsMultipartAsync<InMemoryMultipartFormDataStreamProvider>(new InMemoryMultipartFormDataStreamProvider());
//access form data
NameValueCollection formData = provider.FormData;
List<MediaInfo> listMedia = new List<MediaInfo>();
//dynamic jsonData = JObject.Parse(formData["MediaInfo"]); // THROWS ERROR
JArray ary = JArray.Parse(formData["MediaInfo"]);
foreach (var item in ary) {
//listMedia.Add((MediaInfo)item); // ???
Console.WriteLine(item);
}
//access files
IList<HttpContent> files = provider.Files;
HttpContent file1 = files[0];
var thisFileName = file1.Headers.ContentDisposition.FileName.Trim('\"');
// additional file upload code removed, working fine..
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Headers.Add("DocsUrl", URL);
return response;
}
public class MediaInfo
{
public string PatientID { get; set; }
public string PatientFirstName { get; set; }
public string PatientLastName { get; set; }
public string PatientUID { get; set; }
public string PatientDOB { get; set; }
public string ExamDate { get; set; }
public string ExamDevice { get; set; }
public string SerialNo { get; set; }
public string Eye { get; set; }
public int DeviceID { get; set; }
public int CSIInstanceID { get; set; }
public int MediaNo { get; set; }
public string Procedure { get; set; }
public string FileName { get; set; }
public int FileSize { get; set; }
}
I thought I could do something like :
listMedia.Add((MediaInfo)item;
But I'm missing the correct conversion somewhere.
You can convert a JObject to a type of your choosing with the .ToObject<T>() method.
https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JToken_ToObject__1_1.htm
In this case you want your code to look like this:
listMedia.Add(item.ToObject<MediaInfo>());
You could also use JsonConvert.DeserializeObject to convert it directly into the desired type provided formData["MediaInfo"] returned well formed JSON.
List<MediaInfo> listMedia = JsonConvert.DeserializeObject<List<MediaInfo>>(formData["MediaInfo"]);
I am doing server to server communication and I am getting data back from my api. I using Http web client to do that. This is my code
public async Task<List<Report>> GetReports(string tokenType, string token, int page, int count)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, token);
var builder = new UriBuilder(ApiEndPointBase + "api/" + ApiVersion + "/LibraryDocument");
builder.Port = -1;
var query = HttpUtility.ParseQueryString(builder.Query);
query["page"] = page.ToString();
query["count"] = count.ToString();
builder.Query = query.ToString();
string url = builder.ToString();
var result = await client.GetAsync(url);
if (!result.IsSuccessStatusCode)
throw new Exception("");
List<Report> reports = new List<Report>();
await result.Content.ReadAsAsync<List<Report>>().ContinueWith(response =>
{
reports = response.Result;
});
return reports;
}
The issue I am having is that I am getting data from server in this format
public class Report
{
public int pK_LibraryDocument { get; set; }
public string fileName { get; set; }
public List<string> AvailableForModules { get; set; }
}
But I want data like this
public class Report
{
public int id{ get; set; }
public string fileName { get; set; }
public List<string> AvailableForModules { get; set; }
}
I would probably have other variable name changes as well. The reason for that is that I would have multiple data sources with same data but the format or name would be different. So I want to have a centralize naming for my self.
Is it possible in a not expensive (time consuming) way.
JSON.NET that is used by default for deserialization supports JsonProperty attribute for adjusting JSON field name:
public class Report
{
[JsonProperty("pK_LibraryDocument")]
public int id { get; set; }
public string fileName { get; set; }
public List<string> AvailableForModules { get; set; }
}
I've tried other answers with people who had the same issue, but I can't get it to work. Plus I'm new to this. Any help is appreciated.
When I run this, my phone data is null.
Here's the JSON data I get back from my service.
{"GetDirectoriesResult":"[{\"id\":1,\"department\":\"Admitting\",\"subdepartment\":\"\",\"phone\":\"555-444-4013\",\"comments\":\"Press 1\"},{\"id\":2,\"department\":\"Ambulatory Surgery Center\",\"subdepartment\":\"\",\"phone\":\"555-444-4013\",\"comments\":\"\"}]"}
My Code
public class PhoneList
{
// public string GetDirectoriesResult { get; set; }
public List<Phone> Phones { get; set; } //- can't get this working
}
public class Phone
{
public int id { get; set; }
public string department { get; set; }
public string subdepartment { get; set; }
public string phone { get; set; }
public string comments { get; set; }
}
public IRestResponse<PhoneList> Execute<PhoneList>(RestRequest request) where PhoneList : new()
{
PhoneList ro = new PhoneList();
var client = new RestClient();
client.BaseUrl = BaseUrl;
// var request = new RestRequest();
request.RequestFormat = DataFormat.Json;
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(ro);
IRestResponse<PhoneList> response = client.Execute<PhoneList>(request);
if (response.ErrorException != null)
{
const string message = "Error retrieving response. Check inner details for more info.";
var Exception = new ApplicationException(message, response.ErrorException);
throw Exception;
}
return response;
}
I'm using Facebook Graph API to return user information for my app. So far I only needed to get the email as an extended property and I never had any problem with it. However, now I have to get the user birthday, but it is not working as expected. I am getting a null value.
Here is part of the class I use to return the information
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OAuth2;
namespace Contoso.Web.Mvc.Controls.Authentication.IdentityProviders
{
public class FacebookIdentityProvider : IdentityProvider
{
public override ActionResult Authenticate(Func<LoginParameters, ActionResult> CallbackFunction)
{
var authorization = fbClient.ProcessUserAuthorization();
var urlHelper = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
if (authorization == null && String.IsNullOrWhiteSpace(Parameters.AccessToken))
{
//Kick off authorization request
fbClient.RequestUserAuthorization(scope: new string[] { "email", "user_birthday"});
}
else
{
if(authorization != null)
Parameters.AccessToken = authorization.AccessToken;
var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(Parameters.AccessToken));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var graph = FacebookGraph.Deserialize(responseStream);
var user = GetUser(graph);
var requiresExtraInformation = false;
DoFormAuthenticationAndCreateUserIfNeeded(user, out requiresExtraInformation);
if (requiresExtraInformation)
{
return RedirectToExtraInformationPage(user);
}
return CallbackFunction(Parameters);
}
}
}
return new RedirectResult(urlHelper.Action("Index"));
}
}
[DataContract]
public class FacebookGraph
{
private static DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(FacebookGraph));
[DataMember(Name = "id")]
public long Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "first_name")]
public string FirstName { get; set; }
[DataMember(Name = "last_name")]
public string LastName { get; set; }
[DataMember(Name = "email")]
public string Email { get; set; }
[DataMember(Name = "gender")]
public string Gender { get; set; }
[DataMember(Name = "user_birthday")]
public string UserBirthday { get; set; }
public static FacebookGraph Deserialize(string json)
{
if (string.IsNullOrEmpty(json))
{
throw new ArgumentNullException("jsonStream");
}
return Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(json)));
}
public static FacebookGraph Deserialize(Stream jsonStream)
{
if (jsonStream == null)
{
throw new ArgumentNullException("jsonStream");
}
return (FacebookGraph)jsonSerializer.ReadObject(jsonStream);
}
}
}
When I deserialize the response I get from facebook I get all the information I need except for the user birthday (it appears as null). I checked and my facebook profile does have the user birthday.
Ok, I finally found the problem and it was a little bit silly, but I'm leaving it here in case someone else stumbles upon this.
The problem was that even though I was requesting the correct scope "user_birthday", the property in the graph object is just called "birthday", so instead of having this
[DataMember(Name = "user_birthday")]
public string UserBirthday { get; set; }
I should have this
[DataMember(Name = "birthday")]
public string UserBirthday { get; set; }
And that's it. It's working now!