Click here to Skip to main content
Click here to Skip to main content

Facebook Webpart for SharePoint

, 15 Mar 2011
Rate this:
Please Sign up or sign in to vote.
In this two series article, we will show how to create Facebook webparts. In this first part, we will develop the ShowWall webpart, that will enable you to fetch walls/posts made by a user on your own SharePoint portal. In the second part, we will develop the webpart for posting updates to Facebook.
This is an old version of the currently published article.

Introduction

More and more businesses are moving towards using SharePoint portal as their public facing websites, due to the ease of adding functionality through webparts. With the rise of social networks like Facebook and Twitter, you often provide updates on these networks as well as display the updates on your website. So in this two series article, we will show you the way we can create Facebook webparts, that will allow you to update Facebook directly from SharePoint as well as view the updates on your portal. In this first part, we will develop the ShowWall webpart that will enable you to fetch walls/posts made by a user on your own SharePoint portal. All the source code can be downloaded from the attached zip file and is also available on our open source project:

What You’ll Need Preinstalled

To follow along with this demonstration, you will need to have the following requirements installed:

  • SharePoint 2010
  • Visual Studio 2010

Creating the Project

  1. Use Visual Studio 2010 for creating a new Empty SharePoint project called ShowWall.

  1. When prompted by the SharePoint Customization Wizard, provide a site URL and validate it. Then select the option to Deploy as a farm solution. Click finish.

  1. This will create a solution for you with default project items. Finally, add a new item of type WebPart to the solution.

  1. This creates a solution. The important files are Element.xml, ShowWall.cs and ShowWall.webpart.

Implementing the Main Code

  1. Now, we start to put our code in ShowWall.cs class. For serialization purposes, the ShowWall.cs class must have a default, parameter-less constructor. Add a Web control Label lblMessage. This Label control is used to show exception message occurred during retrieving user walls. We are required to add three namespaces namely: System.IO, system.Net, and Microsoft.SharePoint.WebPartPages as this code will use some classes available in those namespaces.
  2. We will need settings for the Facebook userid whose updates we will fetch. To provide this functionality, we need to add a separate region named “Webpart properties” for storing all webpart properties like user id, wall count and show description. These settings will be used by the SharePoint administrator to change the webpart settings and display. This section is a part of ShowWall.cs class. Please check the below code snippet for providing webpart Facebook Settings Section.
    #region Webpart Properties
    [WebBrowsable(true),
    Category("Facebook Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebPartStorage(Storage.Shared),
    DefaultValue(""),
    WebDisplayName("User Id / User Name"),
    WebDescription("Please enter user id")]
    
    public string UserID { get; set; }
    
    [WebBrowsable(true),
    Category("Facebook Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebPartStorage(Storage.Shared),
    DefaultValue("10"),
    WebDisplayName("Wall Count"),
    WebDescription("Please enter number of wall you want to display")]
    
    public int WallCount { get; set; }
    
    [WebBrowsable(true),
    Category("Facebook Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebPartStorage(Storage.Shared),
    DefaultValue("true"),
    WebDisplayName("Show Description"),
    WebDescription("Would you like to show description")]
    
    public bool EnableShowDesc { get; set; }
    
    #endregion   
  3. To design the webpart UI, we are required to override the CreateChildControls() method of the Webpart base class. There are two main purposes of this method - one is to create UI controls to be displayed on webpart and the second purpose is to fetch the authenticated user posted walls and set those to the created UI. In the first few lines, we create one table instance named “mainTable” and then set its width, CSS and other settings and added this newly created table instance to the webcontrol.
    Table mainTable;
    TableRow tr;
    TableCell tc;
    mainTable = new Table();
    mainTable.Width = Unit.Percentage(100);
    mainTable.CellSpacing = 0;
    mainTable.CellPadding = 0;
    
    mainTable.CssClass = "ms-viewlsts";
    this.Controls.Add(mainTable);
  4. Now we come to the real meat, i.e., getting the updates from Facebook. Fortunately, the Graph API is very simple.
    private JSONObject GetFeeds()
    {
    	JSONObject obj = null;
    	string url;
    	HttpWebRequest request;
    	string oAuthToken = string.Empty;
    
    	try
    	{
    		url = string.Format(http://graph.facebook.com/{0}/feed,
    				this.UserID);
    		request = WebRequest.Create(url) as HttpWebRequest;
    		using (HttpWebResponse response = request.GetResponse()
    				as HttpWebResponse)
    		{
    			StreamReader reader = new StreamReader
    				(response.GetResponseStream());
    			string retVal = reader.ReadToEnd();
    
    			obj = JSONObject.CreateFromString(retVal);
    			if (obj.IsDictionary &&
    				obj.Dictionary.ContainsKey("error"))
    			{
    				throw new Exception(obj.Dictionary
    				["error"].Dictionary["type"].String, new
    		Exception(obj.Dictionary["error"].Dictionary["message"].String));
    			}
    		}
    	}
    	catch (Exception Ex)
    	{
    		LblMessage = new Label();
    		LblMessage.Text = Ex.Message;
    		this.Controls.Add(LblMessage);
    	}
    	return obj;
    }
  5. The above method uses a relative time which is obtained as follows:
    private string relativeTime(string pastTime)
    {
    	DateTime origStamp = DateTime.Parse(pastTime.ToString());
    	DateTime curDate = DateTime.Now;
    
    	TimeSpan ts = curDate.Subtract(origStamp);
    	string strReturn = string.Empty;
    
    	if (ts.Days >= 1)
    	{
    		strReturn = String.Format("{0:hh:mm tt MMM dd}" + "th",
    Convert.ToDateTime(pastTime).ToUniversalTime());
    	}
    	else
    	{
    		if (ts.Hours >= 1)
    			strReturn = "about " + ts.Hours + " hours ago";
    		else
    		{
    			if (ts.Minutes >= 1)
    			{
    				strReturn = "about " + ts.Minutes +
    						" minutes ago";
    			}
    			else
    				strReturn = "about " + ts.Seconds +
    						" seconds ago";
    		}
    	}
    	return strReturn;
    }
  6. You must have noticed that we used a class called JSONObject. This represents an object encoded in JSON. It can be either a dictionary mapping strings to other objects, an array of objects, or a single object, which represents a scalar. This class provides a static method named “CreateFromString” which creates a JSONObject object by parsing string. This JSONObject contains id, from, message and created_time fields. In this webpart, I am using message and created_time. This class requires the JavaScriptSerializer so after adding this class you will need to add the following namespace: System.Web.Script.Serialization and System.Web.Extensions assembly. This class has been picked from GitHub Facebook SDK.
    public static JSONObject CreateFromString(string s)
    {
    	object o;
    	JavaScriptSerializer js = new JavaScriptSerializer();
    	try
    	{
    		o = js.DeserializeObject(s);
    	}
    	catch (ArgumentException)
    	{
    		throw new Exception("JSONException",new Exception
    			( "Not a valid JSON string."));
    	}
    
    	return Create(o);
    }
  7. Finally, let us add the feed obtained from Facebook into our table. This requires nothing, but iterating over each row of data and adding it as a row in the table.
    JSONObject me = GetFeeds();
    if (me.Dictionary["data"] != null)
    {
    	JSONObject[] feeds = me.Dictionary["data"].Array;
    
    	foreach (JSONObject feed in feeds)
    	{
    		if (i < this.WallCount)
    		{
    			tr = new TableRow();
    			mainTable.Rows.Add(tr);
    			tc = new TableCell();
    			tc.CssClass = "ms-vb2";
    			tc.Width = Unit.Percentage(30);
    			tc.Text = feed.Dictionary["message"].String;
    			tr.Cells.Add(tc);
    
    			if (i % 2 != 0)
    			{
    				tr.CssClass = "ms-alternatingstrong";
    			}
    
    			tr = new TableRow();
    			tc = new TableCell();
    			tc.CssClass = "ms-vb2";
    
    			if (this.EnableShowDesc)
    			{
    			   // tc3.VerticalAlign = VerticalAlign.Top;
    				mainTable.Rows.Add(tr);
    				tc.Text = relativeTime(feed.Dictionary
    				["created_time"].String.ToString());
    				tc.Style.Add("color", "Gray");
    				tr.Cells.Add(tc);
    				if (i % 2 != 0)
    				{
    					tr.CssClass = "ms-alternatingstrong";
    				}
    			}
    		}
    		else
    		{
    			break;
    		}
    		i++;
    	}
    }
  8. If any exception occurs, then we show this in the label we created earlier.
    catch (Exception Ex)
    {
        LblMessage = new Label();
        LblMessage.Text = Ex.Message;
        this.Controls.Add(LblMessage);
    }

Building and Deploying the Webpart

  1. Now build the solution in Visual Studio and deploy the solution by clicking on Deploy.
  2. Make sure that you have safecontrol entry in the web.config of the application for the ShowWall Project DLL.
  3. After successful deployment, open up your SharePoint website. Go to Site Actions -> Site Settings -> Galleries->Web parts. Here you should find the ShowWall webpart listed.

  1. To use it on your page, follow the mentioned steps. Open the page where you want to use the Show Wall webpart. Let us create a new page called ShowWallTestPage. For this, first go to Site Pages->All Pages.

  1. Click Add new page link and click on Create to create the new page.

  1. Now you see a blank page. Click Insert Tab under the Editing Tools head, and then click again on Web Part.

  1. Move to Custom in Categories Section. Select the ShowWall Webpart and click Add. ShowWall webpart is added to the page. Click Edit WebPart icon available in the right side of ShowWall WebPart Title and click on Edit Web Part.

  1. This will open Web Part properties window in the right side. Refer to the below image.

  1. Insert your user id. It is mandatory. Put some integer in Wall Count. It will show the number of posted walls on your web part. If you will check Show description, it will show you the time and date of wall else not. Click Save & Close button available at Top Ribbon. You are done! You should see the webpart filled with your posts on Facebook.

Conclusion

In this article, we saw the process of building a SharePoint webpart integrated with Facebook. This is a good starting point for building almost any functionality provided by Facebook through the graph API, including friends, photos, like button and more. In the second part of this article, we will show you how to post on Facebook through a webpart. However, if you want to do a fast forward and are comfortable with the code, you can directly go to http://code.google.com/p/sharepoint-facebook-wall.

History

  • 11th March, 2011: Initial version

Authors

Nitin Gupta is the SharePoint architect and heads the Microsoft Small Business group at BrickRed Technologies. Abhinav Maheshwari is the CTO of BrickRed and has a keen interest in SharePoint and other portal frameworks. Both are members of the Technology Specialists Group at Brickred Technologies, which is a leading provider of mission critical applications for small and medium businesses.

License

This article, along with any associated source code and files, is licensed under The MIT License

About the Author

3PillarLabs

India India
No Biography provided

Comments and Discussions


Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
 
QuestionHelp for setting properties webpart Pinmemberptvce7-Apr-14 18:02 
Questionsource code PinmemberMember 976391917-Jan-13 23:04 
Questionsource code PinmemberMember 976391917-Jan-13 23:02 
QuestionSharepoint-Facebook-Wall 4.0 launched with some cool new features!!! PinmemberTSG BrickRed24-Jan-12 22:37 
BugWriteOnWall Pinmembermaparicio8-Nov-11 9:37 
GeneralRe: WriteOnWall Pinmemberaxorth21-Dec-11 9:20 
QuestionI'm getting 400 Error, Bad Request..! Pinmemberramesh.gaddam8-Aug-11 10:49 
Generalcomment and like on wall Pinmembernisha8828-Apr-11 20:58 
GeneralRe: comment and like on wall PinmemberTSG BrickRed28-Apr-11 21:24 
GeneralRe: comment and like on wall Pinmembernisha8829-Apr-11 1:43 
GeneralRe: comment and like on wall PinmemberTSG BrickRed16-May-12 1:19 
GeneralSharepoint-Facebook-Wall 3.0 launched with some cool new features!!! PinmemberTSG BrickRed15-Apr-11 3:11 
GeneralThe given key was not present in the dictionary. PinmemberTracy Sterling6-Apr-11 13:19 
GeneralMy vote of 5 Pinmemberdev4ever17-Mar-11 23:07 
Generalerror and solution Pinmemberdev4ever17-Mar-11 22:37 
GeneralRe: error and solution PinmemberTSG BrickRed19-Mar-11 23:44 
GeneralRe: error and solution Pinmemberdev4ever20-Mar-11 18:45 
GeneralRe: error and solution Pinmemberdev4ever20-Mar-11 18:46 
GeneralRe: error and solution PinmemberTSG BrickRed22-Mar-11 7:47 
GeneralRe: error and solution [modified] Pinmemberdev4ever22-Mar-11 20:20 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 15 Mar 2011
Article Copyright 2011 by 3PillarLabs
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid