Tutorial: create a Windows Store OneNote API app
Last modified: January 17, 2015
Applies to: OneNote service
In this article
Create a "hello world" Windows 8 OneNote app
Define MainPage
Build and run the app
Additional resources
Note
|
|---|
|
Please use our new documentation site. It contains content for working with consumer and enterprise OneNote APIs. |
Learn how to create a simple "hello world" Windows 8 app that uses the Microsoft OneNote API to save an HTML page to a Microsoft OneNote notebook.
You can also download a complete OneNote API Windows Universal sample or OneNote API Windows Store sample from GitHub.
If you are just getting started with Windows 8 development, visit the Windows Store apps Dev Center for information about getting a developer account and Windows 8 development in general. If you are an experienced Windows 8 developer you’ll probably already have some of the resources listed below, but you’ll need to be sure that you have the Live SDK for Windows.
Here’s what you’ll need in order to use this tutorial:
-
Sign up for a Microsoft account so you can open a developer account and start developing Windows store apps.
-
Windows Store apps Dev Center is the main entry point to the world of Microsoft Windows Store app development.
-
Sign up for a developer account so you can get package identities for your apps.
-
Windows Store Dashboard is where you manage your store apps and create package identities.
-
This sample was written with Visual Studio 2013 and the Windows Software Development Kit (SDK) for Windows 8.1.
-
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 store apps that use the OneNote API because it makes the OAuth part simpler.
-
Live SDK for Windows Store apps help gives you information about downloading and using the SDK.
Create and set up the project
Before you get started in writing the code, follow the instructions for creating a new package identity for Windows Store apps in Get a client ID for use with the OneNote API. The following instructions explain how to associate your app with the new package identity.
To create and set up your app in Visual Studio
-
Start Visual Studio 2013, if it's not already running.
-
Choose File > New > Project. Select the Blank App (XAML) template from the Windows Store group under the Visual C# group. Name the project OneNoteWindowsStoreHelloWorld.
-
Choose Right-click the References folder in Solution Explorer. Select Manage NuGet Packages to open the NuGet Package Manager.
-
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
-
Right-click the project name in Solution Explorer, choose the Store menu, and then choose Associate App with the Store.
-
Sign in with your Windows Store credentials.
-
Select the app name that you created in the Windows Store. Choose the Next button to verify the information that will be added to your app's manifest file, and then choose the Associate button. The package identity will now appear in the Packaging tab of the Package.appmanifest editor.
Figure 2 shows how the contents of your project will look in Solution Explorer after you have added these files.
Figure 2. Contents of the project in Solution Explorer
Now, write the code for your app.
The XAML and code in the MainPage.xaml and MainPage.cs files define the interface that the app presents to users. Add the following XAML to the MainPage.xaml file to define the interface. Include this XAML inside the <Page> tag.
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Canvas HorizontalAlignment="Left" Height="678" Margin="100,80,0,0" VerticalAlignment="Top" Width="1000"> <Button x:Name="btnLogin" Content="Sign In" Canvas.Left="20" Click="btnLogin_Click" /> <Button x:Name="btnCreatePage" Content="Create Page" Height="40" Width="138" Canvas.Top="54" Canvas.Left="20" FontWeight="Bold" Background="GhostWhite" Foreground="DarkBlue" FontSize="12" Click="btnCreate_Page" /> <TextBox x:Name="tbResponse" Height="700" Canvas.Left="20" Canvas.Top="140" Width="850" FontSize="12" AcceptsReturn="True" /> </Canvas> </Grid>
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 the OneNote API. Replace the contents of the MainPage.xaml.cs file with the following code. The app uses information from the package manifest to identify itself to the OneNote API, so you don’t need to include a client id anywhere in the code.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Microsoft.Live;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace OneNoteWindowsStoreHelloWorld
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
// Define the permission scopes
private static readonly string[] scopes = new string[] { "wl.signin", "wl.basic", "Office.OneNote_Create" };
// Set up the Live variables
private LiveAuthClient authClient;
private LiveConnectClient liveClient;
// URI for the OneNote API
private static readonly Uri PagesEndPoint = new Uri("https://www.onenote.com/api/v1.0/pages");
public MainPage()
{
this.InitializeComponent();
tbResponse.Text = string.Empty;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.InitializePage();
}
//Log in the user when the page is loaded so that the user doesn't have to use the sign in button.
private async void InitializePage()
{
try
{
authClient = new LiveAuthClient();
LiveLoginResult loginResult = await authClient.InitializeAsync(scopes);
if (loginResult.Status == LiveConnectSessionStatus.Connected)
{
liveClient = new LiveConnectClient(loginResult.Session);
}
}
//Use the text box to display any exceptions.
catch (LiveAuthException authExp)
{
tbResponse.Text = authExp.ToString();
}
}
private async void btnLogin_Click(object sender, RoutedEventArgs e)
{
try
{
LiveLoginResult loginResult = await authClient.LoginAsync(scopes);
// Use the text box to indicate whether the user is logged in.
if (loginResult.Status == LiveConnectSessionStatus.Connected)
{
liveClient = new LiveConnectClient(loginResult.Session);
tbResponse.Text = "logged in";
}
}
// Use the text box to display exceptions.
catch (LiveAuthException authExp)
{
tbResponse.Text = authExp.ToString();
}
}
/// <summary>
/// Create a simple page with some formatted text.
/// </summary>
private async void btnCreate_Page(object sender, RoutedEventArgs e)
{
await CreatePage();
}
// Create a simple HTML page and send it to the OneNote API
private async Task CreatePage()
{
try
{
var client = new HttpClient();
// Note: API only supports JSON return type.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// This allows you to see what happens when an unauthenticated call is made.
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authClient.Session.AccessToken);
}
string date = GetDate();
string simpleHtml = "<html>" +
"<head>" +
"<title>A simple page created from basic HTML-formatted text on Windows 8.</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>" +
"<p>Here is a <a href=\"http://www.microsoft.com\">link</a></p>" +
"</body>" +
"</html>";
var createMessage = new HttpRequestMessage(HttpMethod.Post, PagesEndPoint)
{
Content = new StringContent(simpleHtml, System.Text.Encoding.UTF8, "text/html")
};
HttpResponseMessage response = await client.SendAsync(createMessage);
tbResponse.Text = response.ToString();
}
catch (Exception e)
{
tbResponse.Text = e.ToString();
}
}
/// <summary>
/// Get date in ISO8601 format with local time zone offset
/// </summary>
/// <returns>Date as ISO8601 string</returns>
private static string GetDate()
{
return DateTime.Now.ToString("o");
}
/// <summary>
/// Does the object currently have a valid authenticated state
/// </summary>
public bool IsAuthenticated
{
get { return authClient.Session != null && !string.IsNullOrEmpty(authClient.Session.AccessToken); }
}
}
}
Once you have finished setting up and writing the app, test it by pressing F5 and running it in either the emulator that comes with the Windows Software Development Kit (SDK) for Windows 8.1 or on the local machine.
Figure 3 shows how the app will appear once you’ve started it.
Note