Hello i have a problem when i try to post something on users wall. here is my code
protected void Page_Load(object sender, EventArgs e)
{
app = new FacebookApp();
auth = new CanvasAuthorizer(app);
auth.Perms += "user_about_me,publish_stream,create_event,offline_access";
if (auth.IsAuthorized())
{
Response.Write("authorized " + app.Session.UserId.ToString()+" "+app.Session.AccessToken + "<br/>");
dynamic rez = app.Get("me");
Response.Write(rez.first_name + " "+rez.last_name);
}
else
Response.Write("not authorized ");
}
protected void btnPost_Click(object sender, EventArgs e)
{
dynamic parameters = new ExpandoObject();
parameters.message = "Check out this funny article";
parameters.link = "http://www.example.com/article.html";
parameters.picture = "http://www.example.com/article-thumbnail.jpg";
parameters.name = "Article Title";
parameters.caption = "Caption for the link";
parameters.description = "Longer description of the link";
parameters.actions = new
{
name = "View on Zombo",
link = "http://www.zombo.com",
};
parameters.privacy = new
{
value = "ALL_FRIENDS",
};
parameters.targeting = new
{
countries = "US",
regions = "6,53",
locales = "6",
};
dynamic result = app.Api("/me/feed",parameters);
}
when i try to post i get the :
(OAuthException) An active access token must be used to query information about the current user.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Facebook.FacebookOAuthException: (OAuthException) An active access token must be used to query information about the current user.
P.S.
dynamic rez = app.Get("me");
Response.Write(rez.first_name + " "+rez.last_name);
is working with no problems!
Thanks in advance.
That is because you have not given it access token try putting
FacebookApp app = new FacebookApp("my_access_token");
at top of post button event and replace
dynamic result = app.Api("/me/feed",parameters);
with
dynamic result = app.Post("me/feed", parameters);
Related
I am stuck into a problem for which I have not found any solution or documentation.
I am building an app using Facebook API in which user will create an app and will give their APP ID & APP SECRET to the application in order to create pages or post to pages.
Now the problem is they will only login into my application not in facebook nor login using FB.
I am getting APP ACCESS TOKEN from APP ID & APP SECRET.
Using https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=client_credentials
But how could i use it to get pages for that account or generate USER ACCESS TOKEN from it?
Please help me with your expert guidance.
Thanks.
You cannot create Apps nor Pages by using the Graph API! See https://developers.facebook.com/docs/graph-api/reference/v2.0/page
If you want to publish to a Page the logged-in User administrers, you can request the respective Page Access Token (with publish_actions and manage_pages permissions!) via
GET /me/accounts
See
https://developers.facebook.com/docs/graph-api/reference/v2.0/user/accounts/
https://developers.facebook.com/docs/facebook-login/access-tokens#pagetokens
first of create developer apps and get token give some permission
public ActionResult Index()
{
var url = "http://www.facebook.com/v2.0/dialog/oauth/?scope=user_friends,read_friendlists,read_stream,read_insights,manage_pages,user_checkins,user_photos,read_mailbox,manage_notifications,read_page_mailboxes,email,user_videos,user_groups,offline_access,publish_actions,manage_pages&client_id=" + ConfigurationManager.AppSettings["ClientId"] + "&redirect_uri=" + ConfigurationManager.AppSettings["RedirectUrl"] + "&response_type=code";
return Redirect(url);
}
that automatic redirect call back url for example
public ActionResult AddFacebookAccount(string code)
{
string ret = string.Empty;
string client_id = ConfigurationManager.AppSettings["ClientId"];
string redirect_uri = ConfigurationManager.AppSettings["RedirectUrl"];
string client_secret = ConfigurationManager.AppSettings["ClientSecretKey"];
long friendscount = 0;
try
{
FacebookClient fb = new FacebookClient();
string profileId = string.Empty;
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters.Add("client_id", client_id);
parameters.Add("redirect_uri", redirect_uri);
parameters.Add("client_secret", client_secret);
parameters.Add("code", code);
JsonObject fbaccess_token = null;
try
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
fbaccess_token = (JsonObject)fb.Get("/oauth/access_token", parameters);
}
catch (Exception ex)
{
try
{
fbaccess_token = (JsonObject)fb.Get("/oauth/access_token", parameters);
}
catch (Exception ex1)
{
ViewBag.acc_tkn= "issue_access_token";
}
}
string accessToken = fbaccess_token["access_token"].ToString();
Session["AccessToken"] = accessToken;
if (accessToken != null)
{
fb.AccessToken = accessToken;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
dynamic profile = fb.Get("v2.2/me");
dynamic friends = fb.Get("v2.2/me/friends");
try
{
Session["uid"] = profile.id;
friendscount = Convert.ToInt16(friends["summary"]["total_count"].ToString());
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
ViewBag.acc_tkn = accessToken;
ViewBag.Uid = profile.id;
}
return View();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
ViewBag.acc_tkn= "Something Went Wrong";
return View();
}
}
you will get access Token when post data on page refer Bellow Code
public void FacebookPostonPage(string file, string message, string tokenid)
{
JsonObject fbaccess_token = null;
FacebookClient fb = new FacebookClient();
fb.AccessToken = tokenid;
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
fbaccess_token = (JsonObject)fb.Get("v2.0/me/accounts");
dynamic Result = fbaccess_token["data"];
foreach (var obj in Result)
{
string result = FacebookComposeMessage(obj.access_token, obj.id, message, file);
}
}
public string FacebookComposeMessage(string tokenid,string userid ,String message,string imagepath)
{
FacebookClient fb = new FacebookClient();
string ret = "";
fb.AccessToken = tokenid;
fb.AppId = ConfigurationManager.AppSettings["ClientId"];
fb.AppSecret = ConfigurationManager.AppSettings["ClientSecretKey"];
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
var args = new Dictionary<string, object>();
args["message"] = message;
if (!string.IsNullOrEmpty(imagepath))
{
var media = new FacebookMediaObject
{
FileName = "filename",
ContentType = "image/jpeg"
};
byte[] img = System.IO.File.ReadAllBytes(imagepath);
media.SetValue(img);
args["source"] = media;
ret = fb.Post("v2.0/" + userid + "/photos", args).ToString();
}
else
{
ret = fb.Post("v2.0/" + userid + "/feed", args).ToString();
// ret = fb.Post("/" + objFacebookAccount.FbUserId + "/photos", args).ToString();
// var data = fb.Get("v2.2" + ret);
}
return ret;
}
You will post Successfully try now
I know these facebook api stuffs are really became a pain in the ass, after from my longer searches on internet, I could only find a message post API to facebook. I just want to modify it for both message and image posting. Here is relevant code which posts a message to facebook.(Windows Phone 7)
private void PostToWall_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(txtMessage.Text))
{
MessageBox.Show("Enter message.");
return;
}
var fb = new FacebookClient(_accessToken);
fb.PostCompleted += (o, args) =>
{
if (args.Error != null)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(args.Error.Message));
return;
}
var result = (IDictionary<string, object>)args.GetResultData();
_lastMessageId = (string)result["id"];
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show("Message Posted successfully");
txtMessage.Text = string.Empty;
btnDeleteLastMessage.IsEnabled = true;
});
};
var parameters = new Dictionary<string, object>();
parameters["message"] = txtMessage.Text;
fb.PostAsync("me/feed", parameters);
}
and I have also found a image post code, but I could not integrate it into my code. I think methods are not appropriate with each other.
Here is image post code;
var photo = new WriteableBitmap(0, 0).FromResource("Background200x200.jpg");
FacebookClient app = new FacebookClient();
IDictionary<string, object> parameters = new Dictionary<string, object>();
parameters["access_token"] = _facebookAccessToken; //set in another method where I authenticate...
parameters["name"] = "my picture";
parameters["message"] = "this is a picture uploaded from my the facebook sdk";
var mediaObject = new FacebookMediaObject {
FileName = "Background200x200.jpg",
ContentType = "image/jpeg",
};
mediaObject.SetValue(photo.ToByteArray());
parameters["source"] = mediaObject;
app.ApiAsync(
UploadComplete,
null,
"https://graph.facebook.com/me/feed",
parameters,
HttpMethod.Post);
I just want to post an image with a message. And If you can give me a sample link which posts an image to facebook (I ve been seeking for a ready-coded image post application,that is, Visual studio solution file which I can compile it and XAP it, and run on my phone)
or If you can help me to evolve my message poster to image poster, I would be really pleasured.
THANKS
How can I get the tweets when I have the tweet ID and the user ID ? I have a file containing lines like :
userID tweetID
I guess I should go by :
Query query = new Query("huh ?");
QueryResult result = twitter.search(query);
List<Status> tweets = result.getTweets();
but I have no clue how to spell the query
Thanks
Well it was no search call. The tweet apparently is called Status and the code to retrieve one by ID is :
final Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
AccessToken accessToken = new AccessToken(TWITTER_TOKEN,
TWITTER_TOKEN_SECRET);
twitter.setOAuthAccessToken(accessToken);
try {
Status status = twitter.showStatus(Long.parseLong(tweetID));
if (status == null) { //
// don't know if needed - T4J docs are very bad
} else {
System.out.println("#" + status.getUser().getScreenName()
+ " - " + status.getText());
}
} catch (TwitterException e) {
System.err.print("Failed to search tweets: " + e.getMessage());
// e.printStackTrace();
// DON'T KNOW IF THIS IS THROWN WHEN ID IS INVALID
}
The accepted answer is no longer valid. Based on the answer in this page, the code should be changed to the following:
String consumerKey = xxxxxxx,
consumerSecret = xxxxxxx,
twitterAccessToken = xxxxxxx,
twitterAccessTokenSecret = xxxxxxx,
Tweet_ID = xxxxxxx;
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(consumerKey);
builder.setOAuthConsumerSecret(consumerSecret);
Configuration configuration = builder.build();
TwitterFactory factory = new TwitterFactory(configuration);
final Twitter twitter = factory.getInstance();
//twitter.setOAuthConsumer(consumerKey, consumerSecret);
AccessToken accessToken = new AccessToken(twitterAccessToken, twitterAccessTokenSecret);
twitter.setOAuthAccessToken(accessToken);
try {
Status status = twitter.showStatus(Long.parseLong(Tweet_ID));
if (status == null) { //
// don't know if needed - T4J docs are very bad
} else {
System.out.println("#" + status.getUser().getScreenName()
+ " - " + status.getText());
}
} catch (
TwitterException e) {
System.err.print("Failed to search tweets: " + e.getMessage());
// e.printStackTrace();
// DON'T KNOW IF THIS IS THROWN WHEN ID IS INVALID
}
A very easy way to get a list of tweets by their ID is to use the lookup function like this:
public static void main(String[] args) throws TwitterException {
ConfigurationBuilder cfg = new ConfigurationBuilder();
cfg.setOAuthAccessToken("key");
cfg.setOAuthAccessTokenSecret("key");
cfg.setOAuthConsumerKey("key");
cfg.setOAuthConsumerSecret("key");
Twitter twitter = new TwitterFactory(cfg.build()).getInstance();
long[] ids = new long [3];
ids[0] = 568363361278296064L;
ids[1] = 568378166512726017L;
ids[2] = 570544187394772992L;
ResponseList<Status> statuses = twitter.lookup(ids);
for (Status status : statuses) {
System.out.println(status.getText());
}
}
The advantage of using lookup is that you can get with a sigle call up to 100 tweets, this means that if you have to download a big number of tweets you will need to do a lot less calls to the twitter API and speed up the process (this is because twitter limits the number of calls you can do).
You can even check the number of calls that you can do before twitter puts you in timeout like this:
RateLimitStatus searchLimits = twitter.getRateLimitStatus("statuses").get("/statuses/lookup");
int remain = searchLimits.getRemaining();
int limit = searchLimits.getLimit();
int secToReset = searchLimits.getSecondsUntilReset();
System.out.println(remain); // this returns the number of calls you have left
System.out.println(limit); // this returns how many calls you have max(this is a fixed number)
System.out.println(secToReset); // this returns the number of second before the reset
// after the reset you return to have the number of calls specified by "limit"
I am trying to make an action to be posted on facebook but I am getting an error " OAuthException) Error validating application. Invalid application ID "
here is my code :
var fb = new FacebookClient("TesterAccessToken");
dynamic parameters = new ExpandoObject();
parameters.dyno_run = "http://samples.ogp.me/3153962321975196100";
parameters.appnamespace = "NameSpace";
parameters.action = "comment";
parameters.object_name = "nice_image";
parameters.object_url = "MyURL";
try
{
dynamic result = fb.Post("me/", parameters);
}
catch (FacebookApiException ex)
{
}
I am posting on wall using below code on friend's wall
Facebook.Web.FacebookWebClient client = new Facebook.Web.FacebookWebClient(accesstoken);
dynamic parameters = new ExpandoObject();
parameters.message = "";
parameters.link = link;
parameters.name = name;
parameters.caption = caption;
parameters.description = desc;
parameters.from = fromId;
object resTest = client.Post("/" + friendId + "/feed", parameters);
You can post on your wall by using
object resTest = client.Post("/me/feed", parameters);
Hi Im writing an app that allows users to post status updates from within the application, I believe that ive got the authentication working correctly for the login, I just dont know how to go about posting a status update. Any code/examples/tutorials of how to go about doing this would be fantastic, here is the code that I have so far for the authentication.
public partial class FacebookAuth : PhoneApplicationPage
{
private string _accessToken;
private WebBrowser _webBrowser;
public FacebookAuth()
{
InitializeComponent();
_webBrowser = new WebBrowser();
this.Loaded += new RoutedEventHandler(FacebookAuthPage_Loaded);
}
void FacebookAuthPage_Loaded(object sender, RoutedEventArgs e)
{
//Get this from the facebook
string appId = "XXXXXXXXXXXXXXX";
string[] extendedPermissions = new[] { "publish_stream", "offline_access", "user_groups" };
var oauth = new FacebookOAuthClient { AppId = appId };
//Telling the Facebook that we want token as response
//and we are using touch enabled device
var parameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "touch" }
};
//If there's extended permissions build the string and set it up
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
//Create the login url
var loginUrl = oauth.GetLoginUrl(parameters);
//Add webBrowser to the contentPanel
ContentPanel.Children.Add(_webBrowser);
_webBrowser.Navigated += webBrowser_Navigated;
//Open the facebook login page into the browser
_webBrowser.Navigate(loginUrl);
}
void webBrowser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
//Try because there might be cases when user input wrong password
if (FacebookOAuthResult.TryParse(e.Uri.AbsoluteUri, out result))
{
if (result.IsSuccess)
{
_accessToken = result.AccessToken;
MessageBox.Show(_accessToken);
//Hide the browser controller
_webBrowser.Visibility = System.Windows.Visibility.Collapsed;
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
MessageBox.Show(errorReason + " " + errorDescription);
}
}
}
private void PostBtn_Click(object sender, RoutedEventArgs e)
{
}
}
}
To publish a status, do an HTTP Post to /me/feed with a post parameter called "message" and it's value being what the authenticate user posted.
Using FacebookClient
var client = new FacebookClient(user_access_token);
dynamic parameters = new ExpandoObject();
parameters.message = "Hello World!"
dynamic post_id = client.Post("/me/feed", parameters);
See also: http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx