Wednesday 27 April 2011

Get HTML from page using the Client Object Model in SharePoint

Here is how to get the RAW HTML of a Web Page on your SharePoint Site using the Client Object Model:

Just substitute your Site Collection name instead of "sitecollection" and your page path along with the Relative Server URL instead of /Sites/Vard/SitePages/Home.aspx

The string variable pageHTML will now have the raw html of the Home.aspx page.

Have Fun!

Monday 25 April 2011

Office365 beta and the SharePoint 2010 Client Object Model

UPDATE: Microsoft has published the article on Authentication the Client Object Model on Office 365. You can find it here:

​I just got my Office365 beta license and configured a new Team Site in Sharepoint Online. Then I thought of accessing this new team site through the SharePoint 2010 .NET Client Object Model when I got the 403: Forbidden error code.

First, I thought that there might be some authenticaion issue so I tried accessing with both Classic Authentication and Claims based authentication.

Forms Based Authentication(Client Object Model):

clientcontext.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication;

clientcontext.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo("username", "password");

Web Service Login:

AuthService.Authentication auth = new AuthService.Authentication();
auth.Url = "";
auth.CookieContainer = new System.Net.CookieContainer();
AuthService.LoginResult loginresult = auth.Login("username","password");

With both the cases, it gave me the following error:

"Server was unable to process request. ---> The server was unable to process the request due to an internal error."


I tried accessing the lists of Office365 through the Lists service:

ListService.Lists list = new ListService.Lists();

list.Credentials = new NetworkCredential("username", "password");

var res = list.GetList("Documents");

but got this clear cut error:

"Server was unable to process request. ---> Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"

After some digging aroung, I found out that indeed right now, support is not there for the client object model and the only way to currently use the Client Object Model with SharePoint Online is to get the FedAuth Cookie (from fiddler) and then include that cookie in your call from the code. But this is not the best practice and is highly discouraged.

Hopefully, the Office 365 team will include the Client Object Model as soon as possible. I will update it here as soon as there is any news regarding the issue.

Friday 22 April 2011

How to Integrate Facebook with Windows Application

Ever wondered how to integrate Facebook into your application? Just how cool would it be to have Facebook button on your application? Lets do it then...

We will be using an awesome C# Facebook API  called facebooksdk which will make our task extremely easy.

First, In order to use your application to post on Facebook, you need to register your application and get the App ID. The registration is absolutely free. This App ID will help Facebook recognize (and authorize) your application each time a communication is made from the application to Facebook.

To Register your application with Facebook, go to and click on "Set Up New App"

Next, we need to give a name to our application, Lets name it DemoApp. Select the Agree button and click on "Create App".

Interesting fact: If the name of your application contains the word "face", Facebook will show you this little number:

When your Application is created, you will be presented with the following screen:
Select various details about you application such as description, Icon , logo, administrator email etc. Then click on "Save Changes".

Now we have come to the most Important screen from our point of view: The MyApps Page where you will be provided with the App Id and other important IDs for your application. You will only require the App Id to successfully authenticate your windows application with Facebook.

Now that you we have our App Id, we need to create a windows application from which we will share our link on Facebook. We will be using the C#, .NET framework 4 and Visual Studio 2010 for our Application. Create a new Windows Application Project in C# and name it something Relevant. Lets name our project as "FacebookDemo"

Once the Windows application is created, Drag a WebBrowser Control and a Button Control on to the Form. These will be the only two controls we will be using in our application.

Next, we need to reference a couple of DLLs which we will be using in our project. Make sure you have the Facebook.dll  and System.Web Assembly referenced in your project.

OK. Enough of screenshots. Time to do some actual coding!

The Facebook SDK provides us with a variety of inbuilt functions. The actual code won't be difficult at all and it will be extremely easy to understand.
The first step we will do is creating a login URL which will help us authenticate our application with Facebook. The following code snippets will create a login URL for us:
(In the Demo Application, I have written this code on the Button Click event of the Button on our Windows Form)

First, we need to create an Instance of the FacebookOAuthClient. The parameters we will be passing will be your App ID which you got when you registered for Facebook and the Redirect Uri which is the Uri to which our Browser will get redirected to when we are successfully authenticated with Facebook.
 The default Uri is but we will override it with so that you are redirected to your Facebook homepage when the wall post is made.

var oauth = new FacebookOAuthClient
                       ClientId = "",
                       RedirectUri = new Uri("")


Next, we will create a Dictionary object which will determine the Display type and the Respose type which will be returned.
Display type is the method by which the Authentication dialog will be rendered. It is set to “page” by default. We will override it to popup so that it consumes less space.
You can find the various display options here:

The response type is the result given by Facebook on successful authentication.

                var parameters = new Dictionary<string, object>
                                    { "display", "popup" },
                                    { "response_type", "token" }

Next, we define the permissions which our application will have to access the user’s data. Right now, since we only need to share a link on the wall of the user, we will require only one permission from the user which is the “publish stream” permission. With this permission, our application can post on the wall of the user. The complete list of allowed permissions is available here:

                var extendedPermissions = "publish_stream";

                if (!string.IsNullOrEmpty(extendedPermissions))
                    parameters["scope"] = extendedPermissions;

Finally, we will pass the parameters to the GetLoginUrl function of the FacebookOAuthClient class which will return the login uri.

                var loginUri = oauth.GetLoginUrl(parameters);

We will navigate to the generated loginUri with the webbrowser control which we created on our windows form.

The next step we are going to take is that we are going to check if our login uri is authenticated. We are going to do this by checking the authentication status each time the page changes. The Navigated event of the webbrowser control will be extremely helpful here as it is triggered each time there is a page change.
(In the Demo Application, I have written the following code in the webBrowser1_Navigated event of the webbrowser control so it will get called and check if authenticated each time there is a page change)

First we need to create an instance of the FacebookOAuthResult class which is designed to check and return the result of the authentication request sent to Facebook. TryParse returns true if it is recognized as a OAuth2 Authentication result. There is a property of the FacebookOAuthResult called IsSuccess which is set to true if the OAuth result was successful and we have the access token. You can use the ErrorDescription property to show the user why the error occurred in the authentication.

FacebookOAuthResult authResult;

if (FacebookOAuthResult.TryParse(e.Url, out authResult))
       if (authResult.IsSuccess)
            //Code to post an update to the wall of the user. (Code is given in the next part)

Next, when we are successfully authenticated by Facebook, we will get an access token which can be used to make the wall post.

         var accessToken = authResult.AccessToken;

The FacebookClient Class is used to get and post updates once we are successfully authenticated. So we will create an object of that class with help of the accessToken which we got from the successful authentication earlier.

            FacebookClient fbc = new FacebookClient(accessToken);

            string encodeaccesstoken = HttpUtility.UrlEncode(accessToken);

            var me = fbc.Get(encodeaccesstoken);

Next, we need to create post. This post can be created the same way as you did earlier by creating a Dictionary object and then adding the different parameters to it. The entire list of parameters you can add to your post can be found here:

            var post = new Dictionary<string, object>
                     { "display", "popup" },
                     { "response_type", "token" }
            post.Add("link", "");
            post.Add("message", "The Message You want to Post on Facebook");

I have only added the link (which points to this blog) and the sample message parameters. You can add whichever ones you want.

And the last step is to publish the actual post on Facebook with the Post method of the FacebookClient Class. The parameters passed are the “me/feed” which tells the API where to publish the post and the actual post dictionary object which contains the details about the post.

           fbc.Post("me/feed", post);

You can download the Sample project from here. Be sure to have Visual Studio 2010 Installed.

Tuesday 19 April 2011

Merge DLLs and EXEs with ILMERGE

You might have felt it to be too cumbersome to give your DLLs along with your EXEs when shipping your application. How cool would it be to give your user only ONE file which contains all your DLLs combined with your EXE? Well there is an awesome little freely available tool by Microsoft called ILMERGE which does just that. You can download it from here. After you install it, go to the command prompt and follow this sample syntax which  merges your program EXE with all your DLLs.

ilmerge /targetplatform:v4,C:\Windows\Microsoft.NET\Framework64\v4.0.30319 /target:winexe /out:CombinedFile.exe Initial.exe Library1.dll Library2.dll Library3.dll

ilmerge --> name of the tool

/targetplatform:v4,C:\Windows\Microsoft.NET\Framework64\v4.0.30319 --> The .NET framework version with witch you are working. (Version 4.0 in this case) and the Path where your .NET framework is installed so that we do not need to merge the system DLLs separately.

/target:winexe --> The type of EXE which you want. winexe=windows application & exe= console application.

/out:CombinedFile.exe --> The name of the file which will contain the combined EXE and the DLLs

Initial.exe --> The initial exe which does not have the DLLs merged with it.

Library1.dll Library2.dll Library3.dll --> The various DLLs which you want to merge with yout EXE.

Upper Case URL Encoding in C#

Recently, I was faced with the following problem: I was cloning a HTTP call in C# and had to encode a URL in Upper case as the server was not accepting the URL encoded in lower case.
So basically, what I wanted was:

instead of

I poked around a little and found that by default C# encodes URLs in lowercase. This is what you might call a limitation in C#. So I did the following work around:

I encoded the URL normally through System.Web.HttpUtility.UrlEncode()

And then wrote this simple function which finds the % in the encoded URL and simply converts the next 2 characters to uppercase:

char[] lcencode = System.Web.HttpUtility.UrlEncode(URL).ToCharArray();

for (int i = 0; i < lcencode.Length - 2; i++)
if (lcencode[i] == '%')
lcencode[i + 1] = char.ToUpper(lcencode[i + 1]);
lcencode[i + 2] = char.ToUpper(lcencode[i + 2]);

string ucencode = new string(lcencode);

Now, ucencode will have the URL encoded with Upper Case.