facebook upload photo as company page - c#

I have a question regarding using facebook graph API (OAuth) to upload photo.
I have created one company page under my account.
When I use my account to upload photo to my company page, my user name appears as a user who uploaded the page.
Is there anyway I can upload page so that company name appears?
Below is the code that I currently implemented.
string access_token = FacebookSystem.RetrieveToken(UserEmail, AppID);
string query = string.Empty;
if (string.IsNullOrEmpty(PageID) || PageID.Equals("default", StringComparison.InvariantCultureIgnoreCase))
{
query = "me/photos";
}
else
{
query = string.Format("{0}/photos", PageID);
}
var fb = new FacebookClient(access_token);
try
{
dynamic parameters = new ExpandoObject();
foreach (string i in args.FileList)
{
parameters.message = args.Comment;
parameters.source = new FacebookMediaObject
{
ContentType = "image",
FileName = Path.GetFileName(i)
}.SetValue(File.ReadAllBytes(i));
fb.Post(query, parameters);
}
}

in order to use Graph API on behalf of a Page, you need to get Page access token - see here for more details: https://developers.facebook.com/docs/facebook-login/access-tokens/#pagetokens
Authenticate the user and request the manage_pages permission
Get the list of pages the user manages from (1): https://graph.facebook.com/me/accounts?access_token=USER_ACCESS_TOKEN
Parse the list and get the token - and use it to post to the feed.
you will do (1) in graph API explorer - and you will get user token. Then insert that token into URL in (2) - and you will see all your pages and corresponding token. Take the one you need and use it in your C# code to upload images.

Related

Facebook Access Token keeps Expiring c#

I have a web application that runs a schedule job which pulls in the Facebook reviews from a page which I manage. Here is a snippet
public void Execute(IJobExecutionContext context)
{
//get api details from the web.config
var pageId = WebConfigurationManager.AppSettings["FacebookPageId"];
var token = WebConfigurationManager.AppSettings["FacebookAPIToken"];
if (!string.IsNullOrEmpty(token))
{
//create a facebook client object
var client = new FacebookClient(token);
//make a call to facebook to retrieve the json data
dynamic graphJson = client.Get(pageId + "?fields=ratings{review_text,reviewer,rating}").ToString();
//deserialize the json returned from facebook
ReviewDeserializeData reviews = JsonConvert.DeserializeObject<ReviewDeserializeData>(graphJson);
//loop through the deserialized data and pass each review to the import class
foreach (var rating in reviews.ratings.data)
{
var fbRating = new FacebookRating
{
RatingReviewerId = long.Parse(rating.reviewer.id),
StarRating = rating.rating,
ReviewerName = rating.reviewer.name,
ReviewText = rating.review_text
};
ImportFacebookRating.ImportTheFacebookRating(fbRating);
}
}
}
This works great until the Page Access Token expires. I have tried following many articles such as this one https://medium.com/#Jenananthan/how-to-create-non-expiry-facebook-page-token-6505c642d0b1#.24vb5pyiv but i have had no luck fixing the token expiring.
Does anyone know how i can achieve this or is there a way to programmatically generate a new token if the existing one has expired? at the moment i have it stored in the web.config as an app setting.
Thanks
I found the answer here and was able to generate a token that 'Never' Expires Long-lasting FB access-token for server to pull FB page info

Share Post as Facebook App on Facebook page

I have been using facebook api to share post on facebook page as facebook app. I have created facebook app.
The post also gets shared but the problem is, it is not being posted as a facebook app. Instead it asks user for login and then it shares post as a user. Any help regarding how could I share a post as a Facebook App would be appreciated as I have been trying this for a long time.
Thanx in advance friends.
The code that I have been using is as follows.
using Facebook;
protected void CheckAuthorization()
{
string authorizationCode = Request.QueryString["code"];
string access_token = Facebook_GetAccessToken(authorizationCode);
FacebookShare(access_token);
}
private string Facebook_GetAccessToken(string pAuthorizationCode)
{
string urlGetAccessToken = "https://graph.facebook.com/oauth/access_token";
urlGetAccessToken += "?client_id=my app id";
urlGetAccessToken += "&client_secret=app secret";
urlGetAccessToken += "&redirect_uri=" + Facebook_GetRedirectUri();
urlGetAccessToken += "&code=" + pAuthorizationCode;
string responseData = RequestResponse(urlGetAccessToken);
if (responseData == "")
{
return "";
}
NameValueCollection qs = HttpUtility.ParseQueryString(responseData);
string access_token = qs["access_token"] == null ? "" : qs["access_token"];
return access_token;
}
protected void FacebookShare(string token)
{
if (token != null)
{
Int64 transactionid = Convert.ToInt64(Cache["transactionid"]);
string app_id = "my app id";
string app_secret = "app secret";
string scope = "offline_access,read_stream,publish_actions,publish_stream,manage_pages,status_update";
dynamic parameters = new ExpandoObject();
parameters.link = "my website link";
parameters.name = "my project name";
parameters.picture= "my website logo";
var client = new FacebookClient(token);
client.Post("/1374775846180409/feed", parameters); // this is my facebook page id where I want to share post.
Response.Cookies["transaction"].Expires = DateTime.Now;
}
else
{
}
}
Regarding above code, I am getting Facebook Authorization code successfully.
You can only ask your user who has logged into your app to post on facebook, apps as such are not allowed to post.
You will need a page access token to post as the page, which have permissions to modify the data belonging to a Facebook Page. To obtain a page access token you need to start by obtaining a user access token, for which your user has to be logged into your app and asking for the manage_pages permission scope. Next, you can GET /me/accounts, which will return a page access token for each page that you manage.
This can not be accomplished using offline access or without logging in.

Given URL is not allowed by the Application configuration on c# web browser

I am trying to integrate Facebook authentication into my Windows desktop application using Facebook C# SDK. I tried to have user login using Facebook with a WebBrowser in an area of my application window. The WebBrowser will always show Given URL is not allowed by the Application configuration.
What URL should I give to my App Setting? Because my application will not be on a web page and Facebook App Setting does not have Windows Desktop platform.
private Uri GenerateFBLoginUrl(string appId, string extendedPermissions)
{
// reference: "http://blog.prabir.me/posts/facebook-csharp-sdk-writing-your-first-facebook-application-v6"
// var parameters = new Dictionary<string,object>
// parameters["client_id"] = appId;
dynamic parameters = new ExpandoObject();
parameters.client_id = appID;
parameters.redirect_uri = "https://www.facebook.com/connect/login_success.html";
// The requested response: an access token (token), an authorization code (code), or both (code token).
parameters.response_type = "token";
// list of additional display modes can be found at http://developers.facebook.com/docs/reference/dialogs/#display
parameters.display = "popup";
// add the 'scope' parameter only if we have extendedPermissions.
if (!string.IsNullOrWhiteSpace(extendedPermissions))
parameters.scope = extendedPermissions;
// generate the login url
var fb = new FacebookClient();
return fb.GetLoginUrl(parameters);
}
private void FacebookLogin()
{
loginUrl = GenerateFBLoginUrl(appID, "id");
this.FBLogin.Navigate(loginUrl.AbsoluteUri);
}
I am not familiar with this but I have two suggestions: 1) if you pass a null string what happens? and 2) pass a arbitrary URL. Good luck.

Creating an album on a Page

I am trying to post make a album and upload photos to a page on facebook that I have administrative rights to. It works using my facebook account's ID found on Find my facebook ID but it doesn't work when I use my page's ID. This is my code for creating the album.
var facebookClient = new FacebookClient(Properties.Settings.Default.AccessToken);
dynamic parameters = new ExpandoObject();
parameters.name = AlbumName;
parameters.description = AlbumDescription;
parameters.uid = AlbumOwnerID;
var fbResult = facebookClient.Post(string.Format("/{0}/Albums", AlbumOwnerID), parameters);
And this is the error that I get.

(OAuthException) An active access token must be used to query information about the current user

I'm using Facebook C# sdk with the code,
i'm trying to create a new score for a user
but i get this error:
(OAuthException) An active access token must be used to query information about the current user.
what am i missing?
protected void btnAddScore_Click(object sender, EventArgs e)
{
if (CanvasAuthorizer.Authorize())
{
var fb = new FacebookWebClient();
dynamic parameters = new ExpandoObject();
parameters.score = 77;
parameters.access_token = GetAppAccessToken();
try
{
dynamic id = fb.Post("me/scores", parameters);
lblPostMessageResult.Text = "Message posted successfully";
txtMessage.Text = string.Empty;
}
catch (FacebookApiException ex)
{
lblPostMessageResult.Text = ex.Message;
}
}
}
private string GetAppAccessToken()
{
var oauthClient = new FacebookOAuthClient
{
AppId = FacebookWebContext.Current.Settings.AppId,
AppSecret = FacebookWebContext.Current.Settings.AppSecret
};
dynamic result = oauthClient.GetApplicationAccessToken();
string appAccessToken = result.access_token;
return appAccessToken;
}
edit:
I got the answer form here:
http://facebooksdk.codeplex.com/discussions/279307
the new right code is:
if (CanvasAuthorizer.Authorize())
{
var fb = new FacebookClient(CanvasAuthorizer.FacebookWebRequest.AccessToken);
var oauthClient = new FacebookOAuthClient(FacebookApplication.Current);
dynamic parameters = new ExpandoObject();
parameters.score = 100;
dynamic ac = oauthClient.GetApplicationAccessToken();
parameters.access_token = ac.access_token;
dynamic result = fb.Post(CanvasAuthorizer.FacebookWebRequest.UserId + "/scores", parameters);
}
Answer:-
Actually for using SCORE Graph API you need the "Application access token" which is different than a normal access token
So if you want your task to be done GET an Application access token by using the following script.......
And then replace the generated application_access_token with old access_token, that's it
The below code is written in php try convert it in c# and then apply it
$APPLICATION_ID = "APP_ID";
$APPLICATION_SECRET = "APP_SECRET";
$token_url = "https://graph.facebook.com/oauth/access_token?" .
"client_id=" . $APPLICATION_ID .
"&client_secret=" . $APPLICATION_SECRET .
"&grant_type=client_credentials";
$app_token = file_get_contents($token_url);
After getting this application access token you can easily do this task.
When You Need An Application Access Token
You need to use a Facebook application access token when you have a process that acts on behalf of the application, rather than on behalf of a particular user. This happens when you access your Facebook Insights data for your app via the graph, and also when you want to create test Facebook users for your app.
Sadly, the documentation for this is buried in the authentication guide for the Facebook graph API.
Your application need to take "publish_actions" permission from user to update the score.
Refer to Create or update a score for a user section of the below documentation.
https://developers.facebook.com/docs/score/

Categories