Still no solution how to simple post a Facebook wall - c#

I need to post a message from my personal website to the website´s facebook wall page. I dont want the user to authenticate against facebook, instead a default website account should be used(probably the facebook app).
This is what I have :
Created facebook App at https://developers.facebook.com
Add Facebook.dll to my ASP.NET webform site(the personal site)
Included the following code :
FacebookClient client = new FacebookClient();
result = client.Get("oauth/access_token", new
{
client_id = ConfigurationManager.AppSettings["FacebookAppId"],
client_secret = ConfigurationManager.AppSettings["FacebookAppSecret"],
grant_type = "client_credentials"
});
client.AccessToken = result.access_token;
result = client.Post("1418771281723422/feed", new { message = "Test Message from app" });
result = client.Get("1418771281723422");
This returns the following exception on client.Post
A first chance exception of type 'Facebook.FacebookOAuthException'
occurred in Facebook.dll
Additional information: (OAuthException - #200) (#200) The user hasn't
authorized the application to perform this action
What am I doing wrong and why is it so hard to do this simple task?

Of course you need to authorize a User to post on Facebook - else it would be incredibly easy to create a spam App.
What you need is a Page Access Token, take a look at the Facebook docs about the different Tokens and how to get them: https://developers.facebook.com/docs/facebook-login/access-tokens
More information about Access Tokens: http://www.devils-heaven.com/facebook-access-tokens/
The code is in PHP, but the text is valid for every language anyway.
This is how to generate an Extended Page Token with PHP: http://www.devils-heaven.com/extended-page-access-tokens-curl/
An Extended Page Token may be exactly what you need, it is valid forever and you can post "as Page" with it.
Doing this with ASP.NET should be pretty similar, but you don´t really need that Facebook SDK if you take a look at the tutorial for extending a Page Token with CURL. This question may help you: curl Request with ASP.NET
To create an Extended Page Token only for yourself, i suggest creating it without any coding:
Use the Graph API Explorer to create a User Access Token with your App.
Extend the User Access Token: https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=[app-id]&client_secret=[app-secret]&fb_exchange_token=[short-lived-token]
Put that resulting User Token in the "Access Token" field of the Graph API Explorer
Make a call to /me/accounts to get a list of all your Facebook Pages
Take the Access Token of your Page and use it in a server side call for posting
It´s explained in this article: http://www.devils-heaven.com/facebook-access-tokens/

Related

Facebook Application publish on facebook page

I want my facebook application to create events in my facebook page. Everyone that use my application will be able to publish events to my facebook page, so I don't want to give admin or contributor to everyone, I want my web app ( appId + secret code) to have the rights to publish
When I'm trying this:
client.AccessToken = "{app-id}|{app-secret}";
dynamic result = client.Post("/{page-id}/events", new{
name = "testEvent",
start_time = "2014-04-11T19:00:00-0700",
end_time = "2014-04-11T20:00:00-0700",
}
);
I received this error
{
"error": {
"type": "Exception",
"message": "You must be an admin of the specified page to perform the requested action.",
"code": 1373019
}
}
Any idea?
You should do the following:
Get a Page Access Token via the /me/accounts endpoint (the logged
in User must be the administrator of this page). You can do this via
https://developers.facebook.com/tools/explorer?method=GET&path=me%2Faccounts Be sure that you have requested the manage_pages, create_event and publish_stream permissions beforehand.
Exchange your short-lived Page Access Token to a non-expiring one as described here:
What are the Steps to getting a Long Lasting Token For Posting To a Facebook Fan Page from a Server
Use the newly generated Page Access Token in your App
The token that you are using is called the App Access Token, and according to the documentation of /{page-id}/events, it says:
An page access token for the page with create_event permission is required.
Now to get the page access token-
First you need to re-authenticate the user (by calling the facebook login/auth again) by adding the permissions:
manage_pages, required for getting the page access token
create_event, required for creating an event
Then make the call:
\GET /{page-id}?fields=access_token, you will get the page access token in response.
Use the token generated in step-2 and make the call you are making, then it will be a success.
(If required, you can also extend this page access token that will never expire- see here)
Learn more about access tokens here.

This API call requires a valid app_id asp.net c# - facebook

I want to post messages in my friends wall using a program. I will post the message using my asp.net application. I tried facebook's graph api. the problem is every time I have to use facebook provided login dialog to get the access token which requires manually enter username and password. Therefore I created a facebook app and obtained appid and app secret string. I am trying the below code to post a message in my wall first. I am getting the below exception.
var fb = new Facebook.FacebookClient();
dynamic tokenInfo =
fb.Get(
String.Format(
"/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials",
"1234567890",
"2bebebdf4709xxxxxxxxxxxxxxx"));
fb.Post("/100006xxxxxx/feed", new { message = "My Message" });
Error :
This API call requires a valid app_id
Your friend must authorize your app and they need to grant the "publish to feed" privilege to your app. To get this going, you need to have the user authorize your app via "Facebook Connect". Use Facebook Connect to trigger the "authorize your app" process. Once the app is authorized, the facebook api should recognize that your friend is logged into facebook (facebook api uses cookies to know that the user is logged into FB or not). Only then will issuing this command work. Hope this helps.
var fb = new FacebookClient(acctocken);
var args = new Dictionary<string, object>();
args["Message"] = "Hai Dear";
fb.PostAsync("[friend id]/feed", args);
Hope Its Help You

DropNet DropBox login, how to do it programmatically in a console application?

Question:
I'm using a DropBox csharp API from here:
https://github.com/dkarzon/DropNet
From the Unit tests, and the only working sample from here
https://github.com/dkarzon/DropNet/blob/master/DropNet.Samples/DropNet.Samples.Web/Default.aspx.cs
I figured that it works like this:
DropNet.DropNetClient client = new DropNet.DropNetClient(strApiKey, strAppSecret);
DropNet.Models.UserLogin login = client.GetToken();
client.UserLogin = login;
var accountInfo = client.AccountInfo();
str = accountInfo.quota_info.quota.ToString();
The probem is, it throws an exception on accountinfo. (System.Net.HttpStatusCode.Unauthorized)
Everything before works fine, I get the login (usertoken & usersecret) .
I think my problem is this part of the sample application:
var url = _client.BuildAuthorizeUrl(Request.Url.ToString() + "?dropboxcallback=1");
Response.Redirect(url);
Where it redirects to dropbox for a login...
I don't have a web application, so I have no URL...
What I have is a console application, that should make a backup of my database every evening automatically as a service, for which it certainly is very bad requiring a webbrowser and a user which has to type in email/username + password.
How can I do a login by directly supplying the hardcoded username and password ?
If I use the sample application, then it works, but that requires typing in the username and password on the web, and that sucks big time for a console application...
As far as I know from other API's (facebook, google, stack exchange etc.) you'll have to redirect your user to a webpage of Dropbox, where it will grant permissions to you to use it's account to perform things.
So in general it is not possible to achive this without a webbrower. Otherwise you'll have to perform really dirty hacks to hack arround the permission system of dropbox.
Please have a look at "OAuth 2.0 authorization flow" on google.
Here's a diagram I found at Yahoo which show's how it works:
For uisng the DropnetClient's 4 argument constructor also we need to build web based url and allow the user to authenticate his account this is compusory thing, accesstoken will generate after the user hit allow button in authentication process
As GameScripting explained the Dropbox API uses oauth which requires user login through the dropbox website to authenticate the access tokens.
Checkout the documentation here: http://dkdevelopment.net/what-im-doing/dropnet/ for the 3 step process.
What sort of application are you building? Normal process is to load a browser control inside the application and navigate to the login URL with it.
Also have a look at the sample Windows Phone app to give you an idea of how this process works: https://github.com/dkarzon/DropNet/blob/master/DropNet.Samples/DropNet.Samples.WP7/MainPage.xaml.cs
Instead of hardcoding the username and password, you can hardcode the OAuth access token.
First, create a simple program (using the same app key) that follows the standard browser-based authorization flow. Then use it to authorize the app with the desired user. This will give you an OAuth access token (a "token" and "token secret") associated with that user and your app key.
Then, in your service-style application, just hardcode the OAuth access token (using DropNetClient's 4-argument constructor).
It is possible, using SharpBox - tested, works.
One needs to acquire the AccessToken as a one-time-action manually, then after that, one can omit the login page and use the saved AccessToken.
http://www.jayway.com/2012/02/06/unboxing-dropbox-and-sharpbox-2/
The magic line is:
Globals.DropBox.Token = AppLimit.CloudComputing.SharpBox.StorageProvider.DropBox.DropBoxStorageProviderTools
.ExchangeDropBoxRequestTokenIntoAccessToken(
Globals.DropBox.config
, Globals.DropBox.AppKey, Globals.DropBox.AppSec
, Globals.DropBox.requestToken
);

facebook c# sdk getting started

I would like to write a console application that automatically posts information to my wall once every morning.
I have signed up for facebook developer and have a AppID and App Secret
I have been trying to play with the C# facebook SDK and looked through several examples.
Seems like the examples get a user token - but have to use a browser that is in windows forms. This is an automated process - so I dont want to have a user present.
Ive also created some examples using the application token - but it does not seem to be able to write to the wall.
I wrote the Twitter equivalent very quickly. I must be missing something here ???
What is the proper way to proceed?
It seems that all I should need to is:
FaceBookClient(appID, appSecret)
and then just
FaceBookClient.Put(message)
???
clarification added:
Playing with the C# facebook sdk winform application
I had to change their FacebookLoginDialog.cs to use the folling URL:
https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=APPID&client_secret=APPSECRET&scope=user_about_me,publish_stream,offline_access
which returns an accesskey in WebBrowser.DocumentText
If I then call:
var fb = new FacebookClient(_accessToken);
dynamic parameters = new ExpandoObject();
parameters.message = "Hello World!";
dynamic result = fb.Post("me/feed", parameters);
I get the exception:
(OAuthException) An active access token must be used to query information about the current user.
If I change the code above to NOT use that access token - but use the appID and Appsecret:
FacebookClient myFacebookClient = new FacebookClient("APPID", "APPSECRET");
dynamic parameters = new ExpandoObject();
parameters.message = "Hello World!";
dynamic result = myFacebookClient.Post("me/feed", parameters);
Then I get the exception:
(OAuthException) An active access token must be used to query information about the current user.
I guess it is the same exception
Here is what I found.
Download the facebook C# sdk source code and samples from http://facebooksdk.codeplex.com/
Unzip the code and load into Visual Studio the Facebook C# SDK sample called CS-WinForms.
At the top of Form1.cs - enter your application ID
Run the application.
Form1.cs pops up with a button "Login to Facebook". Click the button.
FacebookLoginDialog.cs pops up with a browser window in it displaying facebook asking for permissions.
FacebookLoginDialog.cs creates a browser window that will go to your user on facebook and request permissions. By default those permissions are: user_about_me,publish_stream,offline_access.
Offline_access means the AccessToken you get - never expires
Click "OK" in Facebook to allow the application to access your facebook data.
FacebookLoginDialog.cs should find that you logged in and get the access token that never expires.
The access token is a string.
Insert a break point so that you can copy this access token. Save this access token as you can use it from now on to access to Facebook.
Facebook developers website has some tools that you can use to check the access token
https://developers.facebook.com/tools/debug/access_token
You can enter your access token and click "Debug" and it should list your applicationID, UserID, and for "expires" it should say "never".
Once you have this access token - then you can simply write code like:
var fb = new FacebookClient(AccessToken);
dynamic parameters = new ExpandoObject();
parameters.message = FacebookString;
dynamic result = fb.Post("me/feed", parameters);
var id = result.id;
to post message to Facebook!
You should request offline_access in addition to publish_stream. Once you have the never-expiring token, store that in your app.

Console apps and extended permission offline_access workflow

I'm trying to get the Facebook C# SDK to work with offline_access and a console application.
From what I understand, I have to:
Ask for auth for offline_access - that's easy.
Get the "code" that is returned by FB when the user authorizes offline_access
Use ExchangeCodeForAccessToken to get a valid access token each time
I can't figure out how to grab the code in (2) though?
Thanks
Getting the "code" and exchanging the code for a token is something you usually do if you are doing authentication in a server-side workflow. It may be a bit of a red herring in your scenario. There are easier ways to just get the access token directly.
It would help to have more context (including code) showing how you are getting offline_access (javascript, server-side OAuth, ...?)
When you get offline_access via the Javascript SDK, which in my opinion provides the best user experience, you will get the access token back in the response from Facebook:
FB.login(function (response) {
if (response.session) {
if (response.perms) {
var accesstoken = response.session.access_token;
// do something with the token...save it, use it, etc.
} else {
// re-prompt for permissions
}
}
}, { perms: 'offline_access' });
Once you have it in javascript you can stuff it into a hidden form field, put it in an ajax post to your server, or whatever.
Note that in my experience you do not actually need the saved user access token to do offline api calls for all api methods. You can just use an app access token in some cases, and Facebook will let it fly if you have offline_access and the other required permissions. They did post a developer blog post in the last week stating you need a token for some api calls where it was not previously required, so that might be changing.
Also be aware that these tokens can go bad. For example if the user changes their Facebook account password it invalidates all access tokens. So it is good to test them, catch OAuth exceptions, and have a way to bring this to the user's attention to re-prompt for permissions and get a new access token.
After the user grants you the "offline_access" permission, Facebook will redirect the user to your application URL with a "code" query string parameter. You need to grab this "code" query string parameter.
Then, make another WebRequest using this "code" value to get the access token. Use the following URL to make the request:
https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}
The WebResponse can be parsed like this:
NameValueCollection qs = HttpUtility.ParseQueryString(response);
token = qs["access_token"];
You need to persist the token in a database for use in your console application.

Categories

Resources