facebook c# sdk: how to get all user facebook pages - facebook

I want to retrieve all page names the user is administering. Ive came across this post which is exactly what I want using graph api and not the FQL. Ive gotten the access token already but I cant debug using the below code. Anybody knows how do I achieve this?
//view all user pages
private void pageBtn_Click(object sender, EventArgs e)
{
FacebookAPI api = new Facebook.FacebookAPI(myToken.Default.token);
JSONObject pageData = api.Get("/me/account");//pulls all the pages
var data = pageData.Dictionary["name"];
List<JSONObject> pageList = data.Array.ToList<JSONObject>();
foreach (var page in pageList)
{
lbPages.Items.Add(page.Dictionary["name"].String);
}
}

Okaay I think Ive got it. I used the below code to return me all the pages I have. Thanks TommyBs for the first stepping stone!
FacebookAPI api = new Facebook.FacebookAPI(myToken.Default.token);
JSONObject pageData = api.Get("/me/accounts");
var data = pageData.Dictionary["data"];
List<JSONObject> pageList = data.Array.ToList<JSONObject>();
foreach (var page in pageList)
{
// myFriendsData.Add(friend.Dictionary["id"].String, friend.Dictionary["name"].String);
listBox1.Items.Add(page.Dictionary["name"].String);
}

Related

I canĀ“t get the friendlist from facebook C# SDK (Windows phone)

i want to get the facebook friend's list from my application, but returns me data: []... empty! :(
the scenario it's this:
C#
const string QueryToGetFbInfo = "me";
const string QueryToGetFbPhoto = "me?fields=picture.width(200).height(200)";
const string QueryToGetFriendList = "me/friends?fields=name,picture.width(100).height(100)";
private void btnFacebook_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
FacebookSessionClient fbSession = new FacebookSessionClient("FB_APP_ID");
fbSession.LoginWithApp("public_profile, user_friends, read_friendlists, email", "custom_state_string");
}
private async void tbnShowfriends_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
FacebookSession session = SessionStorage.Load();
FacebookClient client = new FacebookClient(session.AccessToken);
// Get Facebook FriendList
dynamic friends = await client.GetTaskAsync(QueryToGetFriendList);
//Get Facebook user info
dynamic result = await client.GetTaskAsync(QueryToGetFbInfo);
GraphUser user = new GraphUser(result);
//Get profile picture from facebook
dynamic result1 = await client.GetTaskAsync(QueryToGetFbPhoto);
JsonObject json = result1.picture.data;
var picture = (IDictionary<string, object>)json;
....
}
Facebook App Config has the permissions... forgot some ?.. the new panel confuses me a little, Maybe I forgot something in the application settings...
when i select Api Graph, returns me, a friendlist, fine!
but when I select my application, I do not return anything
What I forgot ?... how can i fix this problem ?
You authed Graph Explorer using API v1.0 which means that that app will get all your friends until 4/30/2014. You app you authed using v2.0 or v2.1 which means that you will only get friends that are also using the app

How do I get Access Token for Facebook Graph API in C#?

I am trying to develop a demo Facebook App in C#. But I could not get Access Token (for both Application & User).
Please help me, How could I get this for both Application & User (Diff examples are welcome).
My Code is:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckIfFacebookAppIsSetupCorrectly();
var fbWebContext = FacebookWebContext.Current;
if (fbWebContext.IsAuthorized())
{
var fb = new FacebookWebClient(fbWebContext);
dynamic result = fb.Get("/me");
lblName.Text = "Hi " + result.name;
}
}
private void CheckIfFacebookAppIsSetupCorrectly()
{
bool isSetup = false;
var settings = ConfigurationManager.GetSection("facebookSettings");
if (settings != null)
{
var current = settings as IFacebookApplication;
if (current.AppId != "{app id}" &&
current.AppSecret != "{app secret}")
{
isSetup = true;
}
}
if (!isSetup)
{
System.Web.HttpContext.Current.Response.Redirect("~/GettingStarted.aspx");
}
}
}
Well When I check the code by putting the break points, I found that if (fbWebContext.IsAuthorized()) is always returns false, If I try to comment the Authorization I get the following Exception:
(OAuthException) An active access token must be used to query information about the current user.
Than I searched for this, I got following Link: Another Question Link
But When I got the Access Token for the App, I could not assign to the object as that is readonly.
What should I Do in this case, Also How do I get Access Token for Users?
Thanks
you need to create a new app and account at facebookDeveloperSite
you will get access token from there
Regards

Using Facebook C# SDK to post to page

I've been using the Facebook C# SDK for sometime now, but have a really old version and am still using the REST API (I think). I'm just concerned with using the API to post to my own Facebook page (I have a WCMS plugin that posts content to our institution's Facebook page). I was wondering if anyone knew of a good tutorial on how to get this setup with the latest version of the SDK? I'm also concerned with how this is going to work when offline_access goes away so any thoughts on that would be appreciated as well. I'd rather not have to go in an manually get a new access token every 60 days. This seems somewhat unnecessary since the app I'm using to do the posting is in the same FB account as the page I'm trying to post to.
Here's one way to do it:
public static string RefreshTokenAndPostToFacebook(string currentAccessToken)
{
string newAccessToken = RefreshAccessToken(currentAccessToken);
string pageAccessToken = GetPageAccessToken(newAccessToken);
PostToFacebook(pageAccessToken);
return newAccessToken; // replace current access token with this
}
public static string GetPageAccessToken(string userAccessToken)
{
FacebookClient fbClient = new FacebookClient();
fbClient.AppId = "app id";
fbClient.AppSecret = "app secret";
fbClient.AccessToken = userAccessToken;
Dictionary<string, object> fbParams = new Dictionary<string, object>();
JsonObject publishedResponse = fbClient.Get("/me/accounts", fbParams) as JsonObject;
JArray data = JArray.Parse(publishedResponse["data"].ToString());
foreach (var account in data)
{
if (account["name"].ToString().ToLower().Equals("your page name"))
{
return account["access_token"].ToString();
}
}
return String.Empty;
}
public static string RefreshAccessToken(string currentAccessToken)
{
FacebookClient fbClient = new FacebookClient();
Dictionary<string, object> fbParams = new Dictionary<string, object>();
fbParams["client_id"] = "app id";
fbParams["grant_type"] = "fb_exchange_token";
fbParams["client_secret"] = "app secret";
fbParams["fb_exchange_token"] = currentAccessToken;
JsonObject publishedResponse = fbClient.Get("/oauth/access_token", fbParams) as JsonObject;
return publishedResponse["access_token"].ToString();
}
public static void PostToFacebook(string pageAccessToken)
{
FacebookClient fbClient = new FacebookClient(pageAccessToken);
fbClient.AppId = "app id";
fbClient.AppSecret = "app secret";
Dictionary<string,object> fbParams = new Dictionary<string,object>();
fbParams["message"] = "Test message";
var publishedResponse = fbClient.Post("/your_page_name/feed", fbParams);
}
I would recommend you start by reading this blog post. http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-First-Facebook-Application-v6.aspx
And this documentation http://csharpsdk.org/docs/making-synchronous-requests
http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx
and find graph api post
i hope one day prabir and nathan will finish web site docs and we will learn it clearly.for now.just digg the web.

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;
}
}

Facebook c# sdk get users email

I have a site which is using facebook for auth. I want to gather some basic info when a user signs up including their email address.
The code i have for the login is standard:
public ActionResult Login(string returnUrl)
{
var oAuthClient = new FacebookOAuthClient();
oAuthClient.AppId = AppSettings.GetConfigurationString("appId");
oAuthClient.RedirectUri = new Uri(AppSettings.GetConfigurationString("redirectUrl"));
var loginUri = oAuthClient.GetLoginUrl(new Dictionary<string, object> { { "state", returnUrl } });
return Redirect(loginUri.AbsoluteUri);
}
How do i add the request to access permissions in that? Or do i do it another way?
You need to use the email permission (the full list is here: http://developers.facebook.com/docs/authentication/permissions/ )
The way to add permissions to the authorization is by appending a comma separated list to &scope= , e.g.:
https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&scope=email,read_stream
Update: As you marked, the parameters are passed to the GetLoginUrl() method, although in the codeplex forum they also used ExchangeCodeForAccessToken(), which you might want to take a look at also.
A couple of examples using the C# SDK:
http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-first-Facebook-Application.aspx
Facebook .NET SDK: How to authenticate with ASP.NET MVC 2
http://facebooksdk.codeplex.com/discussions/244568
A snoop at the sdk code and i came up wiht:
public ActionResult Login(string returnUrl)
{
var oAuthClient = new FacebookOAuthClient();
oAuthClient.AppId = AppSettings.GetConfigurationString("appId");
oAuthClient.RedirectUri = new Uri(AppSettings.GetConfigurationString("redirectUrl"));
var parameters = new Dictionary<string, object>();
parameters["state"] = returnUrl;
parameters["scope"] = "email";
var loginUri = oAuthClient.GetLoginUrl(parameters);
return Redirect(loginUri.AbsoluteUri);
}
not tested it yet and the missus is shouting at me for working late so will have to test tomoz :)