Click here to Skip to main content
13,139,569 members (54,179 online)
Click here to Skip to main content
Add your own
alternative version

Stats

13.3K views
633 downloads
17 bookmarked
Posted 21 Oct 2014

How to Automate Facebook Tasks with C#

, 21 Oct 2014
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Soufiane Rabhi
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.

You may also be interested in...

Comments and Discussions

 
QuestionGiven URL is not allowed by the Application configuration.: Pin
shrishjain1-Jan-15 10:28
membershrishjain1-Jan-15 10:28 
GeneralMy vote of 5 Pin
Gun Gun Febrianza23-Oct-14 23:09
member Gun Gun Febrianza23-Oct-14 23:09 
SuggestionMy vote of 4 Pin
RsaBrother's22-Oct-14 3:00
memberRsaBrother's22-Oct-14 3:00 
GeneralRe: My vote of 4 Pin
Mr Rabhi22-Oct-14 3:05
memberMr Rabhi22-Oct-14 3:05 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun21-Oct-14 23:43
memberHumayun Kabir Mamun21-Oct-14 23:43 
GeneralRe: My vote of 5 Pin
Mr Rabhi21-Oct-14 23:44
memberMr Rabhi21-Oct-14 23:44 
GeneralRe: My vote of 5 Pin
RsaBrother's22-Oct-14 3:04
memberRsaBrother'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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.170915.1 | Last Updated 21 Oct 2014
Article Copyright 2014 by Soufiane Rabhi
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid