graph api post action on facebook from facebook c# sdk - facebook

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

Related

facebook long-live access using DotNetOpenAuth

i am creating an application in asp.net, which will use the user's facebook data using its api's,
but in order to access the Fb api's we need to perform the OAuth(2.0) first.
i did that too by using the DotNetOpenAuth library in the following code:
private static readonly FacebookClient client = new FacebookClient
{
ClientIdentifier = ConfigurationManager.AppSettings["fbAppID"],
ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ConfigurationManager.AppSettings["fbSecret"]),
};
protected void Page_Load(object sender, EventArgs e)
{
IAuthorizationState authorization = client.ProcessUserAuthorization();
if (authorization == null)
{
// Kick off authorization request
client.RequestUserAuthorization();
}
else
{
var req = WebRequest.Create("https://graph.facebook.com/oauth/access_token?client_id=" + ConfigurationManager.AppSettings["facebookAppID"] + "&client_secret=" + ConfigurationManager.AppSettings["facebookAppSecret"] + "&grant_type=fb_exchange_token&fb_exchange_token=" + Uri.EscapeDataString(authorization.AccessToken));
var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var graph = FacebookGraph.Deserialize(responseStream);
this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name);
}
}
}
}
my question here is, how can i get the long-lived access token of facebook using the DotNetOpenAuth library, so that user do not need to login again and again and i can store that somewhere.
please help me.
If possible use Facebook SDK for .Net to create access token for long time. may be 60 days.
using Facebook;
var cl = new FacebookClient(short_lived_access_token);
dynamic result = client.Post("oauth/access_token", new
{
client_id = "your app id",
client_secret = "your app secret",
grant_type = "fb_exchange_token",
fb_exchange_token = client.AccessToken
});
var long_lived_access_token = result.access_token;

Getting page details from Facebook account using App Access Token

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

twitter4j - get tweets by ID

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"

How to logout FaceBook in window phone 7

I have a problem logging out of Facebook on Windows Phone. I have the code to login, but I can't log out of it. Can someone show me how to log out of Facebook on a Windows Phone?
Here's the login code:
private FacebookClient _asyncFbClient;
private string _appID = "";
private string _appSecret = "";
private void StartFacebookLogin(object sender, RoutedEventArgs e)
{
string[] extendedPermissions = new[] { "user_about_me", "publish_stream", "email" };
FacebookClient fb = new FacebookClient();
var oauth = new FacebookOAuthClient { AppId = _appID, AppSecret = _appSecret };
var logout = new FacebookUser();
var parameters = new Dictionary<string, object>
{
{"response_type", "token"},
{"display", "touch"}
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
webBrowser.Navigated += new EventHandler<System.Windows.Navigation.NavigationEventArgs>(CheckForAuth);
webBrowser.Navigate(loginUrl);
}
private void CheckForAuth(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(e.Uri, out result))
{
if (result.IsSuccess)
{
IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
MessageBox.Show(result.AccessToken);
access = result.AccessToken;
if (Settings.Contains("MyFacebookAccessToken1"))
Settings["MyFacebookAccessToken1"] = result.AccessToken;
else
Settings.Add("MyFacebookAccessToken1", result.AccessToken);
Settings.Save();
_asyncFbClient = new FacebookClient(result.AccessToken);
_asyncFbClient.GetCompleted += new EventHandler<FacebookApiEventArgs>(_asyncFbClient_GetCompleted);
_asyncFbClient.GetAsync("/me");
}
}
}
Here's the logout code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(linkUrl);
request.Method = "GET";
request.BeginGetResponse(new AsyncCallback(LogoutResponse), request);
private void LogoutResponse(IAsyncResult result)
{
string responseData = "";
try
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
HttpWebResponse response = request.EndGetResponse(result) as HttpWebResponse;
if (response != null && response.StatusCode == HttpStatusCode.OK)
{
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
responseData = reader.ReadToEnd();
//responseData = true
}
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() => { MessageBox.Show(ex.Message); });
}
}
I have tried to use Facebook's logout API and get a successful result, but the next time I open the web browser it's already automatically logged in to Facebook again. How can I get it to log out?
I tried quite a few hacks to get this to work... and then Facebook finally updated their documentation with a good answer:
Logout
You can log a user out of their Facebook session by directing them to
the following URL:
https://www.facebook.com/logout.php?next=YOUR_URL&access_token=ACCESS_TOKEN
YOUR_URL must be a URL in your site domain, as defined in the
Developer App.
From http://developers.facebook.com/docs/authentication/
there is no FB Logout, it has been removed.
your best bet is to forget your credentials.
Facebook PHP SDK uses a function like this:
public function getLogoutUrl($params=array()) {
return $this->getUrl(
'www',
'logout.php',
array_merge(array(
'next' => $this->getCurrentUrl(),
'access_token' => $this->getAccessToken(),
), $params)
);
}
Which creates a URL like:
https://www.facebook.com/logout.php?next={YOUR_ENCODED_URL}&access_token={YOUR_ACCESS_TOKEN}
I believe the encoded URL must be owned by the application to whom the access_token belongs.
If you get that URL right, it'll work (just tried for one of my applications).
I'm not 100% sure if it works on windows-phone, but you can give it a try.

Facebook C# SDK 4.2.1 posting on wall problem

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