Geeks With Blogs
The Unstable Mind of a .Net Developer

Over the past several years social media has grown from just a few sites to a booming industry.  With the wealth of information and entertainment available on sites like YouTube, Facebook and Twitter, it is easy to see where it has come from and why it has stuck.  Little wonder why people, developers and companies have sought to leverage the connections found on social media outlets to further careers, sell products or just plain connect to the rest of the world.

Recently, I had been asked to develop an API that would funnel posts through SharePoint to a Facebook page as status updates for a major corporation.  In researching its feasibility, I found a ton of information about posting to Facebook, if I was interested in using PHP.  Since I have graduated to real development languages and tools, I have no interest in doing so.  Unfortunately, examples of posting to Facebook using .Net are few and far between and most are incomplete or confusing at best.  This post is my attempt to provide a clear and complete example of posting to Facebook from a .Net application.


Now, I must admit that unless you are working with a corporation, developing a Facebook application or perhaps using Facebook as an authentication mechanism, if we’re being honest, the biggest reason to hook up to Facebook is to say you can.   Especially when you consider it may not even be necessary.  If you are simply interested in reading status updates on public pages, you can subscribe to RSS feeds of status updates using this URL where <FacebookPageId> is the Facebook unique identifier for the page.  An example is the Microsoft Visual Studio page found here.

http://www.facebook.com/feeds/page.php?format=atom10&id=<FacebookPageId>


Unfortunately, our first hurdle in posting to Facebook is that the API does not expose a means for logging in as a user or logging in a user.  I expect this is primarily as an anti-hijacking measure and to address privacy concerns.  Instead, we must use the Facebook Connect API which authenticates the user through a Facebook hosted login page and then passes control back to the ASP.Net application.  To make use of this API, we first have to do a couple of things.

First, we have to define an application in Facebook.  You start here to create an application.  There are a couple of restrictions on the name, specifically, it cannot include the word “face”.  Once created, Facebook assigns an application id, API key and a secret key.  These will be used in code later.  You will also need to configure the Facebook Connect URL for your application for cross domain posting.  This setting can be found on the Connect tab of the Edit Settings page.  If using the default web server built into Visual Studio, this URL will be something like http://localhost:<web server id>.  All Facebook applications can be managed here.

I did discover that not all applications are created equal.  When I created a second application specifically for this post, it would not work at all.  I have not yet contacted Facebook support to determine the root cause.  If you run into the issue where it appears that the application is being granted the proper permissions, but still cannot post, create another application and try it.

Next, we have to download the Facebook Developer Toolkit for .Net from CodePlex here.  This is the Microsoft “developed and supported” wrapper around the Facebook REST API.  Once installed, we are ready to begin developing.

 

Create a new ASP.Net Web Application in Visual Studio and add a reference to the Facebook.dll library from the Facebook Developer Toolkit.  Add a new HTML page called xd_receiver.htm to the application and drop the following code in it.  This defines the cross domain receiver used by the Facebook Connect API to post back to your application.  We’ll reference this file later.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<body>  
    <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/XdCommReceiver.js"  
        type="text/javascript"></script>  
</body>  
</html>  

 

Copy the following to Default.aspx.  I’ve purposefully excluded any references to the Facebook Connect API and am injecting all necessary code from the server side.  This is a simple form with one label, one text  box and one button to update status.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FacebookDemo._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="pnlFacebookConnect" runat="server">
        </asp:Panel>
        <asp:Panel ID="pnlStatusUpdate" runat="server">
            <asp:Label ID="Label1" runat="server" Text="Label">Post status update to Facebook</asp:Label>
            <asp:TextBox ID="txtStatus" runat="server" Width="500px"></asp:TextBox>&nbsp;<asp:Button 
                ID="btnUpdate" runat="server" Text="Update" Width="100px" 
                onclick="btnUpdate_Click" />
        </asp:Panel>
    </div>
    </form>
</body>
</html>

Now, the magic happens.  In the Page_Load event, start wiring up the necessary javascript code to load and initialize the Facebook Connect API.

// Make sure the FB javascript is loaded and registered
if (!ClientScript.IsStartupScriptRegistered("facebook_init")) {
    // Inject feature loader javascript into page header
    var feature = new HtmlGenericControl("script");
    feature.Attributes.Add("src", "http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php");
    feature.Attributes.Add("type", "text/javascript");
    Page.Header.Controls.Add(feature);

    // Inject the facebook init into the body onload
    ClientScript.RegisterStartupScript(this.GetType(), "facebook_init", string.Format("<script type='text/javascript'>FB.init('{0}', 'xd_receiver.htm');</script>", APPLICATION_ID));
}

 

Next, create the facebook session and request the desired permissions.  There are multiple permissions that can be combined and requested, including photo_upload, publish_stream, etc.  However, we’re only interested in posting status updates so the permission status_update is sufficient.

// Create the facebook session
session = new ConnectSession(APPLICATION_ID, SECRET_KEY);

// Request desired permissions.  If only updating status or content, need publish_stream
List<Enums.ExtendedPermissions> lst = new List<Enums.ExtendedPermissions>();
lst.Add(Enums.ExtendedPermissions.status_update);
session.RequiredPermissions = lst;
session.SessionExpires = false;

 

At this point, we need to determine if the user has already logged on to Facebook (Or, since it is possible to store a logged in user’s session key, if the stored key is still valid).  If necessary, inject the facebook login button into the page.  If the user is connected, simply create an instance of the Facebook api.

// Verify connection
if (!session.IsConnected()) {
    // User is not authenticated, display facebook connect button
    pnlFacebookConnect.Controls.Add(new Literal { Text = "<fb:login-button onlogin='window.location.reload()'></fb:login-button>" });
    pnlFacebookConnect.Controls.Add(new Literal { Text = "<br />" });
    pnlFacebookConnect.Controls.Add(new Label { Text = "Please log in to Facebook ..." });

    // And disable the update panel
    pnlStatusUpdate.Enabled = false;
} else {
    // User is authenticated, instantiate the api
    api = new Api(session);
}

 

Once authenticated, posting status updates are pretty straightforward.  In the button click event, call the Status.Set method.

if (api != null&&!string.IsNullOrEmpty(txtStatus.Text)) {
    api.Status.Set(txtStatus.Text);
}

 

Navigate to your Facebook profile and you should see your status updates.  Congratulations!  Be warned, however, that some goofy relations may decide to make fun of your test statuses.  You can put them in their place by letting them know that you have a Facebook account for professional reasons, not some silly game (though I do like Castle Age and Haven!).

 

Full source (with application id and secret redacted) can be downloaded from here.

 

Ralph Wheaton
Microsoft Certified Technology Specialist
Microsoft Certified Professional Developer

Posted on Wednesday, August 11, 2010 2:29 PM Facebook , Social Media | Back to top


Comments on this post: Social Media 101A: Leveraging Facebook Connect in ASP.Net

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Ralph Wheaton | Powered by: GeeksWithBlogs.net