Click here to Skip to main content
14,355,411 members

Facebook Webpart for SharePoint - Part 2

Rate this:
5.00 (1 vote)
Please Sign up or sign in to vote.
5.00 (1 vote)
20 Jun 2012MIT
Second article showing Facebook write on wall webpart using Visual Studio 2010.

Introduction

In this two part series, first part describes the development of the Facebook Show Wall web-part. In this second part, we wall develop the Facebook write on wall web-part using Visual Studio 2010, that will enable you to write on the Facebook wall, group wall and pages, from your SharePoint portal. All the source code can be downloaded from 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 WriteOnWall.
  2. Image 1

  3. 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. 
  4. Image 2

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

  7. This creates a solution. The important files are Element.xml, WritOnWall.cs and WriteOnWall.webpart
  8. Image 4

Implementing the main code

  1. We will now put our code in WriteOnWall.cs , First thing that we need to do is to Inherit from Microsoft.SharePoint.WebPartPages.WebPart and IWebEditable interface. We have inherited from the IWebEditable in order to create a custom tool part, as we need to give different functionality in the fill properties section that we will discuss later. 
  2. Since we have inherited the IWebEditable interface, we need to write some methods which are shown below, This provides an interface to specify custom editing controls that are associated with the web-part controls.
  3. EditorPartCollection IWebEditable.CreateEditorParts()
    {
       EditorPartCollection defaultEditors = base.CreateEditorParts();
       List<EditorPart> editors = new List<EditorPart>();
       editors.Add(new WriteOnWallEditorPart(this.ID));
       return new EditorPartCollection(defaultEditors, editors);
    }
     
    object IWebEditable.WebBrowsableObject
    {
       get { return this; }
    }
  4. Next we need to define the web-part properties, in order to get the details of the account to which the web-part will be connected to and some more information that will be needed by the web-part for UI. As we can see that we have made these properties Web-browsable false, this is because we will create a custom tool part and set the values into these from there.
  5. region Webpart Properties
     
    [WebBrowsable(false),
    Personalizable(PersonalizationScope.Shared)]
    public string OAuthCode { get; set; }
     
    ....
     
    #endregion
  6. Created a new class WriteOnWallEditorPart.cs which is inheriting the EditorPart class. In this class we will create a custom properties section by overriding few methods of the EditorPart class. In this class we are having a parameterized constructor which sets the ID and Title of the editor part.
  7. public WriteOnWallEditorPart(string webPartID)
    {
        this.ID = "WriteOnWallEditorPart" + webPartID;
        this.Title = "Facebook Settings";
    
    }
  8. First, method that is overridden is the CreateChildControl() which is responsible for creating the UI part for each of the properties needed.
  9. protected override void CreateChildControls() 
    { 
        base.CreateChildControls();
        pnlFacebookSettings = new Panel();
        pnlCommonSettings = new Panel();
        pnlPostToWallSettings = new Panel();
        lineBreak = new LiteralControl("<br/>");
        seperatorDiv = new Panel();
        seperatorDiv.Attributes.Add("class", "UserDottedLine");
        seperatorDiv.Attributes.Add("style", "width: 100%;");
        
        //Code
        pnlProperty = new Panel();           
        pnlPropertyName = new Panel();
        pnlPropertyControl = new Panel();
    
        .....                      
        rdoBtnListPostLocation = new RadioButtonList();
        rdoBtnListPostLocation.Items.Add(new ListItem("On my wall", "postToYourWall"));
        rdoBtnListPostLocation.Items.Add(new ListItem("On my page", "postToPageWall"));
        .....
        rdoBtnListPostLocation.AutoPostBack = false;
        pnlPropertyControl.Controls.Add(rdoBtnListPostLocation);
        pnlProperty.Controls.Add(pnlPropertyControl);
    
        pnlPostToWallSettings.Controls.Add(pnlProperty); 
         
        ....
     
        this.Controls.Add(pnlFacebookSettings);
    
    }
  10. Second, method that needs to be overridden is the ApplyChanges() method, this method is triggered when we click on the Apply button when the web-part properties as edited.
  11. public override bool ApplyChanges() 
    { 
        EnsureChildControls();
    
        WriteOnWall webPart = WebPartToEdit as WriteOnWall; 
    
        if (webPart != null) 
        { 
            webPart.OAuthCode = txtAuthCode.Text;
            webPart.OAuthClientID = txtAuthClientID.Text;
             .....
        }
    
        return true; 
    }
  12. Third, method that we will override is the SyncChanges(), this is responsible for updating the values from the controls in the tool part to the web-part properties values.
  13. public override void SyncChanges() 
    { 
        EnsureChildControls();
        WriteOnWall webPart = WebPartToEdit as WriteOnWall;
            if (webPart != null)
            {
                txtAuthCode.Text = webPart.OAuthCode;
                txtAuthClientID.Text = webPart.OAuthClientID;
                txtAuthClientSecret.Text = webPart.OAuthClientSecret;
                txtAuthRedirectUrl.Text = webPart.OAuthRedirectUrl;
    
                if (chkShowUserName.Visible)
                {
                    chkShowUserName.Checked = webPart.EnableShowUserName;
    
                }
    
                ......
           }
    }
  14. We, have also added a method OnPreRender as we need to register the JavaScript to show and hide some of the controls based on the user selection.
  15. protected override void OnPreRender(EventArgs e)
    {
        ....
    
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), 
             "scriptShowHidePostAsWhatDiv", scriptShowHidePostAsWhatDiv);
        foreach (ListItem item in rdoBtnListPostLocation.Items)
        {
            item.Attributes.Add("onclick", "ShowHidePostAsWhatDiv('" + item.Value + "','postAsWhatDiv');");
        }
    }
  16. That's all that we need to do to the Editor Part section (WriteOnWallEditorPart.cs).
  17. Now coming back to the WriteOnWall.cs file 

  18. Here also we will override the CreateChildControls() method, which will be responsible for creating the UI of the web-part. We will also create a label in the catch which will display the message for error occurred.
  19. protected override void CreateChildControls()
    {
        if (!String.IsNullOrEmpty(this.OAuthCode) ||
                !String.IsNullOrEmpty(this.OAuthClientID) ||
                !String.IsNullOrEmpty(this.OAuthRedirectUrl) ||
                !String.IsNullOrEmpty(this.OAuthClientSecret) ||
                !String.IsNullOrEmpty(this.UserID)
                )
        {
    
            //first get the authentication token 
            oAuthToken = CommonHelper.GetOAuthToken("publish_stream", 
               OAuthClientID, OAuthRedirectUrl, OAuthClientSecret, OAuthCode);
    
            this.Page.Header.Controls.Add(CommonHelper.InlineStyle());
            base.CreateChildControls();
            try
            {
                ....
                buttonWriteOnWall = new Button();
                buttonWriteOnWall.ForeColor = Color.White;
                buttonWriteOnWall.BackColor = Color.FromArgb(84, 116, 186);
                buttonWriteOnWall.Text = "Share";
                buttonWriteOnWall.Click += new EventHandler(buttonWriteOnWall_Click);
                tc.Controls.Add(buttonWriteOnWall);
    
            }
            catch (Exception Ex)
            {
                ....
            }
        }
        else
        {
            .....
        }
    }
  20. Now there will be four supporting methods that are being used in the above methods.
  21. oAuthToken is the string variable that gets the user authentication token to be used in getting the user feeds from the Facebook. This method is written in a common helper class CommonHelper.cs.
  22. public static string GetOAuthToken(string scope, string OAuthClientID, 
                  string OAuthRedirectUrl, string OAuthClientSecret, string OAuthCode)
    {
        string oAuthToken = string.Empty;
       
        string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id" + 
           "={0}&redirect_uri={1}&client_secret={2}&code={3}&scope={4}", 
           OAuthClientID, OAuthRedirectUrl, OAuthClientSecret, OAuthCode,scope);
    
        url = url.Replace(" ", string.Empty);
    
        //get the server certificate for calling https 
        ServicePointManager.ServerCertificateValidationCallback = 
          new System.Net.Security.RemoteCertificateValidationCallback(ValidateFacebookCertificate);
        WebRequest request = WebRequest.Create(url) as HttpWebRequest;
    
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string retVal = reader.ReadToEnd();
            oAuthToken = retVal.Substring(retVal.IndexOf("=") + 1, 
                         retVal.Length - retVal.IndexOf("=") - 1);
        }
    
        return oAuthToken;
    }
  23. GetUserPages() is a private method that gets all the user pages, so that if user chooses to post the message on the page, that page can be retrieved from the users account and the message can be posted.
  24. private JSONObject GetUserPages(string oAuthToken)
    {
        JSONObject obj = null;
        string url;
        HttpWebRequest request;
    
        try
        {
            url = string.Format("https://graph.facebook.com/me/accounts?access_token={0}", oAuthToken);
            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)
        {
            ....
        }
        return obj;
    }
  25. GetUserGroups() is an private method that gets all the user groups, so that if user chooses to post the message on the group wall, that group can be retrieved from the users account and the message can be posted on that group wall.
  26. private JSONObject GetUserGroups(string oAuthToken)
    {
        JSONObject obj = null;
        string url;
        HttpWebRequest request;
    
        try
        {
            url = string.Format("https://graph.facebook.com/me/groups?access_token={1}", 
                                this.OAuthPageID.Trim().ToString(), oAuthToken);
    
            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)
        {
            .....
        }
        return obj;
    }
  27. Now, let's move on to one of the most important method that does all the main stuff, buttonWriteOnWall_Click(), this method is the click event of the Share button which will post the message at the configured wall, after the user has written the message in the message box. 

    void buttonWriteOnWall_Click(object sender, EventArgs e)
    {
        try
        {
            bool userMemberOfGroup = false;
            string postUrl = string.Empty;
            if (this.PostOnProfile)
            {
                postUrl = string.Format("https://graph.facebook.com/me/feed?access" + 
                   "_token={0}&message={1}", oAuthToken, textWall.Text.Trim());
            }
            ....
     
            if (!String.IsNullOrEmpty(postUrl))
            {
                HttpWebRequest request2 = WebRequest.Create(postUrl) as HttpWebRequest;
                request2.Method = "post";
                using (HttpWebResponse response2 = request2.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response2.GetResponseStream());
                    string retVal = reader.ReadToEnd();
    
                   .....
                }
            }
        }
        catch (Exception Ex)
        {
            LblMessage = new Label();
            LblMessage.Text = "An error occurred while posting on wall:" + Ex.Message;
            this.Controls.Add(LblMessage);
        }
    }

Building and Deploying the Web-part

  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 WirteOnWall 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 WriteOnWall webpart listed. 
  4. Image 5

  5. To use it on your page, follow the mentioned steps. Open the page where you want to use the Wite On Wall webpart. Let us create a new page called WriteOnWallTestPage. For this, first go to Site Pages->All Pages. 
  6. Image 6

  7. Click Add new page link and click on Create to create the new page. 
  8. Image 7

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

  11. Move to Brickred in Categories Section. Select the WriteOnWall Webpart and click Add. WriteOnWall webpart is added to the page. Click Edit WebPart icon available in the right side of WriteOnWall WebPart Title and click on Edit Web Part. 
  12. Image 9

  13. This will open Web Part properties window in the right side. Refer to the below image. 
  14. Image 10

  15. 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. 
  16. Image 11

Conclusion

In this article, we have shown the second functionality of writing the message on Facebook wall. The source code shown above is just the highlighted syntax and doesn't include complete implementation. Please download the source code from the link provided above to see the complete source code. 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

  • 18th May, 2012: Initial version

License

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

Share

About the Author

3PillarLabs
India India
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
Article
Posted 20 Jun 2012

Stats

32.3K views
282 downloads
9 bookmarked