Using Skydrive REST API

28. April 2013 21:52

API Cloud Microsoft Projects Utils 

I have created a wrapper class to simplify my work with REST API. I assume that you will be using a web application. First step is to create an application at Once the application is created you will have the ClientID, Client Secret and Redirect domain. We will be using a ClientID and Redirect domain. Remember that the Redirect domain value cannot have localhost. You must provide a correct domain name as after successful authentication you, the user will be redirected to the domain along with the access token.

In the response you will get the access token which will be available to you for the next 3600 seconds. The access token will be in the returning URL of your domain. In my case it is…. I will then retrieve the access token and pass it to my wrapper which will do the work for me.

Time to look and understand the code a bit. I have been using SkyDrive a lot for backup and sharing files and I also access SkyDrive from a web application I have built. But the code is pretty messy and needs revision. So I created a wrapper around the API.

First I need to authenticate the user with his/her live credentials with correct scopes. If scopes are wrong you will not be able to perform actions to the SkyDrive. To learn more about scopes read here. As I am working with SkyDrive I am using 2 scopes wl.signin and wl.skydrive_update. wl.skydrive_update is necessary if you want to have write access to SkyDrive. The SkyDriveAPI wrapper class has the Authenticate method which will redirect you to authentication screen of live service. Once you enter your credentials you will then be redirected to the domain (the domain you provided while you created the application) along with the access token. Here is the sample code:

public void Authenticate()
    string authorizeUri = AuthUri;
    authorizeUri = authorizeUri + String.Format("?client_id={0}&", _ClientId);
    authorizeUri = authorizeUri + String.Format("scope={0}&", "wl.signin,wl.skydrive_update");
    authorizeUri = authorizeUri + String.Format("response_type={0}&", "token");
    authorizeUri = authorizeUri + String.Format("redirect_uri={0}", HttpUtility.UrlEncode(_SiteURL));
    this.AuthURI = authorizeUri;

This is an insight of the wrapper class. In the actual scenario you will never be using it this way:

SkyDrive drive = new SkyDrive(ClientID, Site URL);

In the constructor of the SkyDrive class, the first parameter will be your ClientID and the second one will be the Site URL or the redirect domain. After this the SkyDrive class object drive (whatever the name you give) will call the Authenticate method to generate the URL with all the required parameters and store the URL in the public variable called AuthURI, which I used to redirect the user to authenticate using his credentials.

Now Once the user is authenticated you will be provided with the access token in the URL. It depends on you how you are going to fetch it. Once you fetch the access token you then need to keep it safe. To make sure that the access token remains with your API calls, save it like this:

drive.AccessToken = "EwBIA.....";

Once you have the access token, you are all good to make your first call to SkyDrive. For the simplicity, I am making a request to call get the basic user information.

User usr = drive.GetUserInfo();

Moreover you can also list all the folders in your SkyDriver with this simple call.

Folder driveFolders = new Folder();
foreach (var folder in driveFolders)
    Response.Write(folder.Value + " " + folder.Key +"<br/>");

The above code returns a Dictionary which contains the name of the folder and id of the folder. You’ll need the folder id in order to list down all the files in the folder. To list down all the files in a folder use the below code.

FolderContent content = drive.ListFolderContent("folder.77e33dba68367a16.77E33GBA68467A16!2189");
for (int i = 0; i < content.Files.Count; i++)

It is not just the name of the files you get but you get the complete properties of the file. So you can play around with that too.

Coming to the most searched feature of SkyDriver REST API is to how to upload a file using REST API. The MSDN states that you can upload the files to SkyDriver by making HTTP POST or HTTP PUT requests. Here is how I am doing it inside my wrapper class.

public bool UploadFile(string FolderID, string FilePath)
    bool Uploaded = false;
        byte[] fileBytes = System.IO.File.ReadAllBytes(FilePath);
        string UploadURI = BaseURI + FolderID + "/files/" + Path.GetFileName(FilePath) + "?access_token=" + AccessToken;
        var request = (HttpWebRequest)HttpWebRequest.Create(UploadURI);
        request.Method = "PUT";
        request.ContentLength = fileBytes.Length;
        using (var dataStream = request.GetRequestStream())
            dataStream.Write(fileBytes, 0, fileBytes.Length);
        string status = (((HttpWebResponse)request.GetResponse()).StatusDescription);
        if (status.ToLower() == "created")
            Uploaded = true;
        return Uploaded;
    catch (Exception)
        return false;

I am using a PUT method to upload files to SkyDrive. At this moment I have not implemented the POST method. But in near future I will. If you are using my wrapper class then the just use a single line of code to upload a file to a particular folder.

bool uploaded = drive.UploadFile("folder.77e33dba68367a16.77E33DUA68567A16!104", "D:\\walls\\flowers_442.jpg");

Calling the UploadFile method will upload a file to the folder. The first parameter in the above method is the folder id where you want to upload the folder and the second one is the local file path.

I am currently working and trying to understand the REST API and its features. I will include other functions as more and more I learn about them.

The SkyDrive API Wrapper is hosted on GitHub. Fork it, change it, customize it as you wish. And if you have or found something good, then please do let me know.

I want to give the credit to Christophe Geers for his post which gives me an insight of the API.

 No Rating

Integrate Windows Live SignIn Support In ASP.NET

28. July 2012 12:35


Last year I wrote a post on how you can integrate OpenID support in your ASP.NET application. Few days back as usual I was chasing Windows Live SDK updates on Twitter and yes the most awaited SkyDrive API was made available to all the developers. I will be writing a post later on how to upload files using SkyDrive API.

Setting up the application

To integrate Windows Live Sign-In support I have downloaded the LiveService samples from Github and take a look at ASP.NET sample. All the hard work has been done for you from before. First you need to create an application at Once you create an application, you will get the Client ID and Client secret for the application which we will be using in our application.

Now you have the Client ID and Client secret, you then need to update the same in the Callback.aspx code-behind. The redirect domain will be the name of the domain. In my case I have hosted the complete solution which you can try here. The pretty looking Sign In button rendered on the page is from the JavaScript code.

When you click on the button it will open a window which will ask your Live or Hotmail credentials.

After you successfully authenticated from Live service, it will return you the authentication code. For your ease I have made the authentication code (along with the URL that retrieves the user's image) available to you through a JavaScript alert.

Don't waste your time in looking into the alert message. Just press CTRL+C to copy the whole message and paste it into notepad. Now it's time to look into it carefully. If you quickly open a new tab in your browser and paste the copied URL, then you will get the image of the user who is authenticated. To get more information about the user, modify the URL in the notepad to this:

Note that from the URL above I have removed /picture. Now hit the new URL to the browser again, and this time the output has more information:

The question comes here is: What if I want to get the contacts of the authenticated user or want to get the list of folders in his/her SkyDrive? To understand this, consider that Windows Live is a big application which is built up with small applications like mail, SkyDrive, calendar etc. Now if someone wants to access any part of the application we need to specify which part of the application we need to access. For us (programmers) it is called Scope. The test application I am demonstrating here has the following scopes: wl.signin, wl.basic, wl.offline_access, wl.skydrive. To grant access to your application you should provide the correct scopes in your application. To know more about scopes read here

After everything went fine and I was successfully authenticated I get my picture with Windows Live (it's 2 year old) and the Sign in button changed to Sign out:

You can also display other user information, if you wish. I have compiled all the files under one hood for your ease and you only have to create a new application, get the Client ID and Client secret and update it into the application.

Download: (9.71 kb)

 No Rating

Minify Your CSS & Javascript With SquishIt

15. April 2012 06:38


No one likes if their favourite site is loading up slow. Using CSS sprites instead of using individual images and minify javascript and css files is a way to minimize the request send to the server and also saves you few KBs or may be even MBs. If your site is high on using javacript and CSS then you should minimize them.

I recently used SquishIt to combine/minimize my CSS and javascript files. I found 2 major benefits, first, I am able to combine all of my CSS files into one and minimize it, and second it reduces the request sent to the server to load several .css and .js files. In a typical web application I can have one style sheet and one javascript or jQuery file, but if I am planning to use some plugins then there might be more than one style sheet and javascript files which will get loaded on every page request. Here is an example of a sample web forms application loading two css and javascript files which includes the plugin code. 

Here you can see that there are 4 requests in total to load site CSS and Javascript files. Though in this case the size of the file is less but when you have really large files then it can really affect your site performance and also save MBs in a long run. So, what happens when I use SquishIt? Install the package by firing the below command at NuGet console.


SquishIt is not an independent package, it has dependencies which is doing all the work of minifying and compressing CSS and JS files behind the scenes.


After the package is installed successfully, time to squish the files. Open the web page or the master page where you are loading CSS and JS files (in my case it is site.master) and add a reference to the SquishIt assembly on the top of that page.

<%@ Import Namespace="SquishIt.Framework" %>

In the head section of your page we can then combine all the CSS and JS files and then render them into ONE single file. There are two different methods to minimize CSS and JS files i.e. Bundle.Css() for CSS files and Bundle.JavaScript() for JS files. Here is an example:

To bundle CSS:

<%= Bundle.Css()

To bundle JavaScript:

<%= Bundle.JavaScript()

You can go on adding all the css and javascript files using the Add() method. After all the files has been added call the Render() method. You can say that the Add()method just keep all the files in a stack and the Render() method will combine and minimize the files. If you look closely in the Render() method has a new file name with a (hash) #. The hash symbol is just generates a new unique id of the bundled script.

When you run the application and check the network call stack in your browser, you'll find that the files are not combined. The page is still loading 4 files!? To overcome this set the debug mode to false in the web.config file.

<compilation debug="false" targetFramework="4.0" />

Now if you look in the network call stack, you will find the files have been squished and minimised and compressed!!

And here are my saving statistics:

Without SquishIt:

Four requests in total!!

Name/Path Type Size Content Time Latency
adipoli.css text/css 683B 62ms
/Styles 441B 55ms
Site.css text/css 4.40KB 68ms
/Styles 4.16KB 61ms
jquery-1.7.1.min.js application/x-javascript 109.91KB 80ms
/Scripts 109.65KB 67ms
jquery.adipoli.min.js application/x-javascript 7.57KB 242ms
/Scripts 7.32KB 163ms

The Squish effect:

Two requests in total. Check out the file size and content being loaded. 

Name/Path Type Size Content Time Latency
squishstyle6788C36F832FE70161B88F2D08193F3E.css text/css 2.95KB 80ms
/Styles 2.71KB 72ms
squishjs0F44BB5917C6332E4D49DFCDA5F3556D.js application/x-javascript 98.29KB 91ms
/Scripts 98.03KB 76ms

The same can be done in MVC with this NuGet package.

Currently rated 5.0 by 1 person

BingMap.JS - Jquery Plugin For Bing Maps

10. March 2012 16:39

API Jquery Microsoft Projects 

Bing maps are out there for a long time now and is getting mature pretty fast. I have used Bing maps myself in few of my projects and I remember as a first time user I have a hard time configuring it according to my project requirement. To get myself out of the overhead I searched the web for a jquery plugin, but I can't find a single jquery plugin for Bing Maps instead I found few for Google Maps. I do have some knowledge of jquery and Bing map API, so I decided to write a jquery plugin for Bing map in my free time that will handle all necessary configurations and all the hard work for me and more importantly save my time.

How I get started and how it ended up

Initially I started writing a plugin to just set up the default configuration like setting the map with different modes, zoom level and other necessary configurations, but I ended up doing something more. Besides just the normal configurations of the map I was also able to incorporate Bing map API to search and pinpoint the address on the map. Now if you have an address and you want that to be located on the map then you just have to write in the address in the address parameter and do the other necessary configuration like if you want to show the pushpin on the map or not, or you can set the description on the balloon tip when the user hover the mouse on the pushpin. You can also change the view modes and can also set the zoom level. Plenty of stuff in the plugin and I will add more to make it more flexible and more productive. The API thing in the plugin was just the test from my side, I never thought of using the API in the plugin when I started writing it. But I am happy that I ended up making something useful for myself and I am sure enough that it will help other fellow developers out there also.

Where to get the plugin?

I have a dedicated a page for the Bing Map plugin here. There are still few changes to be made on the page so that it can have more information. In the next phase I am planning to have a demo page and provide more information on plugin.

Make sure to read about the plugin and the configurations before you get started with the plugin at Bing map plugin home page.

If you are using NuGet then you can fire up the below command to install it into the Scripts folder.

If you have doubts and have suggestions for the plugin then please do drop me a comment or e-mail.

 No Rating

Add Google Login Support In ASP.NET With OpenID

18. February 2012 17:12


Few years back I blogged about adding OpenID login support in ASP.NET application. This time I am blogging about adding Google login support in ASP.NET application. A friend of mine is trying to integrate multiple third party authentication support for one of the application he is developing for his client. He is using DotNetOpenAuth for Google authentication. the code I am using here is from my friend and I am sharing it with his explicit permission.

First, download the latest version of DotNetOpenAuth and add its reference in your web application and these two namespaces.

using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.RelyingParty;

After adding the reference, add a normal button with CommandArgument to point

<asp:Button ID="btnGoogleLogin" runat="server" CommandArgument="" 
        OnCommand="btnGoogleLogin_Click" Text="Sign In with Google" />

On the button click event on the server side:

protected void btnGoogleLogin_Click(object sender, CommandEventArgs e)
    string discoveryUri = e.CommandArgument.ToString();
    OpenIdRelyingParty openid = new OpenIdRelyingParty();
    var URIbuilder = new UriBuilder(Request.Url) { Query = "" };
    var req = openid.CreateRequest(discoveryUri, URIbuilder.Uri, URIbuilder.Uri);

Now when you click the button it will take you to Google login page which look something like this.

You can see on the right side of the screen with the information of the site requesting the authentication. Once you get successfully authenticated with your entered user name and password, you will then redirect to the confirmation page:

As I am using my local development server, you will see Locahost. Once you deploy the application in the production environment it will automatically get the name of the domain. Clicking on the Sign in button you will then be redirected to the main page, but before you get to the main page you need to check whether the authentication was successful or was it cancelled by the user or was failed. To make sure use the below code on the load event of the login page:

protected void Page_Load(object sender, EventArgs e)
    OpenIdRelyingParty rp = new OpenIdRelyingParty();
    var response = rp.GetResponse();
    if (response != null)
        switch (response.Status)
            case AuthenticationStatus.Authenticated:
                Session["GoogleIdentifier"] = response.ClaimedIdentifier.ToString();
            case AuthenticationStatus.Canceled:
                Session["GoogleIdentifier"] = "Cancelled.";
            case AuthenticationStatus.Failed:
                Session["GoogleIdentifier"] = "Login Failed.";


On Default.aspx page I have set the ClaimedIdentifier:

The response/status returned from Google will be checked here and we will redirect the application to work the way accordingly. My friend sends me the above code to find out whether there is any way we can logout from the service. Well, unfortunately there isn't any specific way to log out using DotNetOpenAuth? But there is a workaround. I don't know if it is a good practice or bad but it worked out for me. To logout, I am just calling this logout URL used by Google.

If you have some suggestions or you know a better way or approach of doing this then please drop a line in the comments sections.

Currently rated 4.2 by 9 people