January 2016

Volume 31 Number 1

[Windows 10]

Using the OneDrive REST API in a Windows 10 App

By Laurent Bugnion

In previous frameworks, such as Windows Phone 8, the OneDrive team provided an SDK that was quite comfortable to use, but didn’t give the developer a lot of freedom. For example, the login mechanism was only possible using a built-in button control, of which the developer couldn’t change the appearance, nor the behavior. But the most difficult part was that this predefined experience didn’t let the code be shared between platforms.

Now, however, the OneDrive team provides a modern REST API based on HTTP requests (GET, POST, PUT and so on). This is a flexible way to interact with the gigantic cloud file storage and to build cross-platform code using well-known code-sharing techniques that can run on all Windows platforms, and even on iOS and Android with Xamarin platforms.

This first of a two-part article will show you how to leverage the new OneDrive API to build Universal Windows Platform (UWP) apps. First, you’ll learn how the REST API is working, and how developers are expected to interact with it. You’ll see how the user can log into the system using oAuth and how file system operations (browsing folders, getting file information, getting file content, uploading files and so on) can be leveraged. You’ll also learn how to execute additional operations, such as accessing the App folder and sharing a link to an item with friends.

In the next article, I’ll talk about the OneDrive team’s new Portable Class Library (PCL), which is encapsulating the operations described here in a handy library that can be added to your UWP apps, but also in other supported frameworks such as ASP.NET, Xamarin.iOS, Xamarin.Android or Xamarin.Forms.

Note: In addition to the PCL that can be used on the Xamarin.Android and Xamarin.iOS platforms, the OneDrive team also provides native SDKs for the two platforms.

The Sample Code

You can download sample code from galasoft.ch/s/msdnonedrive. It shows how a simple UWP app can use the low-level REST API to perform operations on the OneDrive service. To demonstrate that the code is easily portable, the same app is also implemented for Xamarin.Android, and the same principles can be applied to other platforms.

Understanding the REST API

REST APIs are using HTTP as transport protocol, and rely on the protocol’s methods (GET, POST, PUT, DELETE and so on) and on standard error codes (200 Success, 400 Bad request, 500 Server error and so on). Each API entry point is accessible through a unique URI that can also have parameters. In some cases, a simple GET method and a query string can be used to send information to the service and get a result, but it’s also possible to build more complex requests by POSTing some objects serialized to JSON.

REST APIs are becoming more and more widespread, and developers should be happy about it as it offers a well-understood way to communicate with Web services. Most important, it makes it possible to build portable components in C# and to use these components on all supported platforms. Another huge advantage is that HTTP is text-based and requests can easily go through firewalls and proxies.

However, communicating with low-level HTTP methods can seem like a lot of work, especially for developers who aren’t accustomed with the latest developments in asynchronous programming. Building an asynchronous client using callbacks was not the nicest experience for a developer, because of the deep nesting and possible threading issues that could arise. Thankfully, two relatively recent developments have made this much easier for C# programmers: the HttpClient component and the async/await keywords. For example, accessing the OneDrive Music folder becomes as easy as building a URI and sending a GET request:

var uri = new Uri(
  "https://api.onedrive.com/v1.0/drive/special/music");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
  new AuthenticationHeaderValue("Bearer", AccessToken);
var json = await client.GetStringAsync(uri);

The resulting JSON code can be deserialized (with the JSON.NET library, for example) in order to get a .NET object that’s used in the application. This code (admittedly without login or error handling) shows how what would be a complex operation becomes simple and fluid. In addition, this code will run flawlessly on any platform that HttpClient supports, which includes Windows Presentation Foundation (WPF), ASP.NET, Windows 10, Xamarin and more.

Registering Your App

Before a call to the OneDrive API can be made, you must register your app in the OneDrive developer center, configure it and obtain the Client ID key. The registration mechanism is described at bit.ly/1GPBaWL.

When you register your new app, make sure to go to the API Settings page and set the “Mobile or desktop client app” setting to “Yes.” All other settings can be left to their default. Then, retrieve the Client ID from the App Settings page, and save it for later.

It’s important to understand the different terms and for what each ID is needed:

  • Client ID: This is a unique ID for your UWP app. You can have multiple client applications connecting to Microsoft services with the same Client ID, but in general it’s recommended to use one Client ID per application. The Client ID is linked to information of the UWP app such as its name, the icon and so on. The Client ID is generated when the app is created and never changes.
  • Client Secret: This is a unique identifier that’s generated when the UWP app is created. However, this code may change during the app’s lifetime. For example, if you think that the Client Secret was hacked, you can generate a new one, update your apps and the hackers’ apps will be denied access. Note that the Client Secret is generally used in server apps only.
  • User ID and Password: When the user logs in, he is asked to enter his username and password. Thanks to OAuth, the login interaction happens between the user and OneDrive only, without the client app’s knowledge. In practice, this is done using a WebView in which the login dialog is shown.
  • Access Token: When a user has successfully logged in, the authentication service returns an Access Token. This token is valid for a certain time only (60 minutes), after which the user must log in again. The token must be sent with every request, to prove that the user is authenticated. This authentication mode is named Token Flow in the documentation.
  • Refresh Token: This token can be requested by the app and saved in order to refresh the Access Token in case it expired. This can be useful if your app is used in background mode for a long time and needs to periodically refresh data without user interaction. This authentication mode is named CodeFlow and is described at bit.ly/1MQ3KOb. In this article, I’ll only use Token Flow, which is easier to implement.

Trying Things Out with a Trial Token

If you want to quickly try a few REST requests without implementing authentication first, the OneDrive Dev Center lets you get a trial token, valid for one hour, which can be used by following these steps:

  • Go to bit.ly/1MQ3KOb.
  • Locate the “Try it now” section and click on the Get Token button.
  • If needed, sign in and confirm that you authorize the Dev Center to access your OneDrive account.
  • After the login succeeds, a trial token appears in the main Web window.
  • Create a new UWP app named TrialOneDrive.
  • Open MainPage.xaml and add a button named TrialButton.
  • Open MainPage.xaml.cs and add an event handler for the TrialButton Click event as shown in the code in Figure 1. Note that this event handler must use the “async” keyword because all OneDrive operations are asynchronous.
  • In the code in Figure 1, replace the string YOUR TRIAL TOKEN with the trial token that you copied from the Dev Center Web site. Do not copy the words “Authorization: bearer”!
  • Place a break point at the last line of the event handler in order to inspect the JSON variable.
  • Run the application and click on the button.
  • Inspect the retrieved JSON code in a watch window. You should be able to see information about your Music folder, such as its name, creation date, last modified date, child count, the folder’s ID (which can be used in various file system operations later), the logged-in username and so on.

Figure 1 Adding an Event Handler for the TrialButton Click Event

TrialButton.Click += async (s, e) =>
{
  var uri = new Uri(
    "https://api.onedrive.com/v1.0/drive/special/music");
  var client = new HttpClient();
  client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", "YOUR TRIAL TOKEN");
  var json = await client.GetStringAsync(uri);
};

Remember that the trial token expires after an hour, so don’t forget to get a new one if you want to demo this application to your boss!

Authenticating with OAuth

Now that you have a registered application and understand the important terms, you can implement authentication. Here are the steps to do that, which are illustrated in Figure 2:

  1. The user initiates the authentication, for instance by clicking a button.
  2. The application checks if an Access Token is available.
  3. If yes, the app is already authenticated and the user can move to the next operation. If no Access Token is available, the application navigates to a XAML page containing a WebView.
  4. The XAML page sets the WebView’s initial URL to load the authentication end point’s page. The XAML page also subscribes to the WebView’s WebNavigationCompleted event, in order to monitor the traffic in this control. You’ll learn how the initial URL is structured a little further in the article.
  5. The WebView loads the HTML from the authentication endpoint.
  6. The user enters his username and password into the HTML authentication page. Note that this interaction is strictly between the user and the OneDrive server. The XAML page acts merely as a container.
  7. The user presses the HTML button that submits the form to the authentication server. If the user has set it up, additional pages are shown to handle two-factor authentication.
  8. If the credentials are correct, the authentication server redirects the WebView to a special URL that indicates a successful log in. This URL also has the Access Token as one of its query string parameters. The XAML page detects that the redirection occurred, and can parse the Access Token from the WebView’s new URL.
  9. The Authentication page parses the Access token from the redirected URI.
  10. The application navigates back to the original XAML page. The Access Token is saved for further requests.

OAuth Workflow
Figure 2 OAuth Workflow

Note: While it is important to understand how OAuth works, Windows 10 developers are fortunate to have an easier alternative called WebAuthenticationBroker. In this article, I use the “low-level” OAuth mechanism and I’ll talk about the WebAuthenticationBroker in the next article.

Understanding the Scopes

When the user logs in, the application needs to inform the OneDrive service about the range of features it will need. This is done by specifying scopes in the authentication URL. The service currently supports the following scopes:

  • Single sign-on: wl.signin.
  • Offline access: wl.offline_access. This lets your application get a Refresh Token. This scope is ignored when the Token Flow authentication is used.
  • Readonly access: onedrive.readonly. This gives your application read-only access to the files and folders. If the application attempts to modify a file, or upload a new file, the service returns the error code 403 Forbidden.
  • Readwrite access: onedrive.readwrite. This gives your application read and write access to the files and folders.
  • AppFolder: onedrive.appfolder. This lets the application access the so-called App Folder. I’ll talk more in detail about this special folder later in this article. Note that this scope is automatically granted when you request the readwrite scope. However, requesting the appfolder explicitly will cause this scope to be mentioned in the dialog shown in Figure 3, which is a better UX.

Figure 3 Starting the Authentication

if (!_service.CheckAuthenticate(
  async () =>
  {
    var dialog = new MessageDialog("You are authenticated!", "Success!");
    await dialog.ShowAsync();
    Frame.GoBack();
  },
  async () =>
  {
    var dialog = new MessageDialog("Problem when authenticating!", "Sorry!");
    await dialog.ShowAsync();
    Frame.GoBack();
  }))
{
  Frame.Navigate(typeof (AuthenticationPage));
};

After the user enters his credentials in the authentication Web page, he’s shown a dialog asking to confirm the permissions requested by the application, as shown in Figure 4. The user can change his mind at any time and revoke some of the permissions. To do this, the user logs into his account on the OneDrive Web site, navigates to Security and Privacy and selects the Manage permissions link under Apps & Services. In the sample, you’ll always request single sign-on, readwrite and appfolder access.

Authentication Confirmation
Figure 4 Authentication Confirmation

Creating the Initial URL

The URL used to start the authentication process needs to carry information about the application itself, the features requested (scopes), the authentication mode and the redirect URI.

The authentication mode can be Token or Code. In this article and the sample, I used the Token mode, which means the user needs to confirm the login at every new start of the application, or after one hour. This sounds annoying, but in fact the user merely has to confirm the login by pressing the Yes button on the authentication dialog, as shown in Figure 4.

The redirect URI is the address to which the OneDrive service will redirect the appli­cation when the login is successful. For a Web application, it’s the URI of a page in your own application, and is configured in the OneDrive developer center, in the API settings tab. But in the case of a UWP app, you should leave this field empty. Instead, you’ll rely on a predefined redirect URI:

htt://login.live.com/oauth20_desktop.srf

Putting All the Pieces Together

Now that you understand how the authentication according to OAuth works, let’s see some code. You can follow this in the simple sample by clicking on the Authenticate button.

You use a class called OneDriveService, which is implemented in a PCL. The OneDriveService is instantiated in App.xaml.cs, and you pass the Client ID to it.

First, your MainPage asks the OneDrive service if it’s already authenticated, which means that an Access Token is already present. You pass two delegates to the CheckAuthenticate method call: an Action which will be called if the authentication is successful, and an Action in case of error.

If the service isn’t already authenticated, the MainPage uses its Frame property to navigate to the AuthenticationPage, as shown in Figure 5. This page is a simple XAML page with a WebView that takes the whole screen, where the user will enter his username and password and confirm.

Figure 5 Code for the AuthenticationPage

public sealed partial class AuthenticationPage
{
  private readonly OneDriveService _service;
  public AuthenticationPage()
  {
    InitializeComponent();
    _service = ((App)Application.Current).ServiceInstance;
    Loaded += (s, e) =>
    {
      var uri = _service.GetStartUri();
      Web.Navigate(uri);
    };
    Web.NavigationCompleted += (s, e) =>
    {
      if (_service.CheckRedirectUrl(e.Uri.AbsoluteUri))
      {
        _service.ContinueGetTokens(e.Uri);
      }
    };
    Web.NavigationFailed += (s, e) =>
    {
      _service.ContinueGetTokens(null);
    };
  }
}

When the page is loaded, you get the authentication URI from the OneDriveService:

https://login.live.com/oauth20_authorize.srf?client_id=000000004C169646&
scope=wl.signin+onedrive.readwrite+onedrive.appfolder&response_type=token&
redirect_uri=https%3A%2F%2Flogin.live.com%2Foauth20_desktop.srf

As explained, this URI carries all necessary information such as Client ID, Client Secret, Scope, Redirect URI and so on.

Note that the WebView will be redirected a few times before the Access token is returned. This is why you always check the redirection URI in the NavigationCompleted event of the WebView. When the oauth20_desktop.srf URI is finally detected, the OneDriveService will retrieve the Access token from the query string parameters. Additional information (expiration, token type, scope, user ID and so on) is passed in the query string, but you’re simply ignoring it here. The Redirect URI with Access token is abbreviated here:

https://login.live.com/oauth20_desktop.srf?lc=1033#access_token=EwB4Aq1D...1iiZA%3d&
token_type=bearer&expires_in=3600&scope=wl.signin%20onedrive.readwrite%20onedrive.appfolder
%20onedrive.readonly&user_id=8e5323e8b7c7a0928d03e10811531234

After the user is authenticated, the application can start interacting with files and folders. In this article, I’ll concentrate on a few operations, but extending the application to include additional services is quite easy once the principles are understood.

The Root Folder

First, I’ll talk about the Root folder. This folder is unique in your OneDrive, and is the parent to each of your other items.

Per the OneDrive documentation, getting the Root folder can be done using the following request: GET /drive/root. This request will return a JSON response as described at bit.ly/1M5w4NV. The JSON response can be deserialized and the information it contains can be used for further requests.

File and Folder Structure At this point, it’s important to understand how the file system is structured. OneDrive relies on a system of facets to provide information about files and folder. For example, a file can also be an Image and a Photo, and provide additional information about the file (such as width/height for the Image and Camera Model for the Photo). The following list shows the facets that are currently available and some of their most important properties:

  • Item (Name, ID, download url, parent reference and so on)
  • Folder (child count)
  • File
  • Audio (album, artist, bit rate, duration, title and so on)
  • Image (width, height)
  • Photo (camera make and model, taken date time)
  • Video (duration, bit rate, width, height)

When you upload a new file to OneDrive, it’ll automatically be analyzed and some metadata will be added. For example, a Word document is just a File. But a picture taken with a camera is a Photo and also an Image, in addition to being a File. Each of these facets carries additional information about the file, as shown in the list.

When you parse the JSON you get from the OneDrive service, you can map these types to C# classes. By inspecting the JSON, you can quite easily find out if an item is a Folder, a File, an Image, a Video and so on. For example, Figure 6 shows an extract of the JSON response for the Root folder. You can see that the folder property carries information about the folder’s child count. If you were getting information about a Photo, you would see the image and photo properties filled up with information about the Width and Height, and about the Camera Make and Model, respectively.

In the sample application provided with this article, you deserialize the JSON in the classes contained in the Response folder, which are mapped to the facet system.

Now that you understand how the response works, you can easily access the Root folder information with the code shown here:

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
  new AuthenticationHeaderValue("Bearer", AccessToken);
var uri = new Uri("https://api.onedrive.com/v1.0/drive/root");
var json = await client.GetStringAsync(uri);
var rootFolder = JsonConvert.DeserializeObject<ItemInfoResponse>(json);

To see the code in action, you can execute the simple sample and press on the Authenticate button first, and then on the Get Root Folder button.

Getting the Folder’s Children Like you see in Figure 6, the response only contains meta-information about the folder. You know how many children the folder has, but you need to execute one more request to get the list of children. Here, too, the OneDrive documentation helps and states that you need to request a GET for /drive/items/{item-id}/children, as shown in Figure 7.

Figure 6 JSON Response for Root Folder

{
  "createdBy": {
    "user": {
      "displayName": "Laurent Bugnion",
      "id": "fb0d8f9700498123"
    }
  },
  "createdDateTime": "2010-11-27T17:09:25.513Z",
  "id": "FB0D8F97004979CD!ABC",
  "lastModifiedBy": {
    "user": {
      "displayName": "Laurent Bugnion",
      "id": " fb0d8f9700498123"
    }
  },
  "lastModifiedDateTime": "2015-10-04T14:36:36.217Z",
  "name": "root",
  "size": 178558187077,
  "webUrl": "https://onedrive.live.com/?cid=fb0d8f9700498123",
  "folder": {
    "childCount": 18
  }
}

Figure 7 Getting the List of Children

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
  new AuthenticationHeaderValue("Bearer", AccessToken);
var request = string.Format("/drive/items/{0}/children", info.Id);
var uri = new Uri(
  "https://api.onedrive.com/v1.0"
  + request);
var json = await client.GetStringAsync(uri);
var response = JsonConvert.DeserializeObject<ParseChildrenResponse>(json);
return response.Value;

In Figure 7, the JSON is deserialized to a class named Parse­ChildrenResponse. This is again mapped to the JSON response, which wraps the list of children into a JavaScript array named value. The ParseChildrenResponse class is shown in Figure 8.

Figure 8 ParseChildrenResponse Class

public class ParseChildrenResponse
{
  public IList<ItemInfoResponse> Value
  {
    get;
    set;
  }
  [JsonProperty("@odata.nextLink")]
  public string NextLink
  {
    get;
    set;
  }
}

Because every child is an ItemInfoResponse, you know how to handle these and decide if each child is a folder, a file, a photo, an audio file, etc.

Note that if you want to avoid placing two calls to retrieve the folder information and populate its children list, it’s also possible to use the following request, which does everything in one call:

 

GET /drive/items/root?expand=children

Understanding Paging When you access a folder with a lot of children, the response sent by the OneDrive service might be incomplete and require paging. By default, the service only returns a list of maximum 200 children. If the folder you’re browsing has more, a property is added to the list of children, called “@odata.nextLink” and can be seen in Figure 8, as well. This property contains the URI for the next request that the application needs to do to get to the next “page.” In a UWP app, you can choose to either immediately call the service to get the next page of items (which would work OK because long lists are virtualized), or you can show a More button and implement page navigation in the app.

Browsing a Subfolder Once you have a folder’s ID, you can easily browse this folder using the following request:

GET /drive/items/{item-id}

This is great when you already have the folder’s ID, but sometimes you don’t have this information. Another syntax lets you retrieve the folder’s information using its path relative to the root instead. You see this syntax in Figure 9.

Figure 9 Browsing a Subfolder by Path

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
  new AuthenticationHeaderValue("Bearer", AccessToken);
var request = string.Format("/drive/root:/{0}", path);
var uri = new Uri(
  "https://api.onedrive.com/v1.0"
  + request);
var json = await client.GetStringAsync(uri);
var result = JsonConvert.DeserializeObject<ItemInfoResponse>(json);
return result;

The App Folder

OneDrive has a few special folders, such as Music, Documents, Photos and so on. One of the special folders was introduced recently: The App Folder. This is a special folder that’s available to your application, for instance to persist roaming settings, upload backups and so on. Note that the App Folder isn’t secure or hidden in any way. In fact, it resides in a folder named Apps, located right at the root of the user’s OneDrive. The app’s App Folder has the same name as the OneDrive application, as entered when you registered it in order to get the Client ID. Note that the application’s name might be localized in different languages, based on the OneDrive application’s settings. The user has full access to the App Folder, through the OneDrive Web site or any application and may even delete the folder if he chooses.

Before the concept of App Folder was introduced, applications were (and many still are) saving their settings and other files in the OneDrive root or in a custom folder. Using the App Folder for these items is much cleaner and a better UX. According to the OneDrive documentation (bit.ly/1MBUkS2), the request to get the App Folder’s information is:

GET /drive/special/approot

As you can see, it’s easy to implement the App Folder in any of your applications!

Downloading a File

What use would OneDrive be if you couldn’t upload or download files? In this section and the next, you’ll see how to perform this critical operation, which is extremely easy.

In order to download a file’s content, OneDrive creates a DownloadUrl that’s saved as a property in the item response. Note, however, that the URL is only valid for a short time, so if the file information was cached, you might need to get the information again from the service first, as shown in Figure 10.

Figure 10 Downloading a File’s Content

public async Task<Stream> RefreshAndDownloadContent(
  ItemInfoResponse model,
  bool refreshFirst)
{
  var client = new HttpClient();
  client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", AccessToken);
  // Refresh the item's information
  if (refreshFirst)
  {
    var request = string.Format("/drive/items/{0}", model.Id);
    var uri = new Uri(
      "https://api.onedrive.com/v1.0"
      + request );
    var json = await client.GetStringAsync(uri);
    var refreshedItem =
      JsonConvert.DeserializeObject<ItemInfoResponse>(json);
    model.DownloadUrl = refreshedItem.DownloadUrl;
  }
  var response = await client.GetAsync(model.DownloadUrl);
  var stream = await response.Content.ReadAsStreamAsync();
  return stream;
}

Once you get the file content stream, you can process it locally, save it and so on. The simple sample asks the user for a location to save the file using a FileSavePicker.

Uploading a File

Similarly, uploading a file is also quite simple once you get the file’s stream. In Windows 10 this can be done with a StorageFile instance, for example with a FileOpenPicker. Once the stream is read, you can upload it to OneDrive. According to the documentation, you need to use a PUT operation:

PUT /drive/items/{parent-id}:/{filename}:/content

The HttpClient supports the PUT method with an HttpContent instance. In this case, because you have the raw file stream, you can use a StreamContent instance. If all you want to save is a text file, you can use a StringContent and so on.

The other information you need to pass to the service is the ID of the folder in which the file will be saved. In the simple sample shown in Figure 11, the parentId is passed to the uploading method. Note that the PUT operation returns a JSON content describing the file’s new information on OneDrive, such as its ID, Web URL, download URL and so on.

Figure 11 Uploading a File’s Content

var content = new StreamContent(stream);
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
  new AuthenticationHeaderValue("Bearer", AccessToken);
var uri = new Uri(
  "https://api.onedrive.com/v1.0"
  + string.Format(
    "/drive/items/{0}:/{1}:/content",
    parentId,
    fileName));
var response = await client.PutAsync(uri, content);
var json = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<ItemInfoResponse>(json);
return result;

In addition to the simple upload described here, the OneDrive API also offers multipart and resumable uploads with a different syntax. The simple upload is OK for files smaller than 100MB. If the file is larger, you should consult the documentation at bit.ly/1PB31Cn.

The last operation that I’ll demonstrate here is how to get a unique “share” link for an item. This operation is convenient to send a unique link to a friend over e-mail, SMS, social media and so on. Figure 12 shows how to get this information, based on the item’s ID. In the sample, you can get a link to the file that you just uploaded in the previous demo.

Figure 12 Getting a Share Link

public async Task<LinkResponseInfo> GetLink(
  LinkKind kind,
  string fileId)
{
  // LinkKind id View or Edit
  var client = new HttpClient();
  client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", AccessToken);
  var request = string.Format("/drive/items/{0}/action.createLink", fileId);
  var uri = new Uri(
    "https://api.onedrive.com/v1.0"
    + request);
  var requestJson = JsonConvert.SerializeObject(
    new RequestLinkInfo
    {
      Type = kind.ToString().ToLower()
    });
  var content = new StringContent(
    requestJson,
    Encoding.UTF8,
    "application/json");
  var response = await client.PostAsync(uri, content);
  var result = JsonConvert.DeserializeObject<LinkResponseInfo>(
    await response.Content.ReadAsStringAsync());
  return result;
}

According to the documentation, the request is a little different than the GET requests you placed previously, because the service needs more detailed information. The “share link” request is as follows: POST /drive/items/{item-id}/action.createLink. The information that you need to post to the service is a JSON snippet with the type of the link: “view” or “edit”, for example: { "type": "view" }

Wrapping Up

There are a few additional operations that I didn’t describe in this article, such as deleting a file, updating a file’s content and synchronizing changes. In general, however, the operations all follow the same pattern, and can be performed using HttpClient, HTTP methods and JSON. Thanks to the advancements in asynchronous programming in the Microsoft .NET Framework, such operations are extremely fluid and easy to implement in any supported framework, including Windows 10 but also WPF, Windows Phone, Xamarin.iOS, Xamarin.Android and so on. With such ease of use, there’s really no reason to not have some kind of cloud interaction in your UWP apps, for example to back content up or to roam settings. In the next article, you’ll see how the freshly released PCL by the OneDrive team will help you make this integration even easier.


Laurent Bugnion is senior director for IdentityMine, one of the leading companies (and a gold partner) for Microsoft technologies. He is based in Zurich, Switzerland. His 2010 book, “Silverlight 4 Unleashed,” published by Sams, is an advanced sequel to “Silverlight 2 Unleashed” (2008). He writes for several publications, is in his ninth year as a Microsoft MVP and is in his second year as a Microsoft Regional Director. He’s the author of the well-known open source framework MVVM Light for Windows, WPF, Xamarin, and of the popular Pluralsight reference course about MVVM Light. Reach him on his blog at galasoft.ch.

Thanks to the following technical experts for reviewing this article: Corrado Cavalli (Gaia) and Ryan Gregg (Microsoft)