facebook c# SDK get albums and images - facebook

what i am trying to achieve should be simple by theory but hell by implementation, if you think otherwise please help.
so what i am trying to achieve here is that I have my facebook page which I created a developer acount for it, and what i want is to take albums from the page to my website.
I am using the latest stable facebook sdk for .net 6.8.0, and i am assuming that the graph api is on v2.2.
this is the code i am using below to get the access token and access my albums
try
{
var fb = new FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = "---my application number---",
client_secret = "---my application secret---",
grant_type = "client_credentials"
});
var fb2 = new FacebookClient(result.access_token);
dynamic albums = fb2.Get("my application number/albums");
foreach (dynamic albumInfo in albums)
{
try
{
dynamic albumsPhotos = fb2.GetTaskAsync(albumInfo.id + "/photos");
}
catch (Exception Exception)
{
throw Exception;
}
}
}
catch (Exception e)
{
throw e;
}
The data returned in the dynamic albums variables is empty, the thing that confused me more is when i use facebook graph api explorer the call work fine and it return the albums. so what exactly i am missing.
I also read in some threads that you can access your albums without the secret password if they are public but that didn't work for me either i tried it in javascript but no joy.
Thank you in advance.

Since this is your page, it should be pretty easy to retrieve your own photos using Windows PowerShell and http://facebookpsmodule.codeplex.com Get-FBAlbums.

Related

Retriving Facebook posts from Profile via FB api

I have registered an app in facebook developers program and I can retrieve posts from facebook page using fb api, but I cannot retrieve posts from facebook profile. Should I use some different access token for both page or profile? Is there a different way for retrieving posts from facebook page and profile?
Any help will be appreciated!
You may need the user_status permission.
And you call the posts using this graph query {USER_ID}?fields=statuses
Prerequisite:- You need to have valida FB token for all the request:-
I am answering using c# language.
Step 1:- First you need to get the user's FB id using FB token
I am using Facebook SDK 7.0.6 for querying purpose
here's how to initialize the FB service which we will use in our consecutive calls.
FacebookService facebookService = new FacebookService(facebookToken);
var _facebookClient = new Facebook.FacebookClient(token);
Code snippet
public string GetFacebookID(string facebookToken)
{
dynamic result = _facebookClient.Get("me?fields=id");
if (result.ToString().Contains("id"))
{
return result["id"];
}
return string.Empty;
}
after that you can execute below method to get user's post using FB ID and token
public List<Post> GetPostsForUser(string facebookID)
{
List<Post> posts = new List<Post>();
dynamic result = _facebookClient.Get(facebookID + "/posts"); //Case Sensitive, Posts doesn´t work
if (result.ToString().Contains("data") && result.data.Count > 0)
{
foreach (var item in result.data)
{
posts.Add(new Post
{
ID = item.id,
Story = item.story,
Message = item.message,
Created_Time = Convert.ToDateTime(item.created_time),
Reactions = GetReactions(item.id)
});
}
result = _facebookClient.Get(GetNextURL(result.ToString()));
}
return posts;
}

facebook4j retrieve different image size from my facebook posts

i am using facebook4j to load home posts facebook.getHome() and i am getting the profile image and the post image as follows:
facebook4j.User fromUser = facebook.getUser(fbHomePost.getFrom().getId(),
new Reading().fields("picture"));
if (fromUser.getPicture() != null)
facebookUserPostDto.setProfileImage(fromUser.getPicture().getURL().toURI().toString());
if (fbHomePost.getPicture() != null)
facebookUserPostDto.setImageLocation(fbHomePost.getPicture().toURI().toString());
all is working well, but the image i am getting from the URLs are small and have low resolution. any idea how to get the "large" images from facebook using facebook4j API? facebook can provide different image sizes API Reference › Graph API › Pictures
thanks
OK first you have to add user_photos to your scope and make sure you are using a valid acces token NOT a Graph API Explorer Token
OAuthService service = new ServiceBuilder()
.provider(FacebookApi.class)
.apiKey(apiKey)
.apiSecret(apiSecret)
.callback("xxxx")
.scope("publish_actions,user_photos ")
.build();
then try this : (tested)
for(Post p : feed){
System.out.println("********************");
String type = p.getType();
System.out.println("type :"+type);
String idPicVid = p.getObjectId();
if(type.matches("photo")){
System.out.println("idPicVid "+idPicVid);
try{
Photo pic = facebook.getPhoto(idPicVid);
System.out.println(pic.toString());
System.out.println("source "+pic.getSource());
System.out.println("picture "+pic.getPicture());
}catch (Exception e) {
e.printStackTrace();
}
}
}
ok i got a reply from the facebook4j google group on how to go this
retrieve different image size from my facebook posts
Sameeh Harfoush
Brate

How to post images to facebook via windows phone?

In my application image has to post to Facebook,mail.Sorry i am new to windows phone.i don't have a idea.please help me.what i can do first.
If you want to share a status you can use your facebook account on your phone using Share link task (with this method you can only post on your wall) http://msdn.microsoft.com/en-us/library/hh394027%28v=vs.92%29.aspx
To post (pictures, messages or others) on every wall you have access you need some things :
First you need to create a facebook application using this link :
Facebook developers
After that you need to identify yourself using a WebBrowser control with the link related to your application. The application requests authorization to perform certain actions such as posting. You need to detail the authorizations like this :
Dictionary<string, string> uriParams = new Dictionary<string, string>() {
{"client_id", "your app id"},
{"response_type", "token"},
{"scope", "user_about_me, offline_access, publish_stream"}, //The rights
{"redirect_uri", "http://www.facebook.com/connect/login_success.html"},
{"display", "touch"}
};
The Dictionary also contains the redirection uri to define if the operation was successful.
Finally you are authentified and receive an access token. Now you can use a WebRequest POST to post a message using this token :
WebRequest request = HttpWebRequest.Create("https://graph.facebook.com/" + the id of your wall + "/feed");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream((reqResult) =>
{
using (Stream strm = request.EndGetRequestStream(reqResult))
using (StreamWriter writer = new StreamWriter(strm))
{
writer.Write(client.AccessToken);
writer.Write("&message=" + HttpUtility.UrlEncode(status));
}
request.BeginGetResponse((result) =>
{
try
{
var response = request.EndGetResponse(result);
using (var rstrm = response.GetResponseStream())
{
var serializer = new DataContractJsonSerializer(typeof(FacebookPostResponse));
var postResponse = serializer.ReadObject(rstrm) as FacebookPostResponse;
callback(true, null);
}
}
catch (Exception ex)
{
callback(false, ex);
}
}, null);
}, null);
Here is how to post a message on a facebook page,
You should give the Facebook C# SDK a try
Facebook C# SDK
I have built this in once in an app of mine. They have plenty examples available which should be useful.

Using Facebook Requests 2.0 with the C# SDK

I am trying to update the bookmark count field with the SDK but have not had any success yet.
Can somebody tell me what classes I need to instantiate to do something similar to the following link:
http://developers.facebook.com/blog/post/464
Note:
The link demonstrates how to set the bookmark count and delete it. I would like to be able to do the same with the SDK, any help would be appreciated.
To do this, first you need to get you app's access token:
private string GetAppAccessToken() {
var fbSettings = FacebookWebContext.Current.Settings;
var accessTokenUrl = String.Format("{0}oauth/access_token?client_id={1}&client_secret={2}&grant_type=client_credentials",
"https://graph.facebook.com/", fbSettings.AppId, fbSettings.AppSecret);
// the response is in the form: access_token=foo
var accessTokenKeyValue = HttpHelpers.HttpGetRequest(accessTokenUrl);
return accessTokenKeyValue.Split('=')[1];
}
A couple of things to note about the method above:
I'm using the .Net HttpWebRequest instead of the Facebook C# SDK to grab the app access_token because (as of version 5.011 RC1) the SDK throws a SerializationException. It seems that the SDK is expecting a JSON response from Facebook, but Facebook returns the access token in the form: access_token=some_value (which is not valid JSON).
HttpHelpers.HttpGetRequest simply uses .Net's HttpWebRequest. You can just as well use WebClient, but whatever you choose, you ultimately want to make this http request:
GET https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials HTTP/1.1
Host: graph.facebook.com
Now that you have a method to retrieve the app access_token, you can generate an app request as follows (here I use the Facebook C# SDK):
public string GenerateAppRequest(string fbUserId) {
var appAccessToken = GetAppAccessToken();
var client = new FacebookClient(appAccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = "Test: Action is required";
parameters.data = "Custom Data Here";
string id = client.Post(String.Format("{0}/apprequests", fbUserId), parameters);
return id;
}
Similarly, you can retrieve all of a user's app requests as follows:
Note: you probably don't want to return "dynamic", but I used it here for simplicity.
public dynamic GetAppRequests(string fbUserId) {
var appAccessToken = GetAppAccessToken();
var client = new FacebookClient(appAccessToken);
dynamic result = client.Get(String.Format("{0}/apprequests", fbUserId));
return result;
}
I hope this helps.

How to post image on facebook fan page using C# facebook sdk on codeplex

Currently I'm working on my HTML 5 ASP.Net Application,
Which has requirement of Graffiti Wall, When user draw something on my Wall(means on my HTML 5 Canvas element), and Press Share Button on my Page, at that time the whole picture should need to be post on one of the Facebook Page.
Now my question is that is this thing possible using C# facebook sdk by codeplex ?
if its possible, than how to post image on facebook fan page using this SDK??
Where can I get the good resource the implement this kind of functionality or similar code.
I've check the all examples given by them, there is no any example which post on the facebook fan page.
Or even other library that can implement this kind of functionality.
I've check this library, and see that it has FacebookClient,ExpandoObject, FacebookMediaObject kind of classes, but how to and where to use this classes,where are the description and sample code.
Thanks,
Jigar Shah
you can post to others wall using "{id}/feed"
if you want to post image/video on wall. Try downloading the samples from nuget.
Install-Package Facebook.Sample
Here is how to do using the graph api.
public static string UploadPictureToWall(string id, string accessToken, string filePath)
{
var mediaObject = new FacebookMediaObject
{
FileName = System.IO.Path.GetFileName(filePath),
ContentType = "image/jpeg"
};
mediaObject.SetValue(System.IO.File.ReadAllBytes(filePath));
try
{
var fb = new FacebookClient(accessToken);
var result = (IDictionary<string, object>)fb.Post(id + "/photos", new Dictionary<string, object>
{
{ "source", mediaObject },
{ "message","photo" }
});
var postId = (string)result["id"];
Console.WriteLine("Post Id: {0}", postId);
// Note: This json result is not the orginal json string as returned by Facebook.
Console.WriteLine("Json: {0}", result.ToString());
return postId;
}
catch (FacebookApiException ex)
{
// Note: make sure to handle this exception.
throw;
}
}