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.
Related
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/
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
im just going to dive straight in and give you a little background on what im trying to do, what i've tried, and the obstacles in my way. so here goes..
MY GOAL
To post to a facebook profile or wall from a desktop application.
The desktop application will be used by individual users who have their own facebook account.
The aim is to create each user their own facebook app and get the app id and app secret.
And then use the app id and app secret in the desktop application ( Saved somewhere in database or config )
to allow the user of the desktop application to post to their profile without having to enter their email address and password to login first
So in summary, 1 facebook app per facebook account.
The app settings will be saved in each users desktop application
Post to their own facebook via their own facebook app without logging in
The main emphasis here being that the user does not have to log in manually via a window or browser.
I have created my facebook app and have set it to live status.. i have also added in all possible permissions and extended permissions in the settings ( Within facebook ) just to make sure i wasnt missing anything.
So I do have my AppID and App secret.. I also have my Client Token which it says to use in place of the app secret for 'auth methods'. I use this to get my access token. I tried the app secret and it doesnt return the access token
MY ATTEMPTS :
C# FACEBOOK SDK
So, i started with and am still trying to use the c# sdk
I can retrieve my access token but cannot post.
I get he below errors all the time with whatever i try... these are just 2 of the many code examples i have tried.
(OAuthException - #2500) An active access token must be used to query information about the current user.
dynamic r = fb.Post("me/feed", new { message = "My seconds wall post using Facebook C# SDK" });
(OAuthException - #190) The client token cannot be used for this API
dynamic r = fb.Post("kevin.maguire.965/feed", new { message = "My second wall post using Facebook C# SDK" });
I read the following extract from the below link which states my access token is an app token and i need a access token for a user or page?
Need Help on OAuthException Code 2500
Error 2500 means you have no access token or an app access token but are trying to access /me/ - 'me' is a placeholder for 'current user or page ID' so won't be valid without an access token for a user or page
So, i have tried to get the userID back using the following Answer ( Facebook C# SDK Get Current User )
var fb = new FacebookClient("access_token");
dynamic result = fb.Get("me", new [] { fields = "id" });
var userId = result.id;
I get the access token which i assume is the app token and not the user token
dynamic result = fb.Get("oauth/access_token", new
{
client_id = this.ApplicationId,
client_secret = this.AppSecret,
grant_type = "client_credentials"
});
fb.AccessToken = result.access_token;
So i have no idea at this moment in time how to post to my profile
I am able to achieve the above using twitter where i can use the secret, token, id etc ... they provide and I can successfully post to my twitter account from a desktop application WITHOUT logging into my twitter account.
Another user has also found it quite easy to post to twitter without any real issues. ( facebook c# sdk getting started )
He also seems to have had success which i have not using the same code - this code was uses in June 2012 so there could have been breaking changes released since
then.
I got the message : (OAuthException - #2500) An active access token must be used to query information about the current user... when i used the sdk.
When i tried to get the access token using a web request and then pass that token to the sdk object to create a facebookclient i got this message
(OAuthException - #190) Invalid OAuth access token signature.
WebRequest request = WebRequest.Create("https://graph.facebook.com/oauth/access_token? grant_type=client_credentials&client_id=999999999999999&client_secret=edefefr8e09r8e08r080r8er0e");
request.Method = "POST";
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string accesstoken = reader.ReadToEnd();
MessageBox.Show("accesstoken")
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
var fb = new FacebookClient(accesstoken);
dynamic parameters = new ExpandoObject();
parameters.message = "test";
dynamic result = fb.Post("me/feed", parameters);
var id = result.id;
Obviously in the code above i changed the id and secret to dummy values.
So basically folks...the above links and above code are only a pinch of what I have tried to date in the last few days... i've basically ran out of options and am missing something here which could be averting my attention easily.. or maybe not :) i dont know.
If any one would even have a simple windows form, or wpf window application example using the c# sdk or using restsharp or just using WebRequest object with 'POST' method then I would be eternally greatful.
Just to iterate again that it is a desktop application and not ASP.net .
Many thanks folks for your attention and time.
From what I can see you are supplying an incorrect access token. Since you haven't provided the code with regards to obtaining the access token, may I suggest you take a look at this link which explains how to build a Facebook application, including obtaining an access token via a WebBrowser control.
EDIT: You are supplying the app access token but are trying to post as a user. For this operation you need a user access token which you can obtain by following the steps in the link above.
My WinForms app needs to access one of the Google API's (Calendar). For this, the app needs to have authorization, and Google has provided OAuth 2 for this purpose. I've read everything on their docs site here.
From another documentation page on Google I learned how to get the authorization key via a browser request. This takes place in a Console C# application. What it does is:
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
var service = new CalendarService(auth);
string id = <calendar id>;
Calendar calendar = service.Calendars.Get(id).Fetch();
At the last line, a browser window is opened with a Google page asking me to allow the app access to my Google account. In the console application, a ReadLine() is waiting for input. This comes from the GetAuthorization method:
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
So I grant my app access to my Gmail account, and I get a code in return. This code I paste back into the console window, and the rest of the app does its work as it should (in my case, making a new Calendar event).
But my problem is the fact that I want this functionality in a WinForms app, not a Console app. I have not been able to find anything on Google's pages regarding this.
What I have so far:
User clicks a button, the browser is opened and the user grants access and retrieves the code.
User pastes this code into the app.
Another button is clicked, and this is where I would like to use the user-entered code for the authorization process. This is a string, and I don't know how to combine this with all the authentication methods written in the top of this post.
I have a feeling it could be possible with the use of Google's REST client instead of the native .NET libraries, but I sincerely want to use the .NET libraries instead of REST.
Take a look at the AuthorizationMgr class and in particular at RequestNativeAuthorization method. It uses a LoopbackServerAuthorizationFlow class, which created a tcp listener for you and get the code from the incoming request.
You should also take a look at one of the samples that uses that mechanism (e.g. CreateTask sample)
I'm trying to use the Facebook SDK 5.2.1 to ultimately create a test user, however even what I believe is the simple example of getting the list of test accounts isn't working for me. I get the OAuthException "An access token is required to request this resource."
Here's my code (replace APP ID and APP SECRET with my own):
FacebookOAuthClient oauth = new FacebookOAuthClient { AppId = "APP ID", AppSecret = "APP SECRET" };
dynamic tokenRes = oauth.GetApplicationAccessToken();
fbClient = new FacebookClient(tokenRes.access_token);
dynamic response = fbClient.Get("APPID/accounts/test-users");
However, I get the exception on the fbClient.Get line.
Any idea as to what's wrong?
Thanks,
Chad
After hours of trying various things and reading various web pages/blogs, I found the reason it wasn't working. In my app settings, I had my app type set to a Native/Desktop App. Changing this to Web, allows the above scenario to work. I'm not yet quite sure of what other differences exist between web vs native facebook apps. My app is certainly only being used via a desktop application and I can't understand why I need to set this to Web just to allow me to create test users.
This code works in my app:
var app = new FacebookClient(FacebookApplication.Current.AppId,
FacebookApplication.Current.AppSecret);
dynamic result = app.Post(string.Format("{0}/accounts/test-users",
FacebookApplication.Current.AppId),
new { installed = true, permissions = "user_about_me" });
The reason why you are receiving the exception OAuthException is because you have not yet got the permission of the user.
To do a Graph API call on the current user, you need to get the user to accept the permissions that you require FIRST and then do the Graph API call.
You need to get the user to a browser some how in your application, as there is not an authentication flow which doesn't require a browser window.
Check out this URL to view the authentication flows:
http://developers.facebook.com/docs/authentication/