Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Automate Facebook Tasks with C#

0.00/5 (No votes)
21 Oct 2014 1  
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:
<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:

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:

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.

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here