Skip to content

Latest commit

 

History

History
 
 

day25-onenote

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

Day 25 - Create a OneNote notebook and page

Prerequisites

To complete this sample you need the following:

  • Complete the Base Console Application Setup
  • Visual Studio Code installed on your development machine. If you do not have Visual Studio Code, visit the previous link for download options. (Note: This tutorial was written with Visual Studio Code version 1.28.2. The steps in this guide may work with other versions, but that has not been tested.)
  • .Net Core SDK. (Note This tutorial was written with .Net Core SDK 2.1.403. The steps in this guide may work with other versions, but that has not been tested.)
  • C# extension for Visual Studio Code
  • Either a personal Microsoft account with a mailbox on Outlook.com, or a Microsoft work or school account.

If you don't have a Microsoft account, there are a couple of options to get a free account:

Step 1: Update the App Registration permissions

As this exercise requires new permissions the App Registration needs to be updated to include the Notes.ReadWrite.All permission using the new Azure AD Portal App Registrations UI (in preview as of the time of publish Nov 2018).

  1. Open a browser and navigate to the Preview App Registration within Azure AD Portal. Login using a personal account (aka: Microsoft Account) or Work or School Account with permissions to create app registrations.

    Note: If you do not have permissions to create app registrations contact your Azure AD domain administrators.

  2. Click on the .NET Core Graph Tutorial item in the list

    Note: If you used a different name while completing the Base Console Application Setup select that instead.

  3. Click API permissions from the current blade content.

    1. Click Add a permission from the current blade content.

    2. On the Request API permissions flyout select Microsoft Graph.

      Screenshot of selecting Microsoft Graph permission to add to app registration

    3. Select Application permissions.

    4. In the "Select permissions" search box type "Notes.Read".

    5. Select Notes.ReadWrite.All from the filtered list.

      Screenshot of adding application permission for Notes.ReadWrite.All permission

    6. Click Add permissions at the bottom of flyout.

  4. Back on the API permissions content blade, click Grant admin consent for <name of tenant>.

    Screenshot of granting admin consent for newly added permission

    1. Click Yes.

Step 2: Extend the app to OneNote

In this step you will create a OneNoteHelper class that encapsulates the logic for getting and creating OneNote notebooks, sections, and pages and then add calls to the console application created in the Base Console Application Setup to implement each of these functionalities.

Create the OneNoteHelper class

  1. Create a new file in the Helpers folder called OneNoteHelper.cs.

  2. Replace the contents of OneNoteHelper.cs with the following code:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Net.Http;
    using System.Threading.Tasks;
    using Microsoft.Graph;
    
    namespace ConsoleGraphTest
    {
        public class OneNoteHelper
        {
    
        }
    }
  3. Inside the OneNoteHelper class add a private GraphServiceClient, HttpClient, and constructors for the class using each separately.

    private GraphServiceClient _graphClient;
    private HttpClient _httpClient;
    public OneNoteHelper(GraphServiceClient graphClient)
    {
        if (null == graphClient) throw new ArgumentNullException(nameof(graphClient));
        _graphClient = graphClient;
    }
    
    public OneNoteHelper(HttpClient httpClient)
    {
        if (null == httpClient) throw new ArgumentNullException(nameof(httpClient));
        _httpClient = httpClient;
    }
  4. Next add methods to get and create a OneNote notebook.

    public Notebook GetNotebook(string upn, string notebookName)
    {
        List<QueryOption> options = new List<QueryOption>
        {
            new QueryOption("$filter", $"DisplayName eq '{notebookName}'")
        };
        var notebooks = (_graphClient.Users[upn].Onenote.Notebooks.Request(options).GetAsync()).Result;
    
        if(notebooks.Count > 0)
        {
            return notebooks[0];
        }
        else
        {
            return null;
        }
    }
    
    public async Task<Notebook> CreateNoteBook(string upn, string notebookName)
    {
        var notebook = new Notebook{
            DisplayName = notebookName
        };
    
        return (await _graphClient.Users[upn].Onenote.Notebooks.Request().AddAsync(notebook));
    }
  5. Next add methods to get and create a section in a OneNote notebook.

    public OnenoteSection GetSection(string upn, Notebook notebook, string sectionName)
    {
        List<QueryOption> options = new List<QueryOption>
        {
            new QueryOption("$filter", $"DisplayName eq '{sectionName}'")
        };
    
        var sections = (_graphClient.Users[upn].Onenote.Notebooks[notebook.Id].Sections.Request(options).GetAsync()).Result;
    
        if(sections.Count > 0)
        {
            return sections[0];
        }
        else
        {
            return null;
        }
    }
    
    public async Task<OnenoteSection> CreateSection(string upn, Notebook notebook, string sectionName)
    {
        var section = new OnenoteSection{
            DisplayName = sectionName
        };
    
        return (await _graphClient.Users[upn].Onenote.Notebooks[notebook.Id].Sections.Request().AddAsync(section));
    }
  6. Last add methods to get and create a page in a OneNote section.

    public OnenotePage GetPage(string upn, OnenoteSection section, string pageName)
    {
        List<QueryOption> options = new List<QueryOption>
        {
            new QueryOption("$filter", $"Title eq '{pageName}'")
        };
    
        var pages = (_graphClient.Users[upn].Onenote.Sections[section.Id].Pages.Request(options).GetAsync()).Result;
    
        if(pages.Count > 0)
        {
            return pages[0];
        }
        else
        {
            return null;
        }
    }
    
    public async Task<HttpResponseMessage> CreatePage(string upn, OnenoteSection section, string pageName)
    {
        Uri Uri = new Uri($"https://graph.microsoft.com/v1.0/users/{upn}/onenote/sections/{section.Id}/pages");
    
        // use a verbatim interpolated string to represetnt the HTML text to be used for page creation
        var html = $@"
        <!DOCTYPE html>
        <html>
        <head>
            <title>{pageName}</title>
        </head>
        <body>
            I'm learning about the Microsoft Graph!
        </body>
        </html>";
    
        HttpContent httpContent = new StringContent(html, System.Text.Encoding.UTF8, "application/xhtml+xml");
    
        return (await _httpClient.PostAsync(Uri, httpContent));
    }

Extend program to create a OneNote notebook, section, and page

  1. Inside the Program class add a new method OneNoteHelperCall with the following definition. This method creates a OneNote notebook, section, and page. If any of these are already created then it will get a reference to the existing items (except for page which is always created).

    private static void OneNoteHelperCall()
    {
        const string userPrincipalName = "<userPrincipalName>";
        const string notebookName = "Microsoft Graph notes";
        const string sectionName = "Required Reading";
        const string pageName = "30DaysMSGraph";
    
        var onenoteHelper = new OneNoteHelper(_graphServiceClient);
        var onenoteHelperHttp = new OneNoteHelper(_httpClient);
    
        var notebookResult = onenoteHelper.GetNotebook(userPrincipalName, notebookName) ?? onenoteHelper.CreateNoteBook(userPrincipalName, notebookName).GetAwaiter().GetResult();
        Console.WriteLine("Found / created notebook: " + notebookResult.DisplayName);
    
        var sectionResult = onenoteHelper.GetSection(userPrincipalName, notebookResult, sectionName) ?? onenoteHelper.CreateSection(userPrincipalName, notebookResult, sectionName).GetAwaiter().GetResult();
        Console.WriteLine("Found / created section: " + sectionResult.DisplayName);
    
        var pageCreateResult = onenoteHelperHttp.CreatePage(userPrincipalName, sectionResult, pageName).GetAwaiter().GetResult();
    
        var pageGetResult = onenoteHelper.GetPage(userPrincipalName, sectionResult, pageName);
        Console.WriteLine("Found / created page: " + pageGetResult.Title);
    }

    Important Be sure to replace <userPrincipalName> with a valid UPN within your tenant.

  2. Continuing in the Main method add the following code to call the new method.

    OneNoteHelperCall();
  3. Save all files.

The console application is now able to create a OneNote notebook, section, and page. In order to test the console application run the following commands from the command line:

dotnet build
dotnet run