I am a danish programmer living in Bangkok.
Read more about me @ rasmus.rummel.dk.
Webmodelling Home > Social Media > Interacting with Facebook API using C#
Do good

Facebook API C# Examples

Updated Nov 2012. Facebook API tutorial in C# - writing to a users facebook wall step-by-step with source code.

Just as I was dusting off my old facebook account trying to grasp what social media was all about destiny would it that one of Favourite Design's customers wanted to integrate their comment & blog system with Facebook. Rather than having one of our already over worked programmers to figure it out, I thought I would do it myself (for once) and also I figured that it would be interesting if my Discussions Forum & Comments WebControl directly supported Facebook integration.

Integrating a blog or a website with Facebook turned out not to be all that difficult - just follow the 5 steps below (only 3, 4 & 5 are necessery) and you will have your website write to users facebook walls in no time.

  1. Concepts
  2. Proof of concept - Try it out - write to your facebook wall and list your friends
  3. Create a Facebook application
  4. Setup localhost development - more convenient
  5. Write to Facebook wall - finally & with full code

Concepts

Facebook user objects and their relationships are normally referred to as a social graph, see Wikipedia on socal graph, however if including not only the user objects and their relationships but also the users photos, messages etc. and their relationships, then this is an expansion of the social graph concept and the whole is normally referred to as an open graph.

Facebook API makes it possible to interact with the Facebook open graph and is therefore often referred to as Open Graph API or just Graph API.

Then interacting with the Facebook API, that is: interacting with facebook users and their objects, you need to do so through a Facebook Application. This facebook application is one that you have to create @ facebook (see below how to do that). Then you request Facebook users for permissions to interact with their objects, the users are actually giving these permissions to your Facebook App, not to you - therefore then interacting with a Facebook users objects, your code will always need to authenticate as your Facebook App (since permissions are given to your Facebook App).

For Authentication & Authorization Facebook is following the OAuth 2.0 protocol. Permissions granted by Facebook users (to your Facebook App) will translate into an OAuth access token (which is a string obtainable by your C# code). Here is a logic step-by-step illustration of what happens :

  1. A person here called Rasmus lands on this page, facebook-api.aspx.
  2. Rasmus writes "Test" into the textarea field below and press the submit button.
  3. Upon postback facebook-api.aspx redirect Rasmus browser to Facebook to let Facebook prompt Rasmus to authorize Webmodelling publish_stream access (public stream access allows a Facebook App to write to a users Facebook wall).
  4. If Rasmus is not currently logged on to Facebook, Facebook do not know who the person is and presents a Facebook login page.
  5. After Rasmus login, Facebook see if Rasmus have earlier authorized the Webmodelling App publish_stream access.
  6. If Rasmus have not earlier authorized the Webmodelling App publish_stream access, then Facebook will present a new page asking whether Rasmus want to authorize publish_stream access to the Webmodelling App.
  7. Facebook will redirect Rasmus browser back to facebook-api.aspx and if Rasmus authorized or have earlier aurhorized publish_stream access to the Webmodelling App, then Facebook will add a code key to the querystring.
  8. The C# code for facebook-api.aspx can then use that code key value to request an access token from Facebook. The access token returned by Facebook specifies permission scope (publish_stream) for a specific user (Rasmus) for a specific Facebook application (Webmodelling) as well as a time limit the access token is valid.
  9. With the access token, the C# code of facebook-api.aspx can now interact with the Facebook API eg. to post a message on Rasmus Facebook wall.

Try it out

As a proof of concept, I have created 2 live try-outs of the exact code we are going through in this tutorial. The try-outs are not only fun, but you will also be able to see the OAuth authorization process live (the full process is available only first time you try, if you want to see the full process again, you will need to de-authorize the webmodelling App in your facebook account).

  • Write to your own Facebook wall

    Write some test text in the textarea below, press the submit button and follow the process.

  • List your Facebook friends

    Just press the submit button (if you have already done the above test, authorization will be skipped and you will get your friend list immediately).


How to create a Facebook application

Then interacting with the Facebook API, you do so through a Facebook Application. The most important elements of a Facebook Application is :

  • App Name : a descriptive name, eg. Webmodelling.
  • App URL : eg. http://webmodelling.com/ (the application cannot be used outside of the urls domain)
  • App ID : publicly available and must be submittet to Facebook each time you interact with the Facebook API.
  • App Secret : not publicly available but must be submittet to Facebook each time you need to create an access_token.

If you do not yet have a Facebook Application, you need to create one. Creating a Facebook Application is a very fast procedure, just follow the steps below :

  1. Navigate your browser to https://developers.facebook.com and press the "Log In" link.
  2. After login press the "Apps" link.
  3. If you have any Apps, the first App is default selected. Press the "Create New App" button.
  4. In the "Create New App" dialog, write an appropriate name for your Facebook Application (here I named it MyAppName) and press the Continue button.
  5. You need to pass a Captcha (to avoid automated app creations).
  6. After passing the Captcha, you can set properties for your new App, we only need to set 1 property, the App Url which in our case is called "Site URL" under "Website with Facebook Login" (the Facebook App is now valid if it is used from "Site URL", in my case if used from http://webmodelling.com). Press the "Save Changes" button to save the App.
  7. The Facebook App is now saved and available across the world in a couple of minutes. Press the "Apps" link to get to your App list with your new App default selected - just to get an overview.
  8. Overview of your Facebook Apps.

Congratulations - you now have a Facebook Application that you can use to interact with the Facebook API doing all sorts of things with other peoples objects. However before we continue to do the actual code, we better setup support for developing on localhost, see next.


Setup localhost development

Then developing your Facebook integration, most likely you are developing on localhost, therefore you need a way to have Facebook approving your Facebook application on your localhost - luckily Facebook have made it easy : What Facebook does then validate an API request is to parse out the domain from the url referer of the API request and match the domain against domains allowed for the Facebook App that the API request belongs to. As you can set any domain name in the url referer of an http request, you don't need to setup a real global domain. The most easy solution is to :

  1. In your Facebook App set the App Domain property to YourDomain.com (in my case webmodelling.com), this way Facebook will allow your API requests to come from any subdomain of YourDomain.com :
    1. Login to https://developers.facebook.com and navigate to Apps.
    2. Select the App you want to use for integrating with Facebook API (in my case it is Webmodelling) and click on "Edit Settings".
    3. Under basic settings set "App Domains" to YourDomain.com (in my case webmodelling.com) and press the "Save" button. Facebook will now allow an API request to come from any subdomain of YourDomain.com (you will still need to authenticate using AppID & AppSecret of course).
  2. In your c:\windows\system32\drivers\etc\hosts file to add the following line :
    • 127.0.0.1    develop.YourDomain.com : your browser will now match develop.YourDomain.com to localhost.
  3. Setup your IIS to map develop.YourDomain.com to your website, eg. if your website is an application under Default website, then Default website must be mapped to develop.YourDomain.com :
    1. Launch IIS
    2. Right click on Default website (or wherever your website is located) to open the "Edit Bindings" dialog.
    3. Add develop.YourDomain.com to port 80 (in my case YourDomain is webmodelling).
  4. Everytime you launch your development application in your browser, you need to substitute the "localhost" part with "develop.YourDomain.com", like this :
    • http://localhost/_webmodelling/webmodelling/WebmodellingWeb/webbits/socialmedia/facebook-api.aspx
    • http://develop.YourDomain.com/_webmodelling/webmodelling/WebmodellingWeb/webbits/socialmedia/facebook-api.aspx

Congratulations : you are all set to develop Facebook integration on your localhost.


Write to Facebook wall - full code

Finally we are ready to start! Follow the steps below and/or download the FBWrite C# Code (if downloading the code, you still need to perform step 1, 2 & 3).

  1. Add you Facebook application AppID & AppSecret to you web.config file :
    <appSettings>
        <add key="facebook:AppId" value="YourAppID"/>
        <add key="facebook:AppSecret" value="YourAppSecret"/>
    </appSettings>
    
  2. Create a new C# .aspx page called fbwrite.aspx
  3. In fbwrite.aspx insert the following :
    <asp:TextBox ID="tbMessage" runat="server" TextMode="MultiLine" Rows="5" Columns="30"></asp:TextBox>
    <br /><asp:Button ID="btnSubmit" runat="server" Text="Send to my Facebook" OnClick="btnSubmit_Click" />
    
  4. In fbwrite.aspx.cs insert the following at the top of the page above the class definition :
    using System;
    using System.Web;
    using System.Net;
    using System.IO;
    using System.Configuration;
    using System.Collections.Specialized;
    
  5. In fbwrite.aspx.cs insert the following class globals :
    string facebook_urlAuthorize_base = "https://graph.facebook.com/oauth/authorize";
    string facebook_urlGetToken_base = "https://graph.facebook.com/oauth/access_token";
    string facebook_AppID = ConfigurationManager.AppSettings["facebook:AppID"];
    string facebook_AppSecret = ConfigurationManager.AppSettings["facebook:AppSecret"];
    
  6. In fbwrite.aspx.cs insert the following in Page_Load :
    if (!IsPostBack) 
    {
    	if (Request["code"] != null) 
    	{
    		//After this page have redirected the users browser to Facebook asking to be authorized to write to the
    		//users wall, Facebook will redirect back to this page and if authorized having a "code" key in the querystring
     
    		//Since we have a code we got authorized and can now
    		//1) get an access_token
    		//2) use the access_token to write to the users Facebook wall
    		string authorizationCode = Request["code"];
    		string access_token = Facebook_GetAccessToken(authorizationCode);
    		if (access_token == "")
    		{
    			Response.Write("Could not get access_token");
    			return;
    		}
    		Facebook_WriteWall(access_token, (string)Session["Message"]);
    	}
    }
    
  7. In fbwrite.aspx.cs create the button handler, btnSubmit_Click :
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
    	string message = tbMessage.Text;
     
    	//necessary to save the message in a session since under the authentication & authorization process we are going to loose ViewState
    	Session["message"] = message;
     
    	Facebook_AuthorizeApplication();
    }
    
  8. In fbwrite.aspx.cs create the Facebook_AuthorizeApplication() procedure :
    private void Facebook_AuthorizeApplication()
    {
    	//In this function we ask the user to authorize our Facebook application using an authorization request url
     
    	//the authorization request url need to be appended
    	//1) Our AppID
    	//2) The permission scope (here publish_stream)
    	//3) A Url that Facebook can redirect the users browser to then Facebook is finish asking the user whether permission can be granted
     
    	string scope = "publish_stream"//see: http://developers.facebook.com/docs/authentication/permissions/ for extended permissions
    	string urlAuthorize = facebook_urlAuthorize_base;
    	urlAuthorize += "?client_id=" + facebook_AppID;
    	urlAuthorize += "&redirect_uri=" + Facebook_GetRedirectUri();
    	urlAuthorize += "&scope=" + scope;
     
    	//redirect the users browser to Facebook to ask the user to authorize our Facebook application
    	Response.Redirect(urlAuthorize, true); //this cannot be done using WebRequest since facebook may need to show dialogs in the users browser
    }
    

    After the users browser is redirected to urlAuthorize :

    1. Facebook will first check if the user is logged in with facebook and if not then display a login dialog to authenticate the user.
    2. After the user is authenticated (using either facebook cookie on the users browser or using the login dialog), Facebook will check if the user have already granted Webmodelling access to the requested resources and if not then display a dialog letting the user decide whether to grant permission or not.
    3. After Facebook knows if the user want to authorize our Facebook application the requested permission scope, Facebook will redirect the users browser back to our website using the redirect_uri and in case we were authorized Facebook have appended the redirect_uri with a querystring code key containing the access_token.
  9. In fbwrite.aspx.cs create the Facebook_GetAccessToken() procedure :
    private string Facebook_GetAccessToken(string pAuthorizationCode)
    {
    	//In this function we use the authorization code from before to obtain an access_token.
    	//The access_token can be used to request resources from a specific user within the authorized permission scope
    		
    	//The access_token request url need to be appended
    	//1) Our AppID
    	//2) Our AppSecret
    	//3) The exact same redirect_uri that was used before then authorized
    	//4) The authorization code we just got from Facebook
     
    	string urlGetAccessToken = facebook_urlGetToken_base;
    	urlGetAccessToken += "?client_id=" + facebook_AppID;
    	urlGetAccessToken += "&client_secret=" + facebook_AppSecret;
    	urlGetAccessToken += "&redirect_uri=" + Facebook_GetRedirectUri();
    	urlGetAccessToken += "&code=" + pAuthorizationCode;
     
    	string responseData = RequestResponse(urlGetAccessToken); //we write RequestResponse a little later
    	if (responseData == "")
    	{
    		return "";
    	}
    	NameValueCollection qs = HttpUtility.ParseQueryString(responseData);
    	string access_token = qs["access_token"] == null ? "" : qs["access_token"];
     
    	return access_token;
    	//(The access_token is valid only from within the site domain specified for our Facebook application)
    }
    
  10. In fbwrite.aspx.cs create the Facebook_WriteWall() procedure :
    private void Facebook_WriteWall(string pAccessToken, string pMessage)
    {
    	//In this function we will write to the users Facebook wall by posting the message through the Facebook Graph API
     
    	//The post url need to be appended :
    	//1) A username (I don't understand why, however I guess "me" will translate to the user embedded in the access_token)
    	//2) A data type (here feed)
    	//3) The access_token
     
    	string username = "me";
    	string datatype = "feed";
    	string urlWriteWall = "https://graph.facebook.com/" + username + "/" + datatype + "?access_token=" + pAccessToken;
     
    	//the message to post as a key/value pair
    	string entityMessage = "message=" + Session["message"];
    	entityMessage += "&picture=http://webmodelling.com/_images/jewelpit.png";
    	entityMessage += "&link=http://webmodelling.com";
    	entityMessage += "&name=Rasmus";
    	entityMessage += "&caption=Writing to Facebook wall";
    		
    	HttpPost(urlWriteWall, entityMessage); //we write HttpPost a little later
    }
    
  11. In fbwrite.aspx.cs create the Facebook_GetRedirectUri() helper procedure :
    private string Facebook_GetRedirectUri()
    {
    	string urlCurrentPage = Request.Url.AbsoluteUri.IndexOf('?') == -1 ? Request.Url.AbsoluteUri : Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.IndexOf('?'));
    	NameValueCollection nvc = new NameValueCollection();
    	foreach (string key in Request.QueryString) { if (key != "code") { nvc.Add(key, Request.QueryString[key]); } }
    	string qs = "";
    	foreach (string key in nvc)
    	{
    		qs += qs == "" ? "?" : "&";
    		qs += key + "=" + nvc[key];
    	}
    	string redirect_uri = urlCurrentPage + qs; //urlCallback have to be exactly the same each time it is used (that's why the code key is removed)
     
    	return redirect_uri;
    }
    
  12. In fbwrite.aspx.cs create the HttpPost() helper procedure :
    private string HttpPost(string pUrl, string pPostData)
    {
    	HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(pUrl);
    	webRequest.ContentType = "application/x-www-form-urlencoded";
    	webRequest.Method = "POST";
    	byte[] bytes = System.Text.Encoding.UTF8.GetBytes(pPostData);
    	Stream requestWriter = webRequest.GetRequestStream(); //GetRequestStream
    	requestWriter.Write(bytes, 0, bytes.Length);
    	requestWriter.Close();
     
    	Stream responseStream = null;
    	StreamReader responseReader = null;
    	string responseData = "";
    	try
    	{
    		WebResponse webResponse = webRequest.GetResponse();
    		responseStream = webResponse.GetResponseStream();
    		responseReader = new StreamReader(responseStream);
    		responseData = responseReader.ReadToEnd();
    	}
    	catch (Exception exc)
    	{
    		throw new Exception("could not post : " + exc.Message);
    	}
    	finally
    	{
    		if (responseStream != null)
    		{
    			responseStream.Close();
    			responseReader.Close();
    		}
    	}
     
    	return responseData;
    }
    
  13. In fbwrite.aspx.cs create the RequestResponse() helper procedure :
    private string RequestResponse(string pUrl)
    {
    	HttpWebRequest webRequest = System.Net.WebRequest.Create(pUrl) as HttpWebRequest;
    	webRequest.Method = "GET";
    	webRequest.ServicePoint.Expect100Continue = false;
    	webRequest.Timeout = 20000;
     
    	Stream responseStream = null;
    	StreamReader responseReader = null;
    	string responseData = "";
    	try
    	{
    		WebResponse webResponse = webRequest.GetResponse();
    		responseStream = webResponse.GetResponseStream();
    		responseReader = new StreamReader(responseStream);
    		responseData = responseReader.ReadToEnd();
    	}
    	catch (Exception exc)
    	{
    		Response.Write("<br /><br />ERROR : " + exc.Message);
    	}
    	finally
    	{
    		if (responseStream != null)
    		{
    			responseStream.Close();
    			responseReader.Close();
    		}
    	}
     
    	return responseData;
    }
    

Congratulations - you are ready to try it out : in Visual Studio set fbwrite.aspx as start page and press F5 (don't forget in your browser url field to substitute localhost with develop.YourDomain.com).

The above code is very functional as it is and I also think it makes a good base for a wide range of Facebook integration, eg. I have manipulated it a little to get it working from inside my custom Forum & Comments control, Discussions.


Bonus code : List Facebook friends

To list a Facebook users friends, we can reuse most of the above code except most notably the Facebook_WriteWall function (as we don't want to write to facebook wall here). Either copy the code from the below steps and/or download the full FBFriends C# Code (if you download the code, you will still need to follow step 1, 2 & 3 below).

  1. Add you Facebook application AppID & AppSecret to you web.config file : (if you have not already done that following the fbwrite example above)
    <appSettings>
        <add key="facebook:AppId" value="YourAppID"/>
        <add key="facebook:AppSecret" value="YourAppSecret"/>
    </appSettings>
    
  2. Create a new C# .aspx page called fbfriends.aspx (as opposed to fbwrite.aspx above)
  3. In fbfriends.aspx insert the following : (differs from fbwrite because there are no textarea field)
    <asp:Button ID="btnSubmit" runat="server" Text="Show My Friends" OnClick="btnSubmit_Click" />
    
  4. In fbfriends.aspx.cs insert the following using statements at the top (above the class definition) :
    using System;
    using System.Web;
    using System.Net;
    using System.IO;
    using Newtonsoft.Json; //you need this 3. party assembly, downloadable from http://json.codeplex.com/
    using System.Configuration;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    
  5. In fbfriends.aspx.cs insert the following class globals : (same as for fbwrite)
    string facebook_urlAuthorize_base = "https://graph.facebook.com/oauth/authorize";
    string facebook_urlGetToken_base = "https://graph.facebook.com/oauth/access_token";
    string facebook_AppID = ConfigurationManager.AppSettings["facebook:AppID"];
    string facebook_AppSecret = ConfigurationManager.AppSettings["facebook:AppSecret"];
    
  6. In fbfriends.aspx.cs insert the following in Page_Load : (same as for fbwrite except that we call the Facebook_ListFriends function instead of Facebook_WriteWall)
    if (!IsPostBack)
    {
    	if (Request["code"] != null)
    	{
    		//After this page have redirected the users browser to Facebook asking to be authorized to write to the
    		//users wall, Facebook will redirect back to this page and if authorized having a "code" key in the querystring
     
    		//Since we have a code we got authorized and can now
    		//1) get an access_token
    		//2) use the access_token to write to the users Facebook wall
    		string authorizationCode = Request["code"];
    		string access_token = Facebook_GetAccessToken(authorizationCode);
    		if (access_token == "")
    		{
    			Response.Write("Could not get access_token");
    			return;
    		}
    		Facebook_ListFriends(access_token); //in fbwrite we called Facebook_WriteWall
    	}
    }
    
  7. In fbfriends.aspx.cs create the button handler, btnSubmit_Click : (btnSubmit_Click differs from fbwrite because we don't need to store the text to write)
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
    	Facebook_AuthorizeApplication();
    }
    
  8. In fbfriends.aspx.cs insert the Facebook_ListFriends function :
    private void Facebook_ListFriends(string pAccessToken)
    {
    	string username = "me";
    	string dataType = "friends";
    	string urlGetFriends = "https://graph.facebook.com/" + username + "/" + dataType + "?access_token=" + pAccessToken;
    	string jsonFriends = RequestResponse(urlGetFriends);
    	if (jsonFriends == "")
    	{
    		Response.Write("<br /><br />urlGetFriends have problems");
    		return;
    	}
    	Friends friends = JsonConvert.DeserializeObject<Friends>(jsonFriends); //we write the Friends class later
     
    	foreach (Friend friend in friends.data) //we write the Friend class later
    	{
    		Response.Write("<br />" + friend.name);
    	}
    }
    
  9. Copy the following 5 functions from the fbfriends example above or from the downloadable fbfriends C# Code file and insert them into fbfriends.aspx.cs :
    1. Facebook_AuthorizeApplication()
    2. Facebook_GetAccessToken()
    3. Facebook_GetRedirectUri()
    4. HttpPost()
    5. RequestResponse()
  10. In fbfriends.aspx.cs insert the Friend class (outside of the fbfriends class definition) :
    public class Friend
    {
    	public string id { getset; }
    	public string name { getset; }
    }
    
  11. In fbfriends.aspx.cs insert the Friends class (outside of the fbfriends class definition) :
    public class Friends
    {
    	public List<Friend> data { getset; }
    }
    

Congratulations - you should now be able to list anybodys Facebook friends.

This concludes my Facebook API C# Examples tutorial, please use the comments below to help, ask for help or just voice your opinion.


Appendix : Relevant links


Appendix : Common errors and solutions

  1. Authentication request errors OAuthException Missing client_id parameter

Reason : Look closely at your authentication request url, you will see that the client_id (aka AppID) is missing.

Example : https://graph.facebook.com/oauth/authorize?client_id=&redirect_uri=http://webmodelling.com/socialmedia/facebook/fbwrite.aspx&scope=publish_stream - the client_id value is empty.

Solution : In the querystring of your authentication request url, you need to insert a client_id key with the value of your Facebook AppID. Like this :
https://graph.facebook.com/oauth/authorize?client_id=YourAppID&redirect_uri=http://webmodelling.com/socialmedia/facebook/fbwrite.aspx&scope=publish_stream

  1. Authentication request errors OAuthException Invalid redirect_uri: Given URL is not allowed by the Application configuration.

Reason : Your authentication request does not contain a valid redirect_uri in the querystring. The redirect_uri value must be within the domain of your Facebook application.

Example : You have forgot to set "Site URL" under "Website with Facebook Login", so your Facebook App does not have any App Url in which case an authentication request like https://graph.facebook.com/oauth/authorize?client_id=144708635601028&redirect_uri=http://webmodelling.com/socialmedia/facebook/fbwrite.aspx&scope=publish_stream will fail because the domain part of the redirect_uri value, webmodelling.com, does not match your Facebook App Url.

Solution : Be sure your redirect_uri match your Facebook App Url site domain OR is within your Facebook Apps "App Domains".


Comments

You can comment without logging in
 
 B  U  I  S 
Words: Chars: Chars left: 
 Captcha 
 Nickname
Facebook
    
shezee611
User type : Standard
Register : 2013-Apr-14
Topics : 1
Replies : 1
--------------
      report  reply  
Dear Rasmus,

I use your example http://webmodelling.com/webbits/socialmedia/facebook-api.aspx
it's excellent written. completely understandable but I am having an issue. When I try to authenticate it show me an error. Please have a look

http://fbath.azurewebsites.net/fbwrite.aspx


If I try to login with same id where I created Fb App then it allow to login. Can you please explain why it's like that.


Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  

Hi sheezee611

I have never had this error myself, however according to the error message "error_code=901 error_message=This app is in sandbox mode Edit the app configuration at http://developers.facebook.com/apps to make the app publicly visible", you need to change your facebook application mode from sandbox to not-sandbox.

  1. Go to https://developers.facebook.com and check that you Sandbox mode is On
  2. Click on the "Edit App" button and change Sandbox mode from Enabled to Disabled
  3. Click on the "Save Changes" button
  4. Wait 3 minutes
  5. Try your fbwrite.aspx file again

Please report the result back.

web fiddler by nature

shezee611
User type : Standard
Register : 2013-Apr-14
Topics : 1
Replies : 1
--------------
      report  reply  
I found the reason. Sandbox option should be "Disabled" which comes "Enabled" by default while creating App.

Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  
Ahh... you solved it, great

web fiddler by nature

Anonymous
--------------
      report  reply  
Do you know how to create Album and upload photos? I can see lot of codes using different SDKs but I wanna use direct url method as you did above. Appreciate your help.
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  
I have never tried programmatically to create a facebook album or uploaded photos, however I found this little code snippet how to upload photos to a facebook album.

web fiddler by nature

Anonymous
--------------
      report  reply  
how i get the main picture of my friends in the list fafcebook friends code?
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  

Hi Anonymous

To request say name, gender and profile picture for all your friends, you could use this url :
string urlGetFriends = "https://graph.facebook.com/me/friends?fields=name,gender,picture&access_token=ACCESSTOKEN";

Facebook Graph API will now post back the requested fields (plus the id field) for each of your friends.
string jsonFriends = RequestResponse(urlGetFriends); //RequestResponse is a class from the tutorial code above.

The data posted by Facebook Graph API are formattet as JSON, which you need to parse into your own class :
Friends friends = JsonConvert.DeserializeObject<Friends>(jsonFriends);
You can reuse the Friends class from the tutorial code above, however you need to be sure that your Friend class have the matching properties, eg for the requested fields above you will need :
public class Friend
{
    public string id {get;set;}
    public string name {get;set;}
    public string gender {get;set;}
    public string picture {get;set;}
}

You can see much more in the Facebook Graph API documentation for the User class : http://developers.facebook.com/docs/reference/api/user/

web fiddler by nature

umer
--------------
      report  reply  
Hi rasmus,


where do i wite this code to work properly should i make a new procedure or not
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  

Hi Umer

These 3 lines belong in the Facebook_ListFriends function from the "List Facebook friends" example code step 8 :

"List Facebook friends" example code step 10 is the Friend class that you will have to change from :
public class Friend
{
 public string id { get; set; }
 public string name { get; set; }
}

, to :
public class Friend
{
    public string id {get;set;}
    public string name {get;set;}
    public string gender {get;set;}
    public string picture {get;set;}
}

web fiddler by nature

UMER
--------------
      report  reply  
Thanks Rasmus...
one more thing ....
i am facing the following problem...

Authentication request errors OAuthException Invalid redirect_uri: Given URL is not allowed by the Application configuration.

in appendix i saw the solution but i can not find how to match  redirect_ui
with app domains?????



website with fb login uri =http://sociomatics.co.uk/
Ap domain=sociomatics.co.uk

can i use both at the same time
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  

Hi Umer

For you facebook app under basic settings, set :

 

In case you get the error then you develop, in addition do the following :

  1. In your hosts file (c:\windows\system32\drivers\etc\hosts) set :
    127.0.0.1  localhost.sociomatics.co.uk
  2. Say that in your browser you load your sociomatics dev website like :
    http://localhost/myDevelopmentFolder/sociomatics
    then change that to :
    http://localhost.sociomatics.co.uk/myDevelopmentFolder/sociomatics
    (Say you use Visual Studio and press F5 to load your dev app in a browser, then simply manully write the ".sociomatics.co.uk" part after the "localhost" part).

Your redirect_uri will now be valid since localhost.sociomatics.co.uk is a sub domain of your Site Url and furthermore, on your dev machine, the now valid redirect_uri domain part (localhost.sociomatics.co.uk) will resolve to your localhost 127.0.0.1 so if executed on your machine, your browser will AFTER authentication be redirected to your dev code.

web fiddler by nature

umer
--------------
      report  reply  
Thank you rasmus.. my  write on wall app is working now.. but still i am trying to do the friends part.....

i tried to edit the  (c:\windows\system32\drivers\etc\hosts)
but system did not allow me to do so.....
kindly can you tell me how we can find the comments  likes and shares count of our friends by showing them in grid????
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  

Hi Umer

Apart from having a lot of fields, the User object also have a lot of connections. The connections you are asking for are probably :

  • feed (contains the last 25 posts)
  • likes
  • sharedposts

You can see all fields and connections as well as look up all objects here : http://developers.facebook.com/docs/reference/api/user/

I have never tried to request a connection, however note that while most fields are scalars, connections are arrays. I don't know, but I guess the following mechanism is a good guess of how to get the connections :

string urlGetFriends = "https://graph.facebook.com/me/friends?fields=feed,likes,sharedposts&access_token=ACCESSTOKEN";

(you will need to test how JSON deserializer handle the arrays before you can create the correct Friend class)

web fiddler by nature

titlemanager
--------------
      report  reply  
Hi Rasmus,

I am a 49 year old unemployed programmer living in California. I just wanted to compliment you on the well written code that you have generously made available to us. I'm sure there are people all over the world who appreciate your work. I certainly am very grateful that you are a part of the world. I wish the best for you and your family, and your business ventures in your land of smiles. I plan to follow your expertise and guidance for as long as it is possible, and I hope to see another update on the progress of your life. Thank you again,
Michael Kitterman
Pooja
--------------
      report  reply  
How can i get News Feeds.?
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  

Hi Pooja

To get access to your feed or to a friends feed, you must first find out what kind of permission you need to request. You can find out the necessary permission @ https://developers.facebook.com/docs/reference/api/user/ (the permission is read_stream)

Second you can experiment with building Facebook Graph API request @ Facebook Graph API explorer. Be sure to press the "Get Access Token" button and select the correct permissions (in your case read_stream).

Eg. to get your own feed you can use this url : https://graph.facebook.com/me?fields=feed&access_token=ACCESSTOKEN

If you want to get the feed of a friend, you can use this url : https://graph.facebook.com/FRIENDID?fields=feed&access_token=ACCESSTOKEN

web fiddler by nature

Pooja
--------------
      report  reply  
Hi Rasmus,

Thanks alot . i got that part working :) but the json string that is returned needs to be deserialized i searched for many posts but not able to find a simple way to do it.
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  

Hi Pooja

Then you get the json formatted feed data, you can see that it contains 2 properties :

  • id : just a string specifying the ID of the whom the feed belong to
  • data : an array of objects (each object is one message)

The Message objects are themselves composite types and that makes the whole thing a little complicated, however to get started, you may choose to deserialize only some scalar properties of each message. I have not testet it, but I guess the following may work :


string urlGetFeed = "https://graph.facebook.com/me?fields=feed&access_token=ACCESSTOKEN";
string jsonFeed = RequestResponse(urlGetFeed); //RequestResponse is a class from the tutorial code above
Feed feed = JsonConvert.DeserializeObject<Feed>(jsonFeed);

You can now loop through the messages :
foreach (Message message in feed.data.messages){
    Response.Write("<br />" + message.story;
}

And here are the 3 supporting classes : (Feed, Data & Message)

public class Feed {
    public string id {get;set;}
    public Data data {get;set;}
}

public class Data {
    public List<Message> messages {get;set;}
}

public class Message {
    public string id {get;set;}
    public string story {get;set;}
    public string picture {get;set;}
}

web fiddler by nature

Pooja
--------------
      report  reply  
Hi Rasmus,

i got the deserialization part working as well. :) Thank you .

i wanted to know is it possible to do all these operations (read feeds/write/ retrieve friends etc ..) without logging into facebook and if i have the access token(which remains the same).
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  

Hi Pooja

I think the default access token expires 2 hours after it is granted, see the official how to handle expired access token.

However, it may be possible to request a time extended access token, I am not sure. If you can confirm that it is either possible or not possible, please post your findings here.

web fiddler by nature

Pooja
--------------
      report  reply  

Hi Rasmus,

Yes surely i will do that .My requirement is that if the user logs into my application he should be asked for the login and access permission only once like a single sign on.

SamLuther
User type : Standard
Register : 2013-Jun-10
Topics : 1
Replies : 3
--------------
      report  reply  

Hi Rasmus,

I am trying to create new virtualhost in IIS7 as developer.supersite.com but when I navigate to http://www.developer.supersite.com I get HTTP 403 Forbidden error. The localhost is working fine. I tried adding the virtual host from both the host file in etc folder and also from the new website in IIS7 with no success. Can anyone please advise on how to resolve the issue?

Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  
Hi SamLuther

I cannot see how your post is related to facebook api, so I am going to delete your post in a couple of days.

I do plan to setup a forum here at webmodelling, there your post would give meaning. I hope to get the time maybe this week and maybe I transfer your post to that new forum.

web fiddler by nature

SamLuther
--------------
      report  reply  

Hi Rasmus,

I was trying to follow the steps in "setup localhost development" while trying to use the facebook API hence posted the query in the thread itself. Feel free to move it any place where I can get an answer :)

Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  
Hi SamLuther

Sorry, I misunderstood you, your post is certainly relevant on this page.

Ok, lets get started by confirming the following :
1) IF you have added the following to your hosts file :
127.0.0.1  developer.supersite.com
2) AND in IIS you have binded a website to :
developer.supersite.com
3) THEN you should be able to navigate your browser to :
http://developer.supersite.com (don't use any www)

web fiddler by nature

SamLuther
User type : Standard
Register : 2013-Jun-10
Topics : 1
Replies : 3
--------------
      report  reply  
It is working now. Thanks a lot!
Anonymous
--------------
      report  reply  
How to logout using access token.
Anonymous
--------------
      report  reply  
i am able to authorize user. but after that i need to add another user. For that i have to manually do sign out from Facebook then only my code work. so can you please suggest me how to sign out
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  

Hi Anonymous (if you had logged in then posting, you would get an email notification immediately then this reply was submitted)

I have never tried programmatically to logout a user, however it seems you can use the following url :
https://www.facebook.com/logout.php?next=REDIRECTURL&access_token=ACCESSTOKEN
, which takes 2 parameters :

  • next : which is the url facebook should redirect your browser to, eg. next=http://webmodelling.com/facebook-api.aspx
  • access_token : which is the access token obtained for the user you are about to logout.

web fiddler by nature

sarinsoman
User type : Standard
Register : 2013-Jul-13
Topics : 0
Replies : 1
--------------
      report  reply  
Hi Rasmus,

Excellent tutorial.Thanks for your effort.

I am looking for a sample codes for the following
1)Post photo(not thumbnail image) to facebook page. 
2) Read the feeds from the Page(including the user profile image)
3)How can i display a post from page (including the comments for that post.
4) Read a page post and put comment on that post

Please guide me how can i implement all the above.

Thanks in advance

Sarin
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  

Hi sarinsoman

I am not able to answer your questions without researching them first, which of current I unfortunately don't have the time to do.

However, for question 2) I think I may have already answered it here :
http://webmodelling.com/webbits/socialmedia/facebook-api.aspx?ml-d-mpids=86 

.. and with regard to the picture here : 
http://webmodelling.com/webbits/socialmedia/facebook-api.aspx?ml-d-mpids=57  

Good luck

web fiddler by nature

Anonymous
--------------
      report  reply  
Hi Rasmus,

I copied and paste ur code, but it doesnt work anymore. It returns:

"could not post : The remote server returned an error: (400) Bad Request."
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  
Hi  Anonymous

I am not sure what you mean by "anymore" - have it worked earlier and then stopped working ?

In case you have just copied and pasted the code, I recommend you to read the whole tutorial and don't forget to create a facebook application. Btw. the code you download is identical to the code running behind this page and you can use the "Try it out" section to confirm that the code is working.

web fiddler by nature

Alan
--------------
      report  reply  
Hi Rasmus,

I hv read through tis article, on the "Write to Facebook wall" section. 

After I click submit button, it managed to get the access_token, but it fb server returned: "could not post :The remote server returned an error: (400) Bad Request."

However I managed to post to wall with only "message" in the entityMessage, without "name, link, caption, and picture" like you did in this tutorial. I tried on ur "Try it out" sample, it worked perfectly, i hv no idea why mine doesnt work...
twlalan2
--------------
      report  reply  
thank you for this article, you just saved my day! 

Would love to see more article/tutorial from you Rasmus! Can you do more tutorial on social media using asp.net? for example, post status update on twitter, invite fb friends using fb app, etc.

Good day.
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  
Hi twlalan2

Really nice to hear. However it is unlikely for me to produce any social media using asp.net tutorials in the near future. I have multiple exciting projects going on and far too little time.

web fiddler by nature

Anonymous
--------------
      report  reply  
Hi! How can I read post from my wall using FacebookClient ? Or thomething else ?  And how can I read number of likes of someone post? Thanks.
astahir
User type : Standard
Register : 2013-Sep-20
Topics : 0
Replies : 3
--------------
      report  reply  
Hi Rasmus,

Thank you for a well-written article. I will definitely give it a try but for now I need your guidance in a specific matter. Basically I need to develop a POC and the requirement is that I enter an email address and my page fetches the publicly available info against that email address.  I have never used Graph API before and I need to write it in an ASP.NET application using C#.

Can you guide me to a tutorial / article that takes me step by step to achieve what I am looking for? Simply put, I just enter an email address and fetch all publicly available data against it.

Thanks in advance. 

Ahmed

astahir
User type : Standard
Register : 2013-Sep-20
Topics : 0
Replies : 3
--------------
      report  reply  
Where did my whole comment go?!

astahir
User type : Standard
Register : 2013-Sep-20
Topics : 0
Replies : 3
--------------
      report  reply  
Okay I see it now...Please ignore this comment! 

Talib
--------------
      report  reply  
you can access the fiends info like this

$facebook->api('me/friends?fields=picture,name,gender');

for more info visit the given below link

http://howtoblogr.blogspot.com/2013/10/how-to-count-all-your-facebook-friends.html
mahmoudnassereldine
User type : Standard
Register : 2013-Dec-18
Topics : 0
Replies : 1
--------------
      report  reply  
dear Rasmus
i put  the appid and app scret like here :
<appSettings>
    <add key="facebook:AppId" value="xxxxxxxxxxxxxxxxxxxx"/>
    <add key="facebook:AppSecret" value="xxxxxxxxxxxxxxxxxx"/>
  </appSettings>
she don t work and it display this error :
{   "error": {      "message": "Missing client_id parameter.",      "type": "OAuthException",      "code": 101   }}

can you help me ?
mimo
Anonymous
--------------
      report  reply  
dear rasmus
a have now this error :

Server Error in '/' Application.

A potentially dangerous Request.Path value was detected from the client (:).

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: System.Web.HttpException: A potentially dangerous Request.Path value was detected from the client (:).

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 

[HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (:).]   System.Web.HttpRequest.ValidateInputIfRequiredByConfig() +9673044   System.Web.PipelineStepManager.ValidateHelper(HttpContext context) +53

ravi
--------------
      report  reply  
i have followed ur code

Httppost method returns

The remote server returned an error: (400) Bad Request.

Anonymous
--------------
      report  reply  
Hi Ramus,
I am getting this exception..
could not post : The remote server returned an error: (403) Forbidden.
what went wrong...please let me know..



dfdssdf
--------------
      report  reply  
rtretewrewr
zmbhutta
--------------
      report  reply  
Hi, I am getting error "



The remote server returned an error: (403) Forbidden.

"
Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  
Hi zmbhutta
In case you get the error then trying to develop on localhost, then read my answer to SamLuther : http://webmodelling.com/webbits/socialmedia/facebook-api.aspx?ml-d-did=3&ml-d-mpids=103

web fiddler by nature

Saksena
--------------
      report  reply  
Hi sir,
Thanks for your wonderfull post,I have strucked up with an strange thing for about 4 days pls help me out.
am able to get my own profile details but not my friends list if i specify the dataType="friendlist" am getting my names of my friend list like close friends,family and all but datatype="friends" doesnt return my friends list pls pls help me out

Thanks in advance

Rasmus
User type : Admin
Register : 2012-Dec-21
Topics : 0
Replies : 106
--------------
      report  reply  
Hi Saksena

To be honest I am little rusty on the topic, however please start by trying to click on the "List your Facebook friends" button in the above "Try it out" section. Then I click the button myself, I correctly get a list of friends. Then you click the button, please post the result here.

web fiddler by nature

ferose
User type : Standard
Register : 2014-Sep-18
Topics : 0
Replies : 1
--------------
      report  reply  

Please help me to solve the issue: I used your code it returned the following error: The remote server returned an error: (403) Forbidden.

while debugging error thrown by below line
Response.Redirect(urlAuthorize, true);

Anonymous
--------------
      report  reply  
Hi Rasmus,
     I used your code, its working well but i wanted to show facebook share dialog box before posting message on my fb account.
Anonymous
--------------
      report  reply  
Hi Rasmus,
     I used your code, its working well but i wanted to show facebook share dialog box before posting message on my fb account.
kiquenet
--------------
      report  reply  

Suggestions for add full samples. (for Unit Test project VS 2013, and Windows Forms app too.)

More about Facebook SDK C# for

1) from me and other users:

post to wall, 
post photo to album, 
download photos from album

share post with another user (maybe send messages)
share photo with another user (maybe send messages)
share page with another user

do like and unlike to a post
do like and unlike to a page

get friend list and info data

2) from me
delete post 
delete photo from album

delete album
create new album

Anonymous
--------------
      report  reply  
a detailed explaination for facebook api usage:
http://www.writeulearn.com/facebook-graph-api/
DJ
--------------
      report  reply  
Hi Rasmus,
I am getting following error:

could not post : The remote server returned an error: (403) Forbidden.

as you have mentioned in reply to SamLuther querry I have done all things but still getting same error. my Url are correct. Please help me out.


click to top Facebook API Tutorial