├── .nuget ├── NuGet.exe ├── NuGet.Config └── NuGet.targets ├── OneNoteServiceSamplesWinUniversal.Shared ├── Assets │ ├── Logo.jpg │ ├── BizCard.png │ ├── DarkGray.png │ ├── LightGray.png │ ├── MediumGray.png │ └── attachment.pdf ├── App.xaml ├── SharedBasePage.xaml ├── Common │ ├── AppSettings.cs │ ├── RelayCommand.cs │ └── ObservableDictionary.cs ├── OneNoteServiceSamplesWinUniversal.Shared.shproj ├── OneNoteApi │ ├── Pages │ │ ├── PageResponse.cs │ │ ├── DeletePageExample.cs │ │ └── PatchPagesExample.cs │ ├── HttpUtils.cs │ ├── GenericEntityResponse.cs │ ├── Auth.cs │ ├── ApiBaseResponse.cs │ ├── Notebooks │ │ └── PostNotebooksExample.cs │ ├── Sections │ │ └── PostSectionsExample.cs │ ├── SectionGroups │ │ └── PostSectionGroupsExample.cs │ ├── LiveIdAuth.cs │ └── O365Auth.cs ├── OneNoteServiceSamplesWinUniversal.Shared.projitems ├── SharedBasePage.xaml.cs ├── Strings │ └── en-US │ │ └── Resources.resw ├── App.xaml.cs └── DataModel │ └── ItemPageModel.cs ├── OneNoteServiceSamplesWinUniversal.Windows ├── Assets │ ├── Logo.scale-100.png │ ├── SmallLogo.scale-100.png │ ├── StoreLogo.scale-100.png │ ├── WideLogo.scale-100.png │ └── SplashScreen.scale-100.png ├── packages.config ├── Properties │ └── AssemblyInfo.cs ├── Package.appxmanifest ├── SectionPage.xaml.cs ├── SectionPage.xaml ├── HubPage.xaml.cs ├── HubPage.xaml ├── ItemPage.xaml.cs └── OneNoteServiceSamplesWinUniversal.Windows.csproj ├── OneNoteServiceSamplesWinUniversal.WindowsPhone ├── Assets │ ├── Logo.scale-240.png │ ├── SmallLogo.scale-240.png │ ├── StoreLogo.scale-240.png │ ├── WideLogo.scale-240.png │ ├── SplashScreen.scale-240.png │ ├── HubBackground.theme-dark.png │ ├── HubBackground.theme-light.png │ └── Square71x71Logo.scale-240.png ├── packages.config ├── Properties │ └── AssemblyInfo.cs ├── Package.appxmanifest ├── SectionPage.xaml ├── SectionPage.xaml.cs ├── ContinuationManager.cs ├── HubPage.xaml.cs ├── ItemPage.xaml ├── OneNoteServiceSamplesWinUniversal.WindowsPhone.csproj └── HubPage.xaml ├── .gitattributes ├── .gitignore └── OneNoteServiceSamplesWinUniversal.sln /.nuget/NuGet.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/.nuget/NuGet.exe -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/Assets/Logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.Shared/Assets/Logo.jpg -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/Assets/BizCard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.Shared/Assets/BizCard.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/Assets/DarkGray.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.Shared/Assets/DarkGray.png -------------------------------------------------------------------------------- /.nuget/NuGet.Config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/Assets/LightGray.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.Shared/Assets/LightGray.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/Assets/MediumGray.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.Shared/Assets/MediumGray.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/Assets/attachment.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.Shared/Assets/attachment.pdf -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/Assets/Logo.scale-100.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.Windows/Assets/Logo.scale-100.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/Assets/SmallLogo.scale-100.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.Windows/Assets/SmallLogo.scale-100.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/Assets/StoreLogo.scale-100.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.Windows/Assets/StoreLogo.scale-100.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/Assets/WideLogo.scale-100.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.Windows/Assets/WideLogo.scale-100.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/Logo.scale-240.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/Logo.scale-240.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/Assets/SplashScreen.scale-100.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.Windows/Assets/SplashScreen.scale-100.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/SmallLogo.scale-240.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/SmallLogo.scale-240.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/StoreLogo.scale-240.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/StoreLogo.scale-240.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/WideLogo.scale-240.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/WideLogo.scale-240.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/SplashScreen.scale-240.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/SplashScreen.scale-240.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/HubBackground.theme-dark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/HubBackground.theme-dark.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/HubBackground.theme-light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/HubBackground.theme-light.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/Square71x71Logo.scale-240.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinUniversal/master/OneNoteServiceSamplesWinUniversal.WindowsPhone/Assets/Square71x71Logo.scale-240.png -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/App.xaml: -------------------------------------------------------------------------------- 1 | 6 | 7 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/packages.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/SharedBasePage.xaml: -------------------------------------------------------------------------------- 1 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/Common/AppSettings.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Windows.Storage; 5 | 6 | namespace OneNoteServiceSamplesWinUniversal.Common 7 | { 8 | public static class AppSettings 9 | { 10 | public static bool GetProviderO365() 11 | { 12 | object result = false; 13 | ApplicationData.Current.LocalSettings.Values.TryGetValue("ProviderO365", out result); 14 | return (bool)(result ?? false); 15 | } 16 | public static void SetProviderO365(bool isO365) 17 | { 18 | ApplicationData.Current.LocalSettings.Values["ProviderO365"] = isO365; 19 | } 20 | 21 | public static bool GetUseBeta() 22 | { 23 | object result = false; 24 | ApplicationData.Current.LocalSettings.Values.TryGetValue("UseBeta", out result); 25 | return (bool)(result ?? false); // default to true 26 | } 27 | public static void SetUseBeta(bool useBeta) 28 | { 29 | ApplicationData.Current.LocalSettings.Values["UseBeta"] = useBeta; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteServiceSamplesWinUniversal.Shared.shproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 556a67f3-bd06-49be-ae69-e638d2d6a790 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("OneNoteServiceSamplesWinUniversal.Windows")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("OneNoteServiceSamplesWinUniversal.Windows")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Version information for an assembly consists of the following four values: 18 | // 19 | // Major Version 20 | // Minor Version 21 | // Build Number 22 | // Revision 23 | // 24 | // You can specify all the values or you can default the Build and Revision Numbers 25 | // by using the '*' as shown below: 26 | // [assembly: AssemblyVersion("1.0.*")] 27 | [assembly: AssemblyVersion("1.0.0.0")] 28 | [assembly: AssemblyFileVersion("1.0.0.0")] 29 | [assembly: ComVisible(false)] -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("OneNoteServiceSamplesWinUniversal.WindowsPhone")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("OneNoteServiceSamplesWinUniversal.WindowsPhone")] 13 | [assembly: AssemblyCopyright("Copyright © 2014")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Version information for an assembly consists of the following four values: 18 | // 19 | // Major Version 20 | // Minor Version 21 | // Build Number 22 | // Revision 23 | // 24 | // You can specify all the values or you can default the Build and Revision Numbers 25 | // by using the '*' as shown below: 26 | // [assembly: AssemblyVersion("1.0.*")] 27 | [assembly: AssemblyVersion("1.0.0.0")] 28 | [assembly: AssemblyFileVersion("1.0.0.0")] 29 | [assembly: ComVisible(false)] -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/Package.appxmanifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | OneNoteAPISamplesUniversal 6 | OneNoteSamples_MSFT 7 | Assets\StoreLogo.png 8 | 9 | 10 | 6.3.0 11 | 6.3.0 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteApi/Pages/PageResponse.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft Corporation 3 | // All rights reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the ""License""); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS 12 | // OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 13 | // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR 14 | // PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 15 | // 16 | // See the Apache Version 2.0 License for specific language 17 | // governing permissions and limitations under the License. 18 | //********************************************************* 19 | 20 | namespace OneNoteServiceSamplesWinUniversal.OneNoteApi.Pages 21 | { 22 | /// 23 | /// This class represents the OneNote API Pages response 24 | /// Any response from the Pages API (POST/GET etc) can be translated into this object for ease of use. 25 | /// 26 | /// 27 | /// This is not meant to be a comprehensive SDK or data model. 28 | /// This is ONLY a light-weight representation of a OneNote API's page response. 29 | /// The API's HTTP json response is deserialized into this object 30 | /// 31 | public class PageResponse : ApiBaseResponse 32 | { 33 | /// 34 | /// Title of the page 35 | /// 36 | public string Title; 37 | 38 | public override string ToString() 39 | { 40 | return "Title: " + Title + ", Id: " + Id; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/Package.appxmanifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | OneNoteAPISamplesUniversal 7 | OneNoteSamples_MSFT 8 | Assets\StoreLogo.png 9 | 10 | 11 | 6.3.1 12 | 6.3.1 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteApi/HttpUtils.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Threading.Tasks; 6 | using Newtonsoft.Json; 7 | 8 | namespace OneNoteServiceSamplesWinUniversal.OneNoteApi 9 | { 10 | public static class HttpUtils 11 | { 12 | #region Helper methods used in the examples 13 | 14 | /// 15 | /// Convert the HTTP response message into a simple structure suitable for apps to process 16 | /// 17 | /// The response to convert 18 | /// 19 | /// A simple response 20 | public static async Task TranslateResponse(HttpResponseMessage response, HttpStatusCode expectedStatusCode = HttpStatusCode.Created) 21 | { 22 | ApiBaseResponse apiBaseResponse; 23 | string body = await response.Content.ReadAsStringAsync(); 24 | if (response.StatusCode == expectedStatusCode 25 | /* POST calls always return 201-Created upon success */) 26 | { 27 | apiBaseResponse = JsonConvert.DeserializeObject(body); 28 | } 29 | else 30 | { 31 | apiBaseResponse = new ApiBaseResponse(); 32 | } 33 | 34 | // Extract the correlation id. Apps should log this if they want to collect the data to diagnose failures with Microsoft support 35 | IEnumerable correlationValues; 36 | if (response.Headers.TryGetValues("X-CorrelationId", out correlationValues)) 37 | { 38 | apiBaseResponse.CorrelationId = correlationValues.FirstOrDefault(); 39 | } 40 | apiBaseResponse.StatusCode = response.StatusCode; 41 | apiBaseResponse.Body = body; 42 | return apiBaseResponse; 43 | } 44 | 45 | #endregion 46 | 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteApi/GenericEntityResponse.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft Corporation 3 | // All rights reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the ""License""); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS 12 | // OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 13 | // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR 14 | // PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 15 | // 16 | // See the Apache Version 2.0 License for specific language 17 | // governing permissions and limitations under the License. 18 | //********************************************************* 19 | 20 | using System.Collections.Generic; 21 | 22 | namespace OneNoteServiceSamplesWinUniversal.OneNoteApi 23 | { 24 | /// 25 | /// This class represents a generic the OneNote API entity response 26 | /// Any response from the Notebooks/Sections/SectionGroups API (POST/GET etc) can be translated into this object for ease of use. 27 | /// 28 | /// 29 | /// This is not meant to be a comprehensive SDK or data model. 30 | /// This is ONLY a light-weight representation of a OneNote API's entities (Notebooks, Sections, SectionGroups) 31 | /// The API's HTTP json response is deserialized into this object 32 | /// 33 | public class GenericEntityResponse : ApiBaseResponse 34 | { 35 | /// 36 | /// Name of the entity 37 | /// 38 | public string Name; 39 | 40 | /// 41 | /// Self link to the given entity 42 | /// 43 | public string Self { get; set; } 44 | 45 | public List Sections { get; set; } 46 | 47 | public List SectionGroups { get; set; } 48 | 49 | public override string ToString() 50 | { 51 | return "Name: " + Name + ", Id: " + Id; 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteApi/Auth.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft Corporation 3 | // All rights reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the ""License""); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS 12 | // OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 13 | // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR 14 | // PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 15 | // 16 | // See the Apache Version 2.0 License for specific language 17 | // governing permissions and limitations under the License. 18 | //********************************************************* 19 | 20 | using System.Threading.Tasks; 21 | 22 | namespace OneNoteServiceSamplesWinUniversal.OneNoteApi 23 | { 24 | public enum AuthProvider 25 | { 26 | MicrosoftAccount, 27 | MicrosoftOffice365 28 | } 29 | 30 | /// 31 | /// This class contains all Authentication related code for interacting with the OneNote APIs 32 | /// 33 | /// 34 | /// Based on the context, we either will authenticate user for O365 or for Live ID 35 | /// 36 | internal static class Auth 37 | { 38 | /// 39 | /// Gets a valid authentication token for the selected Authentication provider 40 | /// 41 | /// 42 | /// Used by the API request generators before making calls to the OneNote APIs. 43 | /// 44 | /// valid authentication token 45 | internal static async Task GetAuthToken(AuthProvider provider) 46 | { 47 | if (provider == AuthProvider.MicrosoftAccount) 48 | { 49 | return await LiveIdAuth.GetAuthToken(); 50 | } 51 | else 52 | { 53 | return await O365Auth.GetAuthToken(); 54 | } 55 | } 56 | 57 | internal static async Task SignOut(AuthProvider provider) 58 | { 59 | if (provider == AuthProvider.MicrosoftAccount) 60 | { 61 | await LiveIdAuth.SignOut(); 62 | } 63 | else 64 | { 65 | await O365Auth.SignOut(); 66 | } 67 | } 68 | 69 | internal static bool IsSignedIn(AuthProvider provider) 70 | { 71 | if (provider == AuthProvider.MicrosoftAccount) 72 | { 73 | return LiveIdAuth.IsSignedIn; 74 | } 75 | else 76 | { 77 | return O365Auth.IsSignedIn; 78 | } 79 | } 80 | 81 | internal static async Task GetUserName(AuthProvider provider) 82 | { 83 | if (provider == AuthProvider.MicrosoftAccount) 84 | { 85 | return await LiveIdAuth.GetUserName(); 86 | } 87 | else 88 | { 89 | return await O365Auth.GetUserName(); 90 | } 91 | } 92 | } 93 | } -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteApi/ApiBaseResponse.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft Corporation 3 | // All rights reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the ""License""); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS 12 | // OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 13 | // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR 14 | // PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 15 | // 16 | // See the Apache Version 2.0 License for specific language 17 | // governing permissions and limitations under the License. 18 | //********************************************************* 19 | 20 | using System.Net; 21 | 22 | namespace OneNoteServiceSamplesWinUniversal.OneNoteApi 23 | { 24 | /// 25 | /// Base class representing a simplified response from ALL OneNote APIs 26 | /// 27 | public class ApiBaseResponse 28 | { 29 | /// 30 | /// All OneNote API reponses return a meaningful Http status code 31 | /// Typical pattern for Http status codes are used: 32 | /// 1 1xx Informational 33 | /// 2 2xx Success. e.g. 200-OK for GETs, 201 -Created for POSTs 34 | /// 3 3xx Redirection 35 | /// 4 4xx Client Error e.g. 400-Bad Request 36 | /// 5 5xx Server Error e.g. 500-Internal Server Error 37 | /// 38 | public HttpStatusCode StatusCode { get; set; } 39 | 40 | /// 41 | /// Per call identifier that can be logged to diagnose issues with Microsoft support 42 | /// CorrelationId is included in all Response Headers 43 | /// 44 | public string CorrelationId { get; set; } 45 | 46 | /// 47 | /// Body of the OneNote API response represented as a string. 48 | /// For error cases, this will typically include an error json intended for developers, not for end users. 49 | /// For success cases, depending on the type API call/HTTP verb this may or may not include a json value 50 | /// 51 | public string Body { get; set; } 52 | 53 | /// 54 | /// URLs to launch OneNote rich client/web app 55 | /// 56 | public Links Links { get; set; } 57 | 58 | /// 59 | /// Unique identifier of the object 60 | /// 61 | public string Id { get; set; } 62 | 63 | } 64 | 65 | public class Links 66 | { 67 | /// 68 | /// URL to launch OneNote rich client 69 | /// 70 | public HrefUrl OneNoteClientUrl { get; set; } 71 | 72 | /// 73 | /// URL to launch OneNote web experience 74 | /// 75 | public HrefUrl OneNoteWebUrl { get; set; } 76 | } 77 | 78 | public class HrefUrl 79 | { 80 | public string Href { get; set; } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | # Build results 10 | 11 | [Dd]ebug/ 12 | [Rr]elease/ 13 | x64/ 14 | build/ 15 | [Bb]in/ 16 | [Oo]bj/ 17 | 18 | # Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets 19 | !packages/*/build/ 20 | 21 | # MSTest test Results 22 | [Tt]est[Rr]esult*/ 23 | [Bb]uild[Ll]og.* 24 | 25 | *_i.c 26 | *_p.c 27 | *.ilk 28 | *.meta 29 | *.obj 30 | *.pch 31 | *.pdb 32 | *.pgc 33 | *.pgd 34 | *.rsp 35 | *.sbr 36 | *.tlb 37 | *.tli 38 | *.tlh 39 | *.tmp 40 | *.tmp_proj 41 | *.log 42 | *.vspscc 43 | *.vssscc 44 | .builds 45 | *.pidb 46 | *.log 47 | *.scc 48 | 49 | # Visual C++ cache files 50 | ipch/ 51 | *.aps 52 | *.ncb 53 | *.opensdf 54 | *.sdf 55 | *.cachefile 56 | 57 | # Visual Studio profiler 58 | *.psess 59 | *.vsp 60 | *.vspx 61 | 62 | # Guidance Automation Toolkit 63 | *.gpState 64 | 65 | # ReSharper is a .NET coding add-in 66 | _ReSharper*/ 67 | *.[Rr]e[Ss]harper 68 | 69 | # TeamCity is a build add-in 70 | _TeamCity* 71 | 72 | # DotCover is a Code Coverage Tool 73 | *.dotCover 74 | 75 | # NCrunch 76 | *.ncrunch* 77 | .*crunch*.local.xml 78 | 79 | # Installshield output folder 80 | [Ee]xpress/ 81 | 82 | # DocProject is a documentation generator add-in 83 | DocProject/buildhelp/ 84 | DocProject/Help/*.HxT 85 | DocProject/Help/*.HxC 86 | DocProject/Help/*.hhc 87 | DocProject/Help/*.hhk 88 | DocProject/Help/*.hhp 89 | DocProject/Help/Html2 90 | DocProject/Help/html 91 | 92 | # Click-Once directory 93 | publish/ 94 | 95 | # Publish Web Output 96 | *.Publish.xml 97 | 98 | # NuGet Packages Directory 99 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 100 | #packages/ 101 | 102 | # Windows Azure Build Output 103 | csx 104 | *.build.csdef 105 | 106 | # Windows Store app package directory 107 | AppPackages/ 108 | 109 | # Others 110 | sql/ 111 | *.Cache 112 | ClientBin/ 113 | [Ss]tyle[Cc]op.* 114 | ~$* 115 | *~ 116 | *.dbmdl 117 | *.[Pp]ublish.xml 118 | *.pfx 119 | *.publishsettings 120 | 121 | # RIA/Silverlight projects 122 | Generated_Code/ 123 | 124 | # Backup & report files from converting an old project file to a newer 125 | # Visual Studio version. Backup files are not needed, because we have git ;-) 126 | _UpgradeReport_Files/ 127 | Backup*/ 128 | UpgradeLog*.XML 129 | UpgradeLog*.htm 130 | 131 | # SQL Server files 132 | App_Data/*.mdf 133 | App_Data/*.ldf 134 | 135 | 136 | #LightSwitch generated files 137 | GeneratedArtifacts/ 138 | _Pvt_Extensions/ 139 | ModelManifest.xml 140 | 141 | # ========================= 142 | # Windows detritus 143 | # ========================= 144 | 145 | # Windows image file caches 146 | Thumbs.db 147 | ehthumbs.db 148 | 149 | # Folder config file 150 | Desktop.ini 151 | 152 | # Recycle Bin used on file shares 153 | $RECYCLE.BIN/ 154 | 155 | # Mac desktop service store files 156 | .DS_Store 157 | /packages 158 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/Common/RelayCommand.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Windows.Input; 7 | 8 | namespace OneNoteServiceSamplesWinUniversal.Common 9 | { 10 | /// 11 | /// A command whose sole purpose is to relay its functionality 12 | /// to other objects by invoking delegates. 13 | /// The default return value for the CanExecute method is 'true'. 14 | /// needs to be called whenever 15 | /// is expected to return a different value. 16 | /// 17 | public class RelayCommand : ICommand 18 | { 19 | private readonly Action _execute; 20 | private readonly Func _canExecute; 21 | 22 | /// 23 | /// Raised when RaiseCanExecuteChanged is called. 24 | /// 25 | public event EventHandler CanExecuteChanged; 26 | 27 | /// 28 | /// Creates a new command that can always execute. 29 | /// 30 | /// The execution logic. 31 | public RelayCommand(Action execute) 32 | : this(execute, null) 33 | { 34 | } 35 | 36 | /// 37 | /// Creates a new command. 38 | /// 39 | /// The execution logic. 40 | /// The execution status logic. 41 | public RelayCommand(Action execute, Func canExecute) 42 | { 43 | if (execute == null) 44 | throw new ArgumentNullException("execute"); 45 | _execute = execute; 46 | _canExecute = canExecute; 47 | } 48 | 49 | /// 50 | /// Determines whether this can execute in its current state. 51 | /// 52 | /// 53 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null. 54 | /// 55 | /// true if this command can be executed; otherwise, false. 56 | public bool CanExecute(object parameter) 57 | { 58 | return _canExecute == null ? true : _canExecute(); 59 | } 60 | 61 | /// 62 | /// Executes the on the current command target. 63 | /// 64 | /// 65 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null. 66 | /// 67 | public void Execute(object parameter) 68 | { 69 | _execute(); 70 | } 71 | 72 | /// 73 | /// Method used to raise the event 74 | /// to indicate that the return value of the 75 | /// method has changed. 76 | /// 77 | public void RaiseCanExecuteChanged() 78 | { 79 | var handler = CanExecuteChanged; 80 | if (handler != null) 81 | { 82 | handler(this, EventArgs.Empty); 83 | } 84 | } 85 | } 86 | } -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteApi/Pages/DeletePageExample.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft Corporation 3 | // All rights reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the ""License""); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS 12 | // OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 13 | // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR 14 | // PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 15 | // 16 | // See the Apache Version 2.0 License for specific language 17 | // governing permissions and limitations under the License. 18 | //********************************************************* 19 | 20 | using System.Diagnostics; 21 | using System.Net.Http; 22 | using System.Net.Http.Headers; 23 | using System.Threading.Tasks; 24 | 25 | namespace OneNoteServiceSamplesWinUniversal.OneNoteApi.Pages 26 | { 27 | /// 28 | /// Class to show a selection of examples deleting pages via HTTP DELETE to the OneNote API 29 | /// - Delete a new page is represented via the DELETE HTTP verb. 30 | /// For more info, see http://dev.onenote.com/docs#/reference/delete-pages. 31 | /// 32 | /// 33 | /// NOTE: It is not the goal of this code sample to produce well re-factored, elegant code. 34 | /// You may notice code blocks being duplicated in various places in this project. 35 | /// We have deliberately added these code blocks to allow anyone browsing the sample 36 | /// to easily view all related functionality in near proximity. 37 | /// 38 | /// 39 | /// var client = new HttpClient(); 40 | /// client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await Auth.GetAuthToken()); 41 | /// 42 | /// var deleteMessage = new HttpRequestMessage(HttpMethod.Delete, "https://www.onenote.com/api/v1.0/pages"); 43 | /// HttpResponseMessage response = await client.SendAsync(deleteMessage); 44 | /// 45 | public static class DeletePagesExample 46 | { 47 | #region Examples of DELETE https://www.onenote.com/api/v1.0/pages 48 | 49 | /// 50 | /// Delete a page. 51 | /// 52 | /// Run the code under the debugger 53 | /// 54 | /// 55 | /// 56 | /// Delete a specified page by ID. 57 | /// The converted HTTP response message 58 | public static async Task DeletePage(bool debug, string pageId, AuthProvider provider, string apiRoute) 59 | { 60 | if (debug) 61 | { 62 | Debugger.Launch(); 63 | Debugger.Break(); 64 | } 65 | 66 | var client = new HttpClient(); 67 | 68 | // Note: API only supports JSON response. 69 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 70 | 71 | // Not adding the Authentication header would produce an unauthorized call and the API will return a 401 72 | client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", 73 | await Auth.GetAuthToken(provider)); 74 | 75 | // Prepare an HTTP DELETE request to the Pages endpoint 76 | // The request body content type is text/html 77 | var deleteMessage = new HttpRequestMessage(HttpMethod.Delete, apiRoute + "pages/" + pageId); 78 | var response = await client.SendAsync(deleteMessage); 79 | 80 | return await HttpUtils.TranslateResponse(response); 81 | } 82 | 83 | #endregion 84 | } 85 | } -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/SectionPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Windows.UI.Xaml.Controls; 3 | using Windows.UI.Xaml.Navigation; 4 | using OneNoteServiceSamplesWinUniversal.Common; 5 | using OneNoteServiceSamplesWinUniversal.Data; 6 | 7 | namespace OneNoteServiceSamplesWinUniversal 8 | { 9 | /// 10 | /// A page that displays an overview of a single group, including a preview of the items 11 | /// within the group. 12 | /// 13 | public sealed partial class SectionPage : SharedBasePage 14 | { 15 | private NavigationHelper navigationHelper; 16 | private ObservableDictionary defaultViewModel = new ObservableDictionary(); 17 | 18 | public SectionPage() 19 | { 20 | InitializeComponent(); 21 | navigationHelper = new NavigationHelper(this); 22 | navigationHelper.LoadState += NavigationHelper_LoadState; 23 | } 24 | 25 | /// 26 | /// Gets the NavigationHelper used to aid in navigation and process lifetime management. 27 | /// 28 | public NavigationHelper NavigationHelper 29 | { 30 | get { return navigationHelper; } 31 | } 32 | 33 | /// 34 | /// Gets the DefaultViewModel. This can be changed to a strongly typed view model. 35 | /// 36 | public ObservableDictionary DefaultViewModel 37 | { 38 | get { return defaultViewModel; } 39 | } 40 | 41 | /// 42 | /// Populates the page with content passed during navigation. Any saved state is also 43 | /// provided when recreating a page from a prior session. 44 | /// 45 | /// 46 | /// The source of the event; typically 47 | /// 48 | /// Event data that provides both the navigation parameter passed to 49 | /// when this page was initially requested and 50 | /// a dictionary of state preserved by this page during an earlier 51 | /// session. The state will be null the first time a page is visited. 52 | private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e) 53 | { 54 | // TODO: Create an appropriate data model for your problem domain to replace the sample data 55 | var group = await SampleDataSource.GetGroupAsync((string)e.NavigationParameter); 56 | DefaultViewModel["Group"] = group; 57 | DefaultViewModel["Items"] = group.Items; 58 | pageTitle.Text = group.Title; 59 | } 60 | 61 | /// 62 | /// Invoked when an item is clicked. 63 | /// 64 | /// The GridView displaying the item clicked. 65 | /// Event data that describes the item clicked. 66 | private void ItemView_ItemClick(object sender, ItemClickEventArgs e) 67 | { 68 | // Navigate to the appropriate destination page, configuring the new page 69 | // by passing required information as a navigation parameter 70 | var itemId = ((SampleDataItem)e.ClickedItem).UniqueId; 71 | Frame.Navigate(typeof(ItemPage), itemId); 72 | } 73 | 74 | #region NavigationHelper registration 75 | 76 | /// 77 | /// The methods provided in this section are simply used to allow 78 | /// NavigationHelper to respond to the page's navigation methods. 79 | /// Page specific logic should be placed in event handlers for the 80 | /// 81 | /// and . 82 | /// The navigation parameter is available in the LoadState method 83 | /// in addition to page state preserved during an earlier session. 84 | /// 85 | protected override void OnNavigatedTo(NavigationEventArgs e) 86 | { 87 | navigationHelper.OnNavigatedTo(e); 88 | } 89 | 90 | protected override void OnNavigatedFrom(NavigationEventArgs e) 91 | { 92 | navigationHelper.OnNavigatedFrom(e); 93 | } 94 | 95 | #endregion 96 | } 97 | } -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteServiceSamplesWinUniversal.Shared.projitems: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildAllProjects);$(MSBuildThisFileFullPath) 5 | true 6 | 556a67f3-bd06-49be-ae69-e638d2d6a790 7 | 8 | 9 | OneNoteServiceSamplesWinUniversal 10 | 11 | 12 | 13 | Designer 14 | 15 | 16 | App.xaml 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | SharedBasePage.xaml 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | Designer 56 | MSBuild:Compile 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/SectionPage.xaml: -------------------------------------------------------------------------------- 1 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteApi/Notebooks/PostNotebooksExample.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft Corporation 3 | // All rights reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the ""License""); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS 12 | // OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 13 | // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR 14 | // PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 15 | // 16 | // See the Apache Version 2.0 License for specific language 17 | // governing permissions and limitations under the License. 18 | //********************************************************* 19 | using System.Diagnostics; 20 | using System.Linq; 21 | using System.Net; 22 | using System.Net.Http; 23 | using System.Net.Http.Headers; 24 | using System.Text; 25 | using System.Threading.Tasks; 26 | 27 | namespace OneNoteServiceSamplesWinUniversal.OneNoteApi.Notebooks 28 | { 29 | /// 30 | /// Class to show a selection of examples creating notebooks via HTTP POST to the OneNote API 31 | /// - Creating a new notebook is represented via the POST HTTP verb. 32 | /// - Creating a new notebook represented by the Uri: https://www.onenote.com/api/v1.0/notebooks 33 | /// For more info, see http://dev.onenote.com/docs 34 | /// 35 | /// 36 | /// NOTE: All notebooks get created under the 'Documents' folder of the user's OneDrive account. 37 | /// The notebook name is specified in the request body 38 | /// NOTE: It is not the goal of this code sample to produce well re-factored, elegant code. 39 | /// You may notice code blocks being duplicated in various places in this project. 40 | /// We have deliberately added these code blocks to allow anyone browsing the sample 41 | /// to easily view all related functionality in near proximity. 42 | /// 43 | /// 44 | /// var client = new HttpClient(); 45 | /// client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 46 | /// client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await Auth.GetAuthToken()); 47 | /// var createMessage = new HttpRequestMessage(HttpMethod.Post, "https://www.onenote.com/api/v1.0/notebooks") 48 | /// { 49 | /// Content = new StringContent("{name: NewNotebookName }", System.Text.Encoding.UTF8, "application/json") 50 | /// }; 51 | /// HttpResponseMessage response = await client.SendAsync(createMessage); 52 | /// 53 | public static class PostNotebooksExample 54 | { 55 | #region Examples of POST https://www.onenote.com/api/v1.0/notebooks 56 | 57 | /// 58 | /// Create a notebook with a given name 59 | /// 60 | /// Run the code under the debugger 61 | /// 62 | /// 63 | /// 64 | /// Create notebook using a application/json content type 65 | /// The converted HTTP response message 66 | public static async Task CreateSimpleNotebook(bool debug, string notebookName, AuthProvider provider, string apiRoute) 67 | { 68 | if (debug) 69 | { 70 | Debugger.Launch(); 71 | Debugger.Break(); 72 | } 73 | 74 | var client = new HttpClient(); 75 | 76 | // Note: API only supports JSON response. 77 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 78 | 79 | // Not adding the Authentication header would produce an unauthorized call and the API will return a 401 80 | client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", 81 | await Auth.GetAuthToken(provider)); 82 | 83 | // Prepare an HTTP POST request to the Notebooks endpoint 84 | // The request body content type is application/json and require a name property 85 | var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + "notebooks") 86 | { 87 | Content = new StringContent("{ name : '" + WebUtility.UrlEncode(notebookName) + "' }", Encoding.UTF8, "application/json") 88 | }; 89 | 90 | HttpResponseMessage response = await client.SendAsync(createMessage); 91 | 92 | return await HttpUtils.TranslateResponse(response); 93 | } 94 | 95 | #endregion 96 | 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/Common/ObservableDictionary.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Windows.Foundation.Collections; 5 | 6 | namespace OneNoteServiceSamplesWinUniversal.Common 7 | { 8 | /// 9 | /// Implementation of IObservableMap that supports reentrancy for use as a default view 10 | /// model. 11 | /// 12 | public class ObservableDictionary : IObservableMap 13 | { 14 | private class ObservableDictionaryChangedEventArgs : IMapChangedEventArgs 15 | { 16 | public ObservableDictionaryChangedEventArgs(CollectionChange change, string key) 17 | { 18 | this.CollectionChange = change; 19 | this.Key = key; 20 | } 21 | 22 | public CollectionChange CollectionChange { get; private set; } 23 | public string Key { get; private set; } 24 | } 25 | 26 | private Dictionary _dictionary = new Dictionary(); 27 | public event MapChangedEventHandler MapChanged; 28 | 29 | private void InvokeMapChanged(CollectionChange change, string key) 30 | { 31 | var eventHandler = MapChanged; 32 | if (eventHandler != null) 33 | { 34 | eventHandler(this, new ObservableDictionaryChangedEventArgs(change, key)); 35 | } 36 | } 37 | 38 | public void Add(string key, object value) 39 | { 40 | this._dictionary.Add(key, value); 41 | this.InvokeMapChanged(CollectionChange.ItemInserted, key); 42 | } 43 | 44 | public void Add(KeyValuePair item) 45 | { 46 | this.Add(item.Key, item.Value); 47 | } 48 | 49 | public bool Remove(string key) 50 | { 51 | if (this._dictionary.Remove(key)) 52 | { 53 | this.InvokeMapChanged(CollectionChange.ItemRemoved, key); 54 | return true; 55 | } 56 | return false; 57 | } 58 | 59 | public bool Remove(KeyValuePair item) 60 | { 61 | object currentValue; 62 | if (this._dictionary.TryGetValue(item.Key, out currentValue) && 63 | Object.Equals(item.Value, currentValue) && this._dictionary.Remove(item.Key)) 64 | { 65 | this.InvokeMapChanged(CollectionChange.ItemRemoved, item.Key); 66 | return true; 67 | } 68 | return false; 69 | } 70 | 71 | public object this[string key] 72 | { 73 | get 74 | { 75 | return this._dictionary[key]; 76 | } 77 | set 78 | { 79 | this._dictionary[key] = value; 80 | this.InvokeMapChanged(CollectionChange.ItemChanged, key); 81 | } 82 | } 83 | 84 | public void Clear() 85 | { 86 | var priorKeys = this._dictionary.Keys.ToArray(); 87 | this._dictionary.Clear(); 88 | foreach (var key in priorKeys) 89 | { 90 | this.InvokeMapChanged(CollectionChange.ItemRemoved, key); 91 | } 92 | } 93 | 94 | public ICollection Keys 95 | { 96 | get { return this._dictionary.Keys; } 97 | } 98 | 99 | public bool ContainsKey(string key) 100 | { 101 | return this._dictionary.ContainsKey(key); 102 | } 103 | 104 | public bool TryGetValue(string key, out object value) 105 | { 106 | return this._dictionary.TryGetValue(key, out value); 107 | } 108 | 109 | public ICollection Values 110 | { 111 | get { return this._dictionary.Values; } 112 | } 113 | 114 | public bool Contains(KeyValuePair item) 115 | { 116 | return this._dictionary.Contains(item); 117 | } 118 | 119 | public int Count 120 | { 121 | get { return this._dictionary.Count; } 122 | } 123 | 124 | public bool IsReadOnly 125 | { 126 | get { return false; } 127 | } 128 | 129 | public IEnumerator> GetEnumerator() 130 | { 131 | return this._dictionary.GetEnumerator(); 132 | } 133 | 134 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() 135 | { 136 | return this._dictionary.GetEnumerator(); 137 | } 138 | 139 | public void CopyTo(KeyValuePair[] array, int arrayIndex) 140 | { 141 | int arraySize = array.Length; 142 | foreach (var pair in this._dictionary) 143 | { 144 | if (arrayIndex >= arraySize) break; 145 | array[arrayIndex++] = pair; 146 | } 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/SectionPage.xaml: -------------------------------------------------------------------------------- 1 | 12 | 13 | 14 | 15 | 19 | 20 | 21 | 26 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | User: 93 | 94 | Response: 95 | 96 | List of items in response: 97 | 98 | 99 | 100 | Body: 101 | 102 | 103 | 104 | 105 | 106 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteApi/Sections/PostSectionsExample.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft Corporation 3 | // All rights reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the ""License""); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS 12 | // OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 13 | // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR 14 | // PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 15 | // 16 | // See the Apache Version 2.0 License for specific language 17 | // governing permissions and limitations under the License. 18 | //********************************************************* 19 | 20 | using Newtonsoft.Json; 21 | using System.Collections.Generic; 22 | using System.Diagnostics; 23 | using System.Linq; 24 | using System.Net; 25 | using System.Net.Http; 26 | using System.Net.Http.Headers; 27 | using System.Text; 28 | using System.Threading.Tasks; 29 | 30 | namespace OneNoteServiceSamplesWinUniversal.OneNoteApi.Sections 31 | { 32 | /// 33 | /// Class to show a selection of examples creating sections via HTTP POST to the OneNote API 34 | /// - Creating a new section is represented via the POST HTTP verb. 35 | /// - Creating a new section under a given notebook is represented by the Uri: https://www.onenote.com/api/v1.0/me/notes/notebooks/{notebookId}/sections 36 | /// - Creating a new section under a given section group is represented by the Uri: https://www.onenote.com/api/v1.0/me/notes/sectiongroups/{sectionGroupId}/sections 37 | /// For more info, see http://dev.onenote.com/docs 38 | /// 39 | /// 40 | /// NOTE: All create-sections operations require a parent notebook or parent section group. 41 | /// The section name is specified in the request body 42 | /// NOTE: It is not the goal of this code sample to produce well re-factored, elegant code. 43 | /// You may notice code blocks being duplicated in various places in this project. 44 | /// We have deliberately added these code blocks to allow anyone browsing the sample 45 | /// to easily view all related functionality in near proximity. 46 | /// 47 | /// 48 | /// var client = new HttpClient(); 49 | /// client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 50 | /// client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await Auth.GetAuthToken()); 51 | /// var createMessage = new HttpRequestMessage(HttpMethod.Post, "https://www.onenote.com/api/v1.0/me/notes/notebooks/{notebookId}/sections") 52 | /// { 53 | /// Content = new StringContent("{name: NewSectionName }", System.Text.Encoding.UTF8, "application/json") 54 | /// }; 55 | /// HttpResponseMessage response = await client.SendAsync(createMessage); 56 | /// 57 | public static class PostSectionsExample 58 | { 59 | #region Examples of POST https://www.onenote.com/api/v1.0/me/notes/notebooks/{notebookId}/sections 60 | 61 | /// 62 | /// Create a section with a given name under a given notebookId 63 | /// 64 | /// Run the code under the debugger 65 | /// parent notebook's Id 66 | /// name of the section to create 67 | /// 68 | /// 69 | /// Create section using a application/json content type 70 | /// The converted HTTP response message 71 | public static async Task CreateSectionInNotebook(bool debug, string notebookId, string sectionName, AuthProvider provider, string apiRoute) 72 | { 73 | if (debug) 74 | { 75 | Debugger.Launch(); 76 | Debugger.Break(); 77 | } 78 | 79 | var client = new HttpClient(); 80 | 81 | // Note: API only supports JSON response. 82 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 83 | 84 | // Not adding the Authentication header would produce an unauthorized call and the API will return a 401 85 | client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", 86 | await Auth.GetAuthToken(provider)); 87 | 88 | // Prepare an HTTP POST request to the Sections endpoint 89 | // The request body content type is application/json and require a name property 90 | var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + @"notebooks/" + notebookId + "/sections") 91 | { 92 | Content = new StringContent("{ name : '" + WebUtility.UrlEncode(sectionName) + "' }", Encoding.UTF8, "application/json") 93 | }; 94 | 95 | HttpResponseMessage response = await client.SendAsync(createMessage); 96 | 97 | return await HttpUtils.TranslateResponse(response); 98 | } 99 | 100 | #endregion 101 | 102 | #region Examples of POST https://www.onenote.com/api/v1.0/me/notes/sectiongroups/{sectionGroupId}/sections 103 | 104 | /// 105 | /// BETA Create a section with a given name under a given sectionGroupId 106 | /// 107 | /// Run the code under the debugger 108 | /// parent section group's Id 109 | /// name of the section to create 110 | /// 111 | /// 112 | /// Create section using a application/json content type 113 | /// The converted HTTP response message 114 | public static async Task CreateSectionInSectionGroup(bool debug, string sectionGroupId, string sectionName, AuthProvider provider, string apiRoute) 115 | { 116 | if (debug) 117 | { 118 | Debugger.Launch(); 119 | Debugger.Break(); 120 | } 121 | 122 | var client = new HttpClient(); 123 | 124 | // Note: API only supports JSON response. 125 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 126 | 127 | // Not adding the Authentication header would produce an unauthorized call and the API will return a 401 128 | client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", 129 | await Auth.GetAuthToken(provider)); 130 | 131 | // Prepare an HTTP POST request to the Sections endpoint 132 | // The request body content type is application/json and require a name property 133 | var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + @"sectiongroups/" + sectionGroupId + "/sections") 134 | { 135 | Content = new StringContent("{ name : '" + WebUtility.UrlEncode(sectionName) + "' }", Encoding.UTF8, "application/json") 136 | }; 137 | 138 | HttpResponseMessage response = await client.SendAsync(createMessage); 139 | 140 | return await HttpUtils.TranslateResponse(response); 141 | } 142 | 143 | #endregion 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteApi/SectionGroups/PostSectionGroupsExample.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft Corporation 3 | // All rights reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the ""License""); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS 12 | // OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 13 | // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR 14 | // PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 15 | // 16 | // See the Apache Version 2.0 License for specific language 17 | // governing permissions and limitations under the License. 18 | //********************************************************* 19 | 20 | using Newtonsoft.Json; 21 | using System.Collections.Generic; 22 | using System.Diagnostics; 23 | using System.Linq; 24 | using System.Net; 25 | using System.Net.Http; 26 | using System.Net.Http.Headers; 27 | using System.Text; 28 | using System.Threading.Tasks; 29 | 30 | namespace OneNoteServiceSamplesWinUniversal.OneNoteApi.SectionGroups 31 | { 32 | /// 33 | /// Class to show a selection of examples creating section groups via HTTP POST to the OneNote API 34 | /// - Creating a new section group is represented via the POST HTTP verb. 35 | /// - Creating a new section group under a given notebook is represented by the Uri: https://www.onenote.com/api/v1.0/me/notes/notebooks/{notebookId}/sectiongroups 36 | /// - Creating a new section group under a given section group is represented by the Uri: https://www.onenote.com/api/v1.0/me/notes/sectiongroups/{sectionGroupId}/sectiongroups 37 | /// For more info, see http://dev.onenote.com/docs 38 | /// 39 | /// 40 | /// NOTE: All create-sectiongroups operations require a parent notebook or parent sectiongroup. 41 | /// The section group name is specified in the request body. 42 | /// NOTE: It is not the goal of this code sample to produce well re-factored, elegant code. 43 | /// You may notice code blocks being duplicated in various places in this project. 44 | /// We have deliberately added these code blocks to allow anyone browsing the sample 45 | /// to easily view all related functionality in near proximity. 46 | /// 47 | /// 48 | /// var client = new HttpClient(); 49 | /// client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 50 | /// client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await Auth.GetAuthToken()); 51 | /// var createMessage = new HttpRequestMessage(HttpMethod.Post, "https://www.onenote.com/api/v1.0/me/notes/notebooks/{notebookId}/sectiongroups") 52 | /// { 53 | /// Content = new StringContent("{name: NewSectionGroupName }", System.Text.Encoding.UTF8, "application/json") 54 | /// }; 55 | /// HttpResponseMessage response = await client.SendAsync(createMessage); 56 | /// 57 | public static class PostSectionGroupsExample 58 | { 59 | #region Examples of POST https://www.onenote.com/api/v1.0/me/notes/notebooks/{notebookId}/sectiongroups 60 | 61 | /// 62 | /// BETA Create a section group with a given name under a given notebookId 63 | /// 64 | /// Run the code under the debugger 65 | /// parent notebook's Id 66 | /// name of the section group to create 67 | /// 68 | /// 69 | /// Create section group using a application/json content type 70 | /// The converted HTTP response message 71 | public static async Task CreateSectionGroupInNotebook(bool debug, string notebookId, string sectionGroupName, AuthProvider provider, string apiRoute) 72 | { 73 | if (debug) 74 | { 75 | Debugger.Launch(); 76 | Debugger.Break(); 77 | } 78 | 79 | var client = new HttpClient(); 80 | 81 | // Note: API only supports JSON response. 82 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 83 | 84 | // Not adding the Authentication header would produce an unauthorized call and the API will return a 401 85 | client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", 86 | await Auth.GetAuthToken(provider)); 87 | 88 | // Prepare an HTTP POST request to the SectionGroups endpoint 89 | // The request body content type is application/json and requires a name property 90 | var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + @"notebooks/" + notebookId + "/sectiongroups") 91 | { 92 | Content = new StringContent("{ name : '" + WebUtility.UrlEncode(sectionGroupName) + "' }", Encoding.UTF8, "application/json") 93 | }; 94 | 95 | HttpResponseMessage response = await client.SendAsync(createMessage); 96 | 97 | return await HttpUtils.TranslateResponse(response); 98 | } 99 | 100 | #endregion 101 | 102 | 103 | #region Examples of POST https://www.onenote.com/api/v1.0/me/notes/sectiongroups/{sectionGroupId}/sectiongroups 104 | /// 105 | /// BETA Create a section group with a given name under a given sectionGroupId 106 | /// 107 | /// Run the code under the debugger 108 | /// parent section group's Id 109 | /// name of the section group to create 110 | /// 111 | /// 112 | /// Create section group using a application/json content type 113 | /// The converted HTTP response message 114 | public static async Task CreateSectionGroupInSectionGroup(bool debug, string sectionGroupId, string sectionGroupName, AuthProvider provider, string apiRoute) 115 | { 116 | if (debug) 117 | { 118 | Debugger.Launch(); 119 | Debugger.Break(); 120 | } 121 | 122 | var client = new HttpClient(); 123 | 124 | // Note: API only supports JSON response. 125 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 126 | 127 | // Not adding the Authentication header would produce an unauthorized call and the API will return a 401 128 | client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", 129 | await Auth.GetAuthToken(provider)); 130 | 131 | // Prepare an HTTP POST request to the SectionGroups endpoint 132 | // The request body content type is application/json and requires a name property 133 | var createMessage = new HttpRequestMessage(HttpMethod.Post, apiRoute + @"sectiongroups/" + sectionGroupId + "/sectiongroups") 134 | { 135 | Content = new StringContent("{ name : '" + WebUtility.UrlEncode(sectionGroupName) + "' }", Encoding.UTF8, "application/json") 136 | }; 137 | 138 | HttpResponseMessage response = await client.SendAsync(createMessage); 139 | 140 | return await HttpUtils.TranslateResponse(response); 141 | } 142 | 143 | #endregion 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteApi/LiveIdAuth.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft Corporation 3 | // All rights reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the ""License""); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS 12 | // OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 13 | // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR 14 | // PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 15 | // 16 | // See the Apache Version 2.0 License for specific language 17 | // governing permissions and limitations under the License. 18 | //********************************************************* 19 | 20 | using System; 21 | using System.Diagnostics; 22 | using System.Globalization; 23 | using System.Net; 24 | using System.Net.Http; 25 | using System.Text; 26 | using System.Threading.Tasks; 27 | using Windows.Security.Authentication.OnlineId; 28 | using Newtonsoft.Json; 29 | using Newtonsoft.Json.Linq; 30 | 31 | namespace OneNoteServiceSamplesWinUniversal.OneNoteApi 32 | { 33 | /// 34 | /// This class contains all Authentication related code for interacting with the OneNote APIs 35 | /// 36 | /// 37 | /// In our previous github WinStore and WinPhone Code samples we demonstrated how to use the 38 | /// LiveSDK to do OAuth against the Microsoft Account service. 39 | /// For this Windows 8.1 Universal code sample, we'll demonstrate an alternative way to do 40 | /// OAuth using the new Windows.Security.Authentication.OnlineId.OnlineIdauthenticator 41 | /// class. 42 | /// http://msdn.microsoft.com/en-us/library/windows/apps/windows.security.authentication.onlineid.onlineidauthenticator.aspx 43 | /// Both the existing Live SDK approach and this alternative will work in Windows 8.1 universal apps 44 | /// NOTE: The usage of the OnlineIdAuthenticator class is based on the Windows universal code sample at 45 | /// http://code.msdn.microsoft.com/windowsapps/Windows-account-authorizati-7c95e284 46 | /// 47 | internal static class LiveIdAuth 48 | { 49 | private static readonly OnlineIdAuthenticator Authenticator = new OnlineIdAuthenticator(); 50 | private static string _accessToken; 51 | 52 | // TODO: Replace the below ClientId with your app's ClientId. 53 | // For more info, see: http://msdn.microsoft.com/en-us/library/office/dn575426(v=office.15).aspx 54 | private const string ClientId = "000000004011CF40"; 55 | 56 | // OneNote APIs support multiple OAuth scopes. 57 | // As a guideline, always choose the least permissible 'office.onenote*' scope that your app needs. 58 | // Since this code sample demonstrates multiple aspects of the APIs, it uses the most 59 | // permissible scope: office.onenote_update. 60 | // TODO: Replace the below scopes with the least permissions your app needs 61 | private const string Scopes = "office.onenote_update wl.signin wl.offline_access"; 62 | 63 | private const string LiveApiMeUri = "https://apis.live.net/v5.0/me?access_token="; 64 | 65 | /// 66 | /// Gets a valid authentication token. Also refreshes the access token if it has expired. 67 | /// 68 | /// 69 | /// Used by the API request generators before making calls to the OneNote APIs. 70 | /// 71 | /// valid authentication token 72 | internal static async Task GetAuthToken() 73 | { 74 | if (String.IsNullOrWhiteSpace(_accessToken)) 75 | { 76 | try 77 | { 78 | var serviceTicketRequest = new OnlineIdServiceTicketRequest(Scopes, "DELEGATION"); 79 | var result = 80 | await Authenticator.AuthenticateUserAsync(new[] { serviceTicketRequest }, CredentialPromptType.PromptIfNeeded); 81 | if (result.Tickets[0] != null) 82 | { 83 | _accessToken = result.Tickets[0].Value; 84 | _accessTokenExpiration = DateTimeOffset.UtcNow.AddMinutes(AccessTokenApproxExpiresInMinutes); 85 | } 86 | } 87 | catch (Exception ex) 88 | { 89 | // Authentication failed 90 | if (Debugger.IsAttached) 91 | Debugger.Break(); 92 | } 93 | } 94 | await RefreshAuthTokenIfNeeded(); 95 | return _accessToken; 96 | } 97 | 98 | internal static async Task SignOut() 99 | { 100 | if (IsSignedIn) 101 | { 102 | _accessToken = null; 103 | await Authenticator.SignOutUserAsync(); 104 | } 105 | } 106 | 107 | internal static bool IsSignedIn 108 | { 109 | get { return Authenticator != null && Authenticator.CanSignOut && _accessToken != null; } 110 | } 111 | 112 | internal static async Task GetUserName() 113 | { 114 | var uri = new Uri(LiveApiMeUri + await GetAuthToken()); 115 | var client = new HttpClient(); 116 | var result = await client.GetAsync(uri); 117 | 118 | string jsonUserInfo = await result.Content.ReadAsStringAsync(); 119 | if (jsonUserInfo != null) 120 | { 121 | var json = JObject.Parse(jsonUserInfo); 122 | return json["name"].ToString(); 123 | } 124 | return string.Empty; 125 | } 126 | 127 | #region RefreshToken related code 128 | 129 | // Collateral used to refresh access token (only applicable when the app uses the wl.offline_access wl.signin scopes) 130 | private static DateTimeOffset _accessTokenExpiration; 131 | private static string _refreshToken; 132 | private const int AccessTokenApproxExpiresInMinutes = 59; 133 | 134 | private const string MsaTokenRefreshUrl = "https://login.live.com/oauth20_token.srf"; 135 | private const string TokenRefreshContentType = "application/x-www-form-urlencoded"; 136 | private const string TokenRefreshRedirectUri = "https://login.live.com/oauth20_desktop.srf"; 137 | 138 | private const string TokenRefreshRequestBody = 139 | "client_id={0}&redirect_uri={1}&grant_type=refresh_token&refresh_token={2}"; 140 | 141 | /// 142 | /// Refreshes the live authentication access token if it has expired 143 | /// 144 | public static async Task RefreshAuthTokenIfNeeded() 145 | { 146 | if (_accessTokenExpiration.CompareTo(DateTimeOffset.UtcNow) <= 0) 147 | { 148 | await AttemptAccessTokenRefresh(); 149 | } 150 | } 151 | 152 | /// 153 | /// This method tries to refresh the access token. The token needs to be 154 | /// refreshed continuously, so that the user is not prompted to sign in again 155 | /// 156 | /// 157 | private static async Task AttemptAccessTokenRefresh() 158 | { 159 | var createMessage = new HttpRequestMessage(HttpMethod.Post, MsaTokenRefreshUrl) 160 | { 161 | Content = new StringContent( 162 | String.Format(CultureInfo.InvariantCulture, TokenRefreshRequestBody, 163 | ClientId, 164 | TokenRefreshRedirectUri, 165 | _refreshToken), 166 | Encoding.UTF8, 167 | TokenRefreshContentType) 168 | }; 169 | 170 | var httpClient = new HttpClient(); 171 | HttpResponseMessage response = await httpClient.SendAsync(createMessage); 172 | await ParseRefreshTokenResponse(response); 173 | } 174 | 175 | /// 176 | /// Handle the RefreshToken response 177 | /// 178 | /// The HttpResponseMessage from the TokenRefresh request 179 | private static async Task ParseRefreshTokenResponse(HttpResponseMessage response) 180 | { 181 | if (response.StatusCode == HttpStatusCode.OK) 182 | { 183 | dynamic responseObject = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); 184 | _accessToken = responseObject.access_token; 185 | _accessTokenExpiration = _accessTokenExpiration.AddSeconds((double)responseObject.expires_in); 186 | _refreshToken = responseObject.refresh_token; 187 | } 188 | } 189 | 190 | #endregion 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /.nuget/NuGet.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildProjectDirectory)\..\ 5 | 6 | 7 | false 8 | 9 | 10 | false 11 | 12 | 13 | true 14 | 15 | 16 | false 17 | 18 | 19 | 20 | 21 | 22 | 26 | 27 | 28 | 29 | 30 | $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) 31 | 32 | 33 | 34 | 35 | $(SolutionDir).nuget 36 | 37 | 38 | 39 | $(MSBuildProjectDirectory)\packages.$(MSBuildProjectName.Replace(' ', '_')).config 40 | $(MSBuildProjectDirectory)\packages.$(MSBuildProjectName).config 41 | 42 | 43 | 44 | $(MSBuildProjectDirectory)\packages.config 45 | $(PackagesProjectConfig) 46 | 47 | 48 | 49 | 50 | $(NuGetToolsPath)\NuGet.exe 51 | @(PackageSource) 52 | 53 | "$(NuGetExePath)" 54 | mono --runtime=v4.0.30319 "$(NuGetExePath)" 55 | 56 | $(TargetDir.Trim('\\')) 57 | 58 | -RequireConsent 59 | -NonInteractive 60 | 61 | "$(SolutionDir) " 62 | "$(SolutionDir)" 63 | 64 | 65 | $(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir) 66 | $(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols 67 | 68 | 69 | 70 | RestorePackages; 71 | $(BuildDependsOn); 72 | 73 | 74 | 75 | 76 | $(BuildDependsOn); 77 | BuildPackage; 78 | 79 | 80 | 81 | 82 | 83 | 84 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 99 | 100 | 103 | 104 | 105 | 106 | 108 | 109 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 141 | 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/HubPage.xaml: -------------------------------------------------------------------------------- 1 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 50 | 51 | 52 | 53 | 54 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 75 | 76 | 87 | 88 | 89 | 90 | 92 | 93 | 104 | 105 | 106 | 107 | 109 | 110 | 121 | 122 | 123 | 124 | 126 | 127 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/OneNoteServiceSamplesWinUniversal.WindowsPhone.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {7310B814-9334-43BC-921C-735B66984A1D} 8 | AppContainerExe 9 | Properties 10 | OneNoteServiceSamplesWinUniversal 11 | OneNoteServiceSamplesWinUniversal.WindowsPhone 12 | en-US 13 | 8.1 14 | 12 15 | 512 16 | {76F1466A-8B6D-4E39-A767-685A06062A39};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 17 | true 18 | ..\ 19 | true 20 | 21 | 22 | AnyCPU 23 | true 24 | full 25 | false 26 | bin\Debug\ 27 | DEBUG;TRACE;NETFX_CORE;WINDOWS_PHONE_APP 28 | prompt 29 | 4 30 | 31 | 32 | AnyCPU 33 | pdbonly 34 | true 35 | bin\Release\ 36 | TRACE;NETFX_CORE;WINDOWS_PHONE_APP 37 | prompt 38 | 4 39 | 40 | 41 | true 42 | bin\ARM\Debug\ 43 | DEBUG;TRACE;NETFX_CORE;WINDOWS_PHONE_APP 44 | ;2008 45 | full 46 | ARM 47 | false 48 | prompt 49 | false 50 | 51 | 52 | bin\ARM\Release\ 53 | TRACE;NETFX_CORE;WINDOWS_PHONE_APP 54 | true 55 | ;2008 56 | pdbonly 57 | ARM 58 | false 59 | prompt 60 | false 61 | 62 | 63 | true 64 | bin\x86\Debug\ 65 | DEBUG;TRACE;NETFX_CORE;WINDOWS_PHONE_APP 66 | ;2008 67 | full 68 | x86 69 | false 70 | prompt 71 | false 72 | 73 | 74 | bin\x86\Release\ 75 | TRACE;NETFX_CORE;WINDOWS_PHONE_APP 76 | true 77 | ;2008 78 | pdbonly 79 | x86 80 | false 81 | prompt 82 | false 83 | 84 | 85 | 86 | 87 | HubPage.xaml 88 | 89 | 90 | 91 | SectionPage.xaml 92 | 93 | 94 | ItemPage.xaml 95 | 96 | 97 | 98 | 99 | Designer 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | MSBuild:Compile 116 | Designer 117 | 118 | 119 | Designer 120 | MSBuild:Compile 121 | 122 | 123 | Designer 124 | MSBuild:Compile 125 | 126 | 127 | 128 | 129 | ..\packages\Microsoft.IdentityModel.Clients.ActiveDirectory.2.14.201151115\lib\wpa\Microsoft.IdentityModel.Clients.ActiveDirectory.winmd 130 | 131 | 132 | ..\packages\Newtonsoft.Json.6.0.4\lib\portable-net45+wp80+win8+wpa81\Newtonsoft.Json.dll 133 | 134 | 135 | 136 | 137 | 138 | 139 | 12.0 140 | 141 | 142 | 143 | WindowsPhoneApp 144 | 145 | 146 | 147 | 148 | 149 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 150 | 151 | 152 | 153 | 160 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.WindowsPhone/HubPage.xaml: -------------------------------------------------------------------------------- 1 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 58 | 59 | 60 | 61 | 62 | 64 | 65 | 66 | 67 | 68 | 70 | 71 | 72 | 73 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 92 | 93 | 100 | 101 | 102 | 103 | 104 | 106 | 107 | 114 | 115 | 116 | 117 | 118 | 120 | 121 | 128 | 129 | 130 | 131 | 132 | 134 | 135 | 142 | 143 | 144 | 145 | 147 | 148 | 155 | 156 | 157 | 158 | 159 | 160 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/ItemPage.xaml.cs: -------------------------------------------------------------------------------- 1 | using OneNoteServiceSamplesWinUniversal.Data; 2 | using OneNoteServiceSamplesWinUniversal.Common; 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | using Windows.ApplicationModel.Core; 9 | using Windows.Foundation; 10 | using Windows.System; 11 | using Windows.UI.Core; 12 | using Windows.UI.Xaml; 13 | using Windows.UI.Xaml.Controls; 14 | using Windows.UI.Xaml.Controls.Primitives; 15 | 16 | using Windows.UI.Xaml.Navigation; 17 | 18 | // The Universal Hub Application project template is documented at http://go.microsoft.com/fwlink/?LinkID=391955 19 | using OneNoteServiceSamplesWinUniversal.OneNoteApi; 20 | using System.ComponentModel; 21 | using System.Net; 22 | using OneNoteServiceSamplesWinUniversal.DataModel; 23 | 24 | namespace OneNoteServiceSamplesWinUniversal 25 | { 26 | /// 27 | /// A page that displays details for a single item within a group. 28 | /// 29 | public sealed partial class ItemPage : SharedBasePage 30 | { 31 | private readonly NavigationHelper _navigationHelper; 32 | private readonly ItemPageModel _model = new ItemPageModel(); 33 | 34 | public ItemPage() 35 | { 36 | InitializeComponent(); 37 | DataContext = Model; 38 | _navigationHelper = new NavigationHelper(this); 39 | _navigationHelper.LoadState += NavigationHelper_LoadState; 40 | } 41 | 42 | /// 43 | /// Gets the NavigationHelper used to aid in navigation and process lifetime management. 44 | /// 45 | public NavigationHelper NavigationHelper 46 | { 47 | get { return _navigationHelper; } 48 | } 49 | 50 | public ItemPageModel Model 51 | { 52 | get { return _model; } 53 | } 54 | 55 | /// 56 | /// Populates the page with content passed during navigation. Any saved state is also 57 | /// provided when recreating a page from a prior session. 58 | /// 59 | /// 60 | /// The source of the event; typically 61 | /// 62 | /// Event data that provides both the navigation parameter passed to 63 | /// when this page was initially requested and 64 | /// a dictionary of state preserved by this page during an earlier 65 | /// session. The state will be null the first time a page is visited. 66 | private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e) 67 | { 68 | var itemId = e.NavigationParameter as string; 69 | if (itemId != null) 70 | { 71 | UserData.ItemId = itemId; 72 | } 73 | else 74 | { 75 | UserData = (HubContext) e.NavigationParameter; 76 | } 77 | 78 | var item = await SampleDataSource.GetItemAsync(UserData.ItemId); 79 | Model.Item = item; 80 | InputSelectionPanel2.Visibility = (item.RequiresInputComboBox2) ? Visibility.Visible : Visibility.Collapsed; 81 | InputTextBox.Visibility = (item.RequiresInputTextBox) ? Visibility.Visible : Visibility.Collapsed; 82 | if (item.RequiresInputComboBox1) 83 | { 84 | var response = await SampleDataSource.ExecuteApiPrereq(item.UniqueId, UserData.Provider, UserData.UseBeta); 85 | if (response is List) 86 | { 87 | InputComboBox1.ItemsSource = response; 88 | InputSelectionPanel1.Visibility = Visibility.Visible; 89 | } 90 | } 91 | else 92 | { 93 | InputSelectionPanel1.Visibility = Visibility.Collapsed; 94 | } 95 | } 96 | 97 | #region NavigationHelper registration 98 | 99 | /// 100 | /// The methods provided in this section are simply used to allow 101 | /// NavigationHelper to respond to the page's navigation methods. 102 | /// Page specific logic should be placed in event handlers for the 103 | /// 104 | /// and . 105 | /// The navigation parameter is available in the LoadState method 106 | /// in addition to page state preserved during an earlier session. 107 | /// 108 | protected override async void OnNavigatedTo(NavigationEventArgs e) 109 | { 110 | _navigationHelper.OnNavigatedTo(e); 111 | Model.AuthUserName = await Auth.GetUserName(UserData.Provider); 112 | } 113 | 114 | protected override void OnNavigatedFrom(NavigationEventArgs e) 115 | { 116 | _navigationHelper.OnNavigatedFrom(e); 117 | } 118 | 119 | #endregion 120 | 121 | private async void Button_Click(object sender, RoutedEventArgs e) 122 | { 123 | var button = sender as Button; 124 | bool debug = button != null && button.Name.Equals("DebugButton"); 125 | SampleDataItem item = Model.Item; 126 | 127 | UserData.TimeStamp = DateTime.UtcNow; 128 | Model.UserData = UserData; 129 | Model.AuthUserName = await Auth.GetUserName(UserData.Provider); 130 | 131 | await ExecuteApiAction(debug, item); 132 | } 133 | 134 | private async Task ExecuteApiAction(bool debug, SampleDataItem item) 135 | { 136 | Model.ApiResponse = null; 137 | 138 | string requiredSelectedId = null; 139 | if (item.RequiresInputComboBox1) 140 | { 141 | var selectedItem = (ApiBaseResponse) InputComboBox1.SelectedItem; 142 | if (selectedItem != null) 143 | { 144 | requiredSelectedId = selectedItem.Id; 145 | } 146 | else 147 | { 148 | FlyoutBase.ShowAttachedFlyout(InputComboBox1); 149 | return; 150 | } 151 | } 152 | if (item.RequiresInputComboBox2) 153 | { 154 | var selectedItem = (ApiBaseResponse) InputComboBox2.SelectedItem; 155 | if (selectedItem != null) 156 | { 157 | requiredSelectedId = selectedItem.Id; 158 | } 159 | else 160 | { 161 | FlyoutBase.ShowAttachedFlyout(InputComboBox2); 162 | return; 163 | } 164 | } 165 | 166 | string requiredInputText = null; 167 | if (item.RequiresInputTextBox) 168 | { 169 | requiredInputText = InputTextBox.Text; 170 | if (String.IsNullOrWhiteSpace(requiredInputText) || requiredInputText.Equals("Enter required text here")) 171 | { 172 | FlyoutBase.ShowAttachedFlyout(InputTextBox); 173 | return; 174 | } 175 | } 176 | 177 | Model.ApiResponse = await SampleDataSource.ExecuteApi(item.UniqueId, debug, requiredSelectedId, requiredInputText, UserData.Provider, UserData.UseBeta); 178 | } 179 | 180 | /// 181 | /// Yield the thread of operation to the dispatcher to allow UI updates to happen. 182 | /// 183 | /// 184 | /// Schedules a do-nothing operation on the dispatcher, then allows continuation after it's 'completed'. 185 | /// Usage: await Yield(); 186 | /// 187 | /// A dispatcher operation that is awaitable. 188 | /// 189 | private static IAsyncAction Yield() 190 | { 191 | return CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { }); 192 | } 193 | 194 | private void InputTextBox_OnGotFocus(object sender, RoutedEventArgs e) 195 | { 196 | //Clear the section hint if that was the existing value 197 | string sectionSpecified = InputTextBox.Text; 198 | if (sectionSpecified.Equals("Enter required text here")) 199 | { 200 | InputTextBox.Text = string.Empty; 201 | } 202 | } 203 | 204 | private void InputTextBox_OnLostFocus(object sender, RoutedEventArgs e) 205 | { 206 | //Restore the section hint if a value was not entered 207 | string sectionSpecified = InputTextBox.Text; 208 | if (string.IsNullOrEmpty(sectionSpecified)) 209 | { 210 | InputTextBox.Text = "Enter required text here"; 211 | } 212 | } 213 | 214 | private async void ClientLinkLaunchButton_OnClickLinkLaunchButton_Click(object sender, RoutedEventArgs e) 215 | { 216 | Uri uri; 217 | if (Uri.TryCreate(ClientLinkTextBox.Text, UriKind.Absolute, out uri)) 218 | { 219 | await Launcher.LaunchUriAsync(uri); 220 | } 221 | } 222 | private async void WebLinkLaunchButton_Click(object sender, RoutedEventArgs e) 223 | { 224 | Uri uri; 225 | if (Uri.TryCreate(WebLinkTextBox.Text, UriKind.Absolute, out uri)) 226 | { 227 | await Launcher.LaunchUriAsync(uri); 228 | } 229 | } 230 | 231 | private void InputComboBox1_OnSelectionChanged(object sender, SelectionChangedEventArgs e) 232 | { 233 | if (InputSelectionPanel2.Visibility == Visibility.Visible) 234 | { 235 | var comboBox = sender as ComboBox; 236 | if (comboBox != null && comboBox.SelectedItem != null) 237 | { 238 | var response = comboBox.SelectedItem as GenericEntityResponse; 239 | if (response != null && response.Sections != null) 240 | { 241 | InputComboBox2.ItemsSource = response.Sections; 242 | } 243 | } 244 | } 245 | } 246 | } 247 | } -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Shared/OneNoteApi/O365Auth.cs: -------------------------------------------------------------------------------- 1 | //********************************************************* 2 | // Copyright (c) Microsoft Corporation 3 | // All rights reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the ""License""); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS 12 | // OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 13 | // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR 14 | // PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. 15 | // 16 | // See the Apache Version 2.0 License for specific language 17 | // governing permissions and limitations under the License. 18 | //********************************************************* 19 | 20 | using System; 21 | using System.Diagnostics; 22 | using System.Linq; 23 | using System.Text.RegularExpressions; 24 | using System.Threading.Tasks; 25 | 26 | using Microsoft.IdentityModel.Clients.ActiveDirectory; 27 | using Windows.ApplicationModel.Activation; 28 | namespace OneNoteServiceSamplesWinUniversal.OneNoteApi 29 | { 30 | /// 31 | /// This class contains all Authentication related code for interacting with the OneNote APIs over O365 32 | /// 33 | internal static class O365Auth 34 | { 35 | private static AuthenticationResult _authenticationResult; 36 | private static AuthenticationContext _authenticationContext; 37 | 38 | // TODO: Replace the below ClientId with your app's ClientId. 39 | // For more info, see: http://msdn.microsoft.com/en-us/library/office/dn575426(v=office.15).aspx 40 | private const string ClientId = "2bb5432a-93d1-4a3d-955e-e20c8d0e00e0"; // onebeta 41 | 42 | // OneNote APIs support multiple O365 scopes for OneNote entity. 43 | // As a guideline, always choose the least permissible scope that your app needs. 44 | // Since this code sample demonstrates multiple aspects of the APIs, it uses the most 45 | // permissible scope. 46 | 47 | private const string AuthContextUrl = "https://login.windows.net/Common"; 48 | 49 | private const string ResourceUri = "https://onenote.com"; 50 | 51 | // TODO: Replace the below RedirectUri with your app's RedirectUri. 52 | private const string RedirectUri = "https://localhost"; 53 | 54 | /// 55 | /// Gets a valid authentication token. Also refreshes the access token if it has expired. 56 | /// 57 | /// 58 | /// Used by the API request generators before making calls to the OneNote APIs. 59 | /// 60 | /// valid authentication token 61 | internal static async Task GetAuthToken() 62 | { 63 | return (await GetAuthenticationResult()).AccessToken; 64 | } 65 | 66 | internal static AuthenticationContext AuthContext 67 | { 68 | get 69 | { 70 | //create a new authentication context for our app 71 | #if WINDOWS_PHONE_APP 72 | return _authenticationContext ?? (_authenticationContext = AuthenticationContext.CreateAsync(AuthContextUrl).GetResults()); 73 | #else 74 | return _authenticationContext ?? (_authenticationContext = new AuthenticationContext(AuthContextUrl)); 75 | #endif 76 | } 77 | set { _authenticationContext = value; } 78 | } 79 | 80 | internal static string AccessToken 81 | { 82 | get { return _authenticationResult != null ? _authenticationResult.AccessToken : string.Empty; } 83 | } 84 | 85 | /// 86 | /// Gets a valid authentication token. Also refreshes the access token if it has expired. 87 | /// 88 | /// 89 | /// Used by the API request generators before making calls to the OneNote APIs. 90 | /// 91 | /// valid authentication token 92 | internal static async Task GetAuthenticationResult() 93 | { 94 | if (String.IsNullOrEmpty(AccessToken)) 95 | { 96 | try 97 | { 98 | //look to see if we have an authentication context in cache already 99 | //we would have gotten this when we authenticated previously 100 | var allCachedItems = AuthContext.TokenCache.ReadItems(); 101 | var validCachedItems = allCachedItems 102 | .Where(i => i.ExpiresOn > DateTimeOffset.UtcNow.UtcDateTime && IsO365Token(i.IdentityProvider)) 103 | .OrderByDescending(e=>e.ExpiresOn); 104 | var cachedItem = validCachedItems.First(); 105 | if (cachedItem != null) 106 | { 107 | //re-bind AuthenticationContext to the authority source of the cached token. 108 | //this is needed for the cache to work when asking for a token from that authority. 109 | #if WINDOWS_PHONE_APP 110 | AuthContext = AuthenticationContext.CreateAsync(cachedItem.Authority, true).GetResults(); 111 | #else 112 | AuthContext = new AuthenticationContext(cachedItem.Authority, true); 113 | #endif 114 | 115 | //try to get the AccessToken silently using the resourceId that was passed in 116 | //and the client ID of the application. 117 | _authenticationResult = await AuthContext.AcquireTokenSilentAsync(GetResourceHost(ResourceUri), ClientId); 118 | RefreshAuthTokenIfNeeded().Wait(); 119 | } 120 | } 121 | catch (Exception) 122 | { 123 | //not in cache; we'll get it with the full oauth flow 124 | } 125 | } 126 | 127 | if (string.IsNullOrEmpty(AccessToken)) 128 | { 129 | try 130 | { 131 | AuthContext.TokenCache.Clear(); 132 | #if WINDOWS_PHONE_APP 133 | 134 | _authenticationResult = await AuthContext.AcquireTokenSilentAsync(GetResourceHost(ResourceUri), ClientId); 135 | 136 | if (_authenticationResult == null || string.IsNullOrEmpty(_authenticationResult.AccessToken)) 137 | { 138 | AuthContext.AcquireTokenAndContinue(GetResourceHost(ResourceUri), ClientId, new Uri(RedirectUri), null); 139 | } 140 | #else 141 | _authenticationResult = 142 | await AuthContext.AcquireTokenAsync(GetResourceHost(ResourceUri), ClientId, new Uri(RedirectUri), PromptBehavior.Always); 143 | #endif 144 | } 145 | catch (Exception) 146 | { 147 | // Authentication failed 148 | if (Debugger.IsAttached) 149 | Debugger.Break(); 150 | } 151 | } 152 | 153 | return _authenticationResult; 154 | } 155 | 156 | private static bool IsO365Token(string identityProvider) 157 | { 158 | Match result = Regex.Match(identityProvider, "https://.*.windows.*.net/.*/"); 159 | return result.Success; 160 | } 161 | private static string GetResourceHost(string url) 162 | { 163 | Uri theHost = new Uri(url); 164 | return theHost.Scheme + "://" + theHost.Host + "/"; 165 | } 166 | 167 | internal static async Task SignOut() 168 | { 169 | await Task.Delay(0); 170 | 171 | if (IsSignedIn) 172 | { 173 | if (_authenticationContext != null) 174 | { 175 | _authenticationContext.TokenCache.Clear(); 176 | } 177 | _authenticationResult = null; 178 | } 179 | } 180 | 181 | internal static bool IsSignedIn 182 | { 183 | get { return !string.IsNullOrEmpty(AccessToken); } 184 | } 185 | 186 | internal async static Task GetUserName() 187 | { 188 | await Task.Delay(0); 189 | return _authenticationResult != null ? 190 | (_authenticationResult.UserInfo != null ? 191 | _authenticationResult.UserInfo.GivenName + " " + _authenticationResult.UserInfo.FamilyName: string.Empty ): string.Empty; 192 | } 193 | 194 | #region RefreshToken related code 195 | 196 | /// 197 | /// Refreshes the live authentication access token if it is about to expire in next 5 minutes 198 | /// 199 | public static async Task RefreshAuthTokenIfNeeded(double minutes = 5) 200 | { 201 | if (_authenticationResult != null && DateTimeOffset.Now.UtcDateTime.AddMinutes(minutes) > _authenticationResult.ExpiresOn) 202 | { 203 | await AttemptAccessTokenRefresh(); 204 | } 205 | } 206 | 207 | /// 208 | /// This method tries to refresh the access token. The token needs to be 209 | /// efreshed continuously, so that the user is not prompted to sign in again 210 | /// 211 | /// 212 | public static async Task AttemptAccessTokenRefresh() 213 | { 214 | _authenticationResult = await AuthContext.AcquireTokenByRefreshTokenAsync(_authenticationResult.RefreshToken, ClientId); 215 | } 216 | 217 | #endregion 218 | 219 | #if WINDOWS_PHONE_APP 220 | internal static async Task ContinueAcquireTokenAsync(WebAuthenticationBrokerContinuationEventArgs args) 221 | { 222 | _authenticationResult = await _authenticationContext.ContinueAcquireTokenAsync(args); 223 | 224 | // TODO by app developer: ideally we want to preserve the state of what we wanted to do before the continuation call, and do it. 225 | // see https://msdn.microsoft.com/library/windows/apps/dn631755.aspx and http://www.cloudidentity.com/blog/2014/06/16/adal-for-windows-phone-8-1-deep-dive/ 226 | } 227 | #endif 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /OneNoteServiceSamplesWinUniversal.Windows/OneNoteServiceSamplesWinUniversal.Windows.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {04B19D2E-1156-423E-8E90-524F91EE688F} 8 | AppContainerExe 9 | Properties 10 | OneNoteServiceSamplesWinUniversal 11 | OneNoteServiceSamplesWinUniversal.Windows 12 | en-US 13 | 8.1 14 | 12 15 | 512 16 | {BC8A1FFA-BEE3-4634-8014-F334798102B3};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 17 | true 18 | OneNoteServiceSamplesWinUniversal.Windows_StoreKey.pfx 19 | A02B7083F443C81C005D43E9F58A8F870F7639A6 20 | ..\ 21 | true 22 | 23 | 24 | AnyCPU 25 | true 26 | full 27 | false 28 | bin\Debug\ 29 | DEBUG;TRACE;NETFX_CORE;WINDOWS_APP 30 | prompt 31 | 4 32 | 33 | 34 | AnyCPU 35 | pdbonly 36 | true 37 | bin\Release\ 38 | TRACE;NETFX_CORE;WINDOWS_APP 39 | prompt 40 | 4 41 | 42 | 43 | true 44 | bin\ARM\Debug\ 45 | DEBUG;TRACE;NETFX_CORE;WINDOWS_APP 46 | ;2008 47 | full 48 | ARM 49 | false 50 | prompt 51 | true 52 | 53 | 54 | bin\ARM\Release\ 55 | TRACE;NETFX_CORE;WINDOWS_APP 56 | true 57 | ;2008 58 | pdbonly 59 | ARM 60 | false 61 | prompt 62 | true 63 | 64 | 65 | true 66 | bin\x64\Debug\ 67 | DEBUG;TRACE;NETFX_CORE;WINDOWS_APP 68 | ;2008 69 | full 70 | x64 71 | false 72 | prompt 73 | true 74 | 75 | 76 | bin\x64\Release\ 77 | TRACE;NETFX_CORE;WINDOWS_APP 78 | true 79 | ;2008 80 | pdbonly 81 | x64 82 | false 83 | prompt 84 | true 85 | 86 | 87 | true 88 | bin\x86\Debug\ 89 | DEBUG;TRACE;NETFX_CORE;WINDOWS_APP 90 | ;2008 91 | full 92 | x86 93 | false 94 | prompt 95 | true 96 | 97 | 98 | bin\x86\Release\ 99 | TRACE;NETFX_CORE;WINDOWS_APP 100 | true 101 | ;2008 102 | pdbonly 103 | x86 104 | false 105 | prompt 106 | true 107 | 108 | 109 | 110 | HubPage.xaml 111 | 112 | 113 | SectionPage.xaml 114 | 115 | 116 | ItemPage.xaml 117 | 118 | 119 | 120 | 121 | 122 | Designer 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | MSBuild:Compile 137 | Designer 138 | 139 | 140 | MSBuild:Compile 141 | Designer 142 | 143 | 144 | MSBuild:Compile 145 | Designer 146 | 147 | 148 | 149 | 150 | ..\packages\Microsoft.IdentityModel.Clients.ActiveDirectory.2.14.201151115\lib\netcore45\Microsoft.IdentityModel.Clients.ActiveDirectory.winmd 151 | 152 | 153 | ..\packages\Newtonsoft.Json.6.0.4\lib\netcore45\Newtonsoft.Json.dll 154 | 155 | 156 | 157 | 12.0 158 | 159 | 160 | 161 | 162 | 163 | 164 | This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 165 | 166 | 167 | 168 | 175 | --------------------------------------------------------------------------------