Click here to Skip to main content
15,884,628 members
Articles / Programming Languages / C#
Tip/Trick

How to Automate Facebook Tasks with C#

Rate me:
Please Sign up or sign in to vote.
4.43/5 (11 votes)
21 Oct 2014CPOL2 min read 30.1K   910   17   7
C# Facebook SDK

Introduction

This tip describes how to execute some Facebook tasks directly from C#. We will guide you through the development of a small Windows Forms application that will enable you to post pictures directly from your application to your Facebook wall.

Background

This article may be useful for intermediate developers who have some basics in C# and .NET.

Using the Code

Through this paragraph, we will explain how to develop a small Windows Forms application that will enable you to automate posting pictures directly from your application to your Facebook wall. You will have to follow two majors steps:

  1. The first thing you have to do is to create and register your application into Facebook.
  2. The second consists of writing some C# code based on the C# Facebook SDK.

Facebook Configuration

  1. Login to https://developers.facebook.com/apps.
  2. Click on the register button.
  3. Facebook will ask you to enter some information (Phone number, etc.).
  4. Once the registration is complete, you can click on the menu “Apps” => “Add new App”.
  5. Choose “Web site” and then click on “Create App ID”.
  6. The “App ID” will be used later on in the Config File in the C# project, in our case, we will create an application called “CodeProject”, we will use this application to develop a small utility that will enable us to post pictures on Facebook.

Once you complete all these steps, it’s time to write some code. :)

Working with Visual Studio

  1. Create a Windows Forms application.
  2. Add reference to Facebook.dll from here: https://github.com/facebook-csharp-sdk/facebook-csharp-sdk
  3. Add the Control “Web Browser” and name it “webBrowser
  4. Open “App.config” and add these lines:
XML
<appSettings>
    <add key="ApplicationId" value="The Application ID" />
    <add key="ApplicationUrl" value="" />
    <add key="ApplicationSecret" value="The Application Secret" />
    <add key="ExtendedPermissions" value="offline_access" />
</appSettings>

The application ID and the Application Secret are generated by Facebook “See section Facebook Configuration”.

On the main page “Main.cs”, on the load event of the Page, add these lines:

C#
var destinationURL = String.Format(@"https://www.facebook.com/dialog/oauth?client_id={0}&
    scope={1}&redirect_uri=http://www.facebook.com/connect/login_success.html&response_type=token", 
    this.ApplicationID , this.ExtendedPermissions);
webBrowser.Navigated += WebBrowserNavigated;
webBrowser.Navigate(destinationURL);

These lines define the Login URL used internally by Facebook. You have to construct this URL with the “applicationID” and the “ExtendedPermissions”. You can add their values directly into the source code or write two getters properties to get their values from the config file:

C#
public string ApplicationId
{
    get
    {
        return ConfigurationManager.AppSettings["ApplicationId"];
    }
}

public string ExtendedPermissions
{
    get
    {
        return ConfigurationManager.AppSettings["ExtendedPermissions"];
    }
}

public string AppSecret
{
    get
    {
        return ConfigurationManager.AppSettings["ApplicationSecret"];
    }
}

Now, what remains is only writing code to publish pictures directly from the application to Facebook wall.

C#
private void WebBrowserNavigated(object sender, WebBrowserNavigatedEventArgs e)
        {
// this dictionary contain any kind of information 'Pictures, videos, 
// Text, it will be published through the Facebook C# SDK

   Dictionary<string, object> parameters = new Dictionary<string, object>();

            // an Image to be added to the parameters               
            FacebookMediaObject media = new FacebookMediaObject
            {
                FileName = "CodeProject",
                ContentType = "image/jpeg"
            };
            byte[] img = File.ReadAllBytes("the Path of a picture ");
            media.SetValue(img);
            parameters.Add("source", media);

// get token from the URL generated by the Web browser, 
// this token will be used to create a new instance of the class "FacebookClient"
            var url = e.Url.Fragment;
            if (url.Contains("access_token") && url.Contains("#"))
            {
                url = (new Regex("#")).Replace(url, "?", 1);
                this.AccessToken = System.Web.HttpUtility.ParseQueryString(url).Get("access_token");
                //Create an instance of Facebook client
                var fb = new FacebookClient(this.AccessToken);
                //post the dictionary with the picture inside
                dynamic result = fb.Post("/me/photos", parameters);
                var newPostId = result.id;

//Facebook won't update your wall in real time, it will take some seconds or minutes,
// then you can check your Facebook wall, you will find the picture published
            }

You find the source code of the application. You can download it but do not forget to update the web config file with your ApplicationID and the ApplicationSecret generated by Facebook.

Thank you for reading and do not hesitate to leave your questions and comments.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
France France
Sofiene Rabhi is Microsoft certified professional in C# ,HTML 5 and JavaScript, Asp.net and Microsoft Silverlight, consultant, trainer specializing in application development with Microsoft technologies, including c#, Vb.net, and Microsoft Azure.

Comments and Discussions

 
QuestionGiven URL is not allowed by the Application configuration.: Pin
shrishjain1-Jan-15 10:28
shrishjain1-Jan-15 10:28 
GeneralMy vote of 5 Pin
Gun Gun Febrianza23-Oct-14 23:09
Gun Gun Febrianza23-Oct-14 23:09 
SuggestionMy vote of 4 Pin
RsaBrother's22-Oct-14 3:00
RsaBrother's22-Oct-14 3:00 
GeneralRe: My vote of 4 Pin
Soufiane Rabhi 22-Oct-14 3:05
Soufiane Rabhi 22-Oct-14 3:05 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun21-Oct-14 23:43
Humayun Kabir Mamun21-Oct-14 23:43 
GeneralRe: My vote of 5 Pin
Soufiane Rabhi 21-Oct-14 23:44
Soufiane Rabhi 21-Oct-14 23:44 
GeneralRe: My vote of 5 Pin
RsaBrother's22-Oct-14 3:04
RsaBrother's22-Oct-14 3:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.