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
- Use Visual Studio 2010 for creating a new Empty SharePoint project called
WriteOnWall
.
- 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.
- This will create a solution for you with default project items. Finally, add a new item of type WebPart to the solution.
- This creates a solution. The important files are Element.xml, WritOnWall.cs and WriteOnWall.webpart.
Implementing the main code
- 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.
- 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.
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; }
}
- 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.
region Webpart Properties
[WebBrowsable(false),
Personalizable(PersonalizationScope.Shared)]
public string OAuthCode { get; set; }
....
#endregion
- 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.
public WriteOnWallEditorPart(string webPartID)
{
this.ID = "WriteOnWallEditorPart" + webPartID;
this.Title = "Facebook Settings";
}
- First, method that is overridden is the
CreateChildControl()
which is responsible for creating the UI part for each of the properties needed.
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%;");
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);
}
- 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.
public override bool ApplyChanges()
{
EnsureChildControls();
WriteOnWall webPart = WebPartToEdit as WriteOnWall;
if (webPart != null)
{
webPart.OAuthCode = txtAuthCode.Text;
webPart.OAuthClientID = txtAuthClientID.Text;
.....
}
return true;
}
- 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.
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;
}
......
}
}
- 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.
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');");
}
}
- That's all that we need to do to the Editor Part section (WriteOnWallEditorPart.cs).
Now coming back to the WriteOnWall.cs file
- 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.
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)
)
{
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
{
.....
}
}
- Now there will be four supporting methods that are being used in the above methods.
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.
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);
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;
}
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.
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;
}
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.
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;
}
- 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
- Now build the solution in Visual Studio and deploy the solution by clicking on Deploy.
- Make sure that you have safecontrol entry in the web.config of the application for the WirteOnWall Project DLL.
- 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.
- 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.
- Click Add new page link and click on Create to create the new page.
- Now you see a blank page. Click Insert Tab under the Editing Tools head, and then click again on Web Part.
- 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.
- This will open Web Part properties window in the right side. Refer to the below image.
- 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 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