Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

Tutorial: create a Windows Phone OneNote API app

Last modified: January 17, 2015

Applies to: OneNote service

In this article
Create a "hello world" Windows Phone OneNote app
Build and run the app
Additional resources

Use this tutorial to create a simple "hello world" Windows Phone app that uses the Microsoft OneNote API to save HTML documents to a Microsoft OneNote notebook.

You can also download a complete OneNote API Windows Universal sample or OneNote API Windows Phone sample from GitHub.

If you are just getting started with Windows Phone development, visit the Windows Phone Developer Center for information about getting a developer account and Windows Phone development in general. If you are an experienced Windows Phone developer you’ll probably already have some of the resources listed below, but you’ll need to make sure that you have the Live SDK for Windows and the Newtonsoft Json.NET JSON parsing library.

Here’s what you’ll need to use this tutorial:

  • Sign up for a Microsoft account so you can open a developer account and start developing Windows store apps.

  • Live app management site for getting client IDs for your apps.

  • Live SDK for Windows is hosted on GitHub. You include the library in Visual Studio using the NuGet package manager. We recommend you use this library in all Windows Phone apps that use the OneNote API because it makes the OAuth part simpler.

  • Live SDK for Windows Phone apps help gives you information about downloading and using the SDK.

  • This sample was written with Visual Studio 2013 and the Windows Phone SDK. You can also create it with Visual Studio 2012 and the Windows Phone SDK.

  • Newtonsoft Json.NET is a popular Json parsing library for .NET apps. You include the library in Visual Studio using the NuGet package manager. We use the Newtonsoft library in the Windows phone sample.

  • Microsoft BCL Build components provides build infrastructure components so that projects referencing specific Microsoft packages can successfully build. You include the library in Visual Studio using the NuGet package manager.

  • Microsoft BCL Portability Pack enables projects targeting down-level platforms to use some of the types added in later versions of the .NET platform. You include the library in Visual Studio using the NuGet package manager.

  • Microsoft HTTP client libraries includes HttpClient for sending requests over HTTP and other classes used for processing HTTP messages. You include the library in Visual Studio using the NuGet package manager.

  • Your users will need a Microsoft account, and you will need to get a client ID for your app. Follow the instructions in Get a client ID for use with the OneNote API to get a Microsoft account and a client ID for your app.

Create and set up the project

This sample starts with the Windows Phone App template from the Windows Phone SDK.

To create and set up the Windows Phone App project

  1. Start Visual Studio 2013, if it's not already running.

  2. Choose File > New > Project. Select the Windows Phone App template from the Windows Phone group under the Visual C# group. Name the project WindowsPhoneOneNoteServiceHelloWorld.

  3. Right-click the References folder in Solution Explorer. Select Manage NuGet Packages to open the NuGet Package Manager.

  4. Search in the Online category for Live SDK. The Live SDK will appear in the results pane. Choose the Install button. Figure 1 shows how this item will appear in the NuGet Package Manager.

    Figure 1. Install the Live SDK from the NuGet Package Manager

    Install the Live SDK by using NuGet.
  5. Search again in the Online category for Newtonsoft.json. The JSON.NET library will appear in the results pane. Choose the Install button to install this library.

  6. Search again in the Online category for HTTP.Client. The Microsoft HTTP Client Libraries will appear in the results pane. Choose the Install button to install these libraries. You will be prompted to accept the license for the Microsoft.Bcl.Build, Microsoft.Bcl, and Microsoft.Net.Http packages, as in Figure 2. Choose the I Accept button.

    Figure 2. License acceptance window for the Microsoft.Bcl.Build, Microsoft.Bcl, and Microsoft.Net.Http packages.

    Install the BCL components with HTTPClient
  7. Right-click the project name in Solution Explorer and select Add > New Item. Select Class from the Code group under the Visual C# group. Name the new class StandardResponse.cs.

    Figure 3 shows how the contents of your project will look in Solution Explorer after you have added these files.

    Figure 3. Contents of the project in Solution Explorer

    OneNote Windows Phone app project structure.

Now you are ready to create your app.

Define StandardResponse

The StandardResponse class contains information that gets returned in responses from the OneNote API. Replace the contents of the StandardResponse.cs file with the following code to define this class.

using System.Net;

namespace WinPhoneOneNoteServiceHelloWorld
    /// <summary>
    /// Base class representing a simplified response from a service call 
    /// </summary>
    public abstract class StandardResponse
        public HttpStatusCode StatusCode { get; set; }

        /// <summary>
        /// Per call identifier that can be logged to diagnose issues with Microsoft support
        /// </summary>
        public string CorrelationId { get; set; }

    /// <summary>
    /// Class representing standard error from the service
    /// </summary>
    public class StandardErrorResponse : StandardResponse
        /// <summary>
        /// Error message - intended for developer, not end user
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        public StandardErrorResponse()
            this.StatusCode = HttpStatusCode.InternalServerError;

    /// <summary>
    /// Class representing a successful create call from the service
    /// </summary>
    public class CreateSuccessResponse : StandardResponse
        /// <summary>
        /// URL to launch OneNote rich client
        /// </summary>
        public string OneNoteClientUrl { get; set; }

        /// <summary>
        /// URL to launch OneNote web experience
        /// </summary>
        public string OneNoteWebUrl { get; set; }

Define MainPage

The XAML and code in the MainPage.xaml and MainPage.cs files define the interface that the app presents to users. Replace the contents of the MainPage.xaml file with the following XAML to define the interface.

Make your app client ID the value of the ClientId string in this tag: <System:String x:Key="ClientId"><your client id></System:String>.

    SupportedOrientations="Portrait" Orientation="Portrait"

        <!-- Add the client ID for your application from the Live application management page.-->
        <!--Example: 0000000012345678 -->
        <System:String x:Key="ClientId">    </System:String>
        <StaticResource ResourceKey="PhoneFontFamilyNormal"/>
        <StaticResource ResourceKey="PhoneFontSizeNormal"/>
        <StaticResource ResourceKey="PhoneForegroundBrush"/>
    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="OneNote API Sample" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
            <TextBlock Text="Home" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <Button x:Name="btn_CreateSimple" Content="Create simple page" HorizontalAlignment="Left" Margin="17,160,0,0" VerticalAlignment="Top" Width="419" Click="btn_CreateSimple_Click"/>
            <Controls:SignInButton Content="SignInButton" HorizontalAlignment="Left" Margin="126,81,0,0" VerticalAlignment="Top" Scopes="office.onenote_create" Branding="MicrosoftAccount" SessionChanged="onSessionChanged" Width="192" ClientId="{StaticResource ClientId}"/>
            <TextBlock x:Name="infoTextBlock" HorizontalAlignment="Center" Margin="22,26,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="424"/>
            <HyperlinkButton x:Name="hyperlinkCreatedPage" Content="See Page" HorizontalAlignment="Left" Margin="160,539,0,0" VerticalAlignment="Top"  Click="HyperlinkButton_Click" Visibility="Collapsed"/>




The code in MainPage.xaml.cs defines that logic that drives the user interface. It also handles authentication with the user’s Microsoft account and sending and receiving calls to and from the OneNote API. Replace the contents of the MainPage.xaml.cs file with the following code.

using Microsoft.Live;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Resources;

namespace WinPhoneOneNoteServiceHelloWorld
    public partial class MainPage : PhoneApplicationPage

        // TODO: Replace sample ClientId on MainPage.xaml with your own ClientId

        private string m_AccessToken = null;
        private StandardResponse m_Response = null;

        // v1.0 Endpoints        
        private const string PAGESENDPOINT = "https://www.onenote.com/api/v1.0/pages";

        // Constructor
        public MainPage()


        private void onSessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
            if (e.Status == LiveConnectSessionStatus.Connected)
                m_AccessToken = e.Session.AccessToken;

                infoTextBlock.Text = "Authentication successful";

                infoTextBlock.Text = "Authentication failed.";


        private async void btn_CreateSimple_Click(object sender, RoutedEventArgs e)

            string date = GetDate();

            /////////////// Add the first part /////////////////
            string simpleHtml = "<html>" +
                          "<head>" +
                          "<title>A page created from basic HTML-formatted text (WinPhone8 Sample)</title>" +
                          "<meta name=\"created\" content=\"" + date + "\" />" +
                          "</head>" +
                          "<body>" +
                          "<p>This is a page that just contains some simple <i>formatted</i> <b>text</b></p>" +
                          "</body>" +

            // Create the request message, which is a multipart/form-data request
            var createMessage = new HttpRequestMessage(HttpMethod.Post, PAGESENDPOINT)
                Content = new StringContent(simpleHtml, System.Text.Encoding.UTF8, "text/html")

            HttpClient httpClient = new HttpClient();

            // Add Authorization header
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", m_AccessToken);

            // Note: API only supports JSON return type.
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = await httpClient.SendAsync(createMessage);

            await EndRequest(response);


        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
            if (m_Response as CreateSuccessResponse != null)
                CreateSuccessResponse successResponse = (CreateSuccessResponse)m_Response;
                WebBrowserTask webTask = new WebBrowserTask();
                webTask.Uri = new Uri(successResponse.OneNoteWebUrl, UriKind.Absolute);

        /// <summary>
        /// Get date in ISO8601 format with local timezone offset
        /// </summary>
        /// <returns>Date as ISO8601 string</returns>
        private static string GetDate()
            return DateTime.Now.ToString("o");

        private void StartRequest()
            infoTextBlock.Text = "Sending Request...";
            hyperlinkCreatedPage.Visibility = Visibility.Collapsed;
            m_Response = null;

        private async Task EndRequest(HttpResponseMessage response)
            m_Response = await TranslateResponse(response);

            if (response.StatusCode == HttpStatusCode.Created)
                infoTextBlock.Text = "Page successfully created.";
                hyperlinkCreatedPage.Visibility = Visibility.Visible;

                infoTextBlock.Text = "Page creation failed with error code: " + response.StatusCode;
                hyperlinkCreatedPage.Visibility = Visibility.Collapsed;


        private async static Task<StandardResponse> TranslateResponse(HttpResponseMessage response)
            StandardResponse standardResponse;
            if (response.StatusCode == HttpStatusCode.Created)
                dynamic responseObject = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
                standardResponse = new CreateSuccessResponse
                    StatusCode = response.StatusCode,
                    OneNoteClientUrl = responseObject.links.oneNoteClientUrl.href,
                    OneNoteWebUrl = responseObject.links.oneNoteWebUrl.href
                standardResponse = new StandardErrorResponse
                    StatusCode = response.StatusCode,
                    Message = await response.Content.ReadAsStringAsync()

            // Extract the correlation ID.  Apps should log this to collect data to diagnose failures with Microsoft support 
            IEnumerable<string> correlationValues;
            if (response.Headers.TryGetValues("X-CorrelationId", out correlationValues))
                standardResponse.CorrelationId = correlationValues.FirstOrDefault();

            return standardResponse;

Once you have finished setting up and writing the app, test it by choosing F5 and running it in either the emulator that comes with the Windows Phone SDK or on the local machine.

Figure 4 shows how the app will appear once you’ve started it.

Figure 4. App start page

OneNote Windows Phone app launch page.
© 2015 Microsoft