├── LICENSE.txt
├── OneNoteCloudCreatePagesSample.sln.DotSettings
├── OneNoteCloudCreatePagesSample
├── AccountFlyout.xaml
├── AccountFlyout.xaml.cs
├── App.xaml
├── App.xaml.cs
├── Assets
│ ├── DarkGray.png
│ ├── LightGray.png
│ ├── Logo.jpg
│ ├── Logo.png
│ ├── MediumGray.png
│ ├── SmallLogo.png
│ ├── SplashScreen.png
│ ├── StoreLogo.png
│ └── attachment.pdf
├── Common
│ ├── BindableBase.cs
│ ├── BooleanNegationConverter.cs
│ ├── BooleanToVisibilityConverter.cs
│ ├── LayoutAwarePage.cs
│ ├── ReadMe.txt
│ ├── RichTextColumns.cs
│ ├── SettingsFlyout.cs
│ ├── StandardStyles.xaml
│ └── SuspensionManager.cs
├── CreateExamples.cs
├── DataModel
│ └── SampleDataSource.cs
├── MainPage.xaml
├── MainPage.xaml.cs
├── OneNoteServiceCreatePagesSample.csproj
├── Package.appxmanifest
├── PrivacyFlyout.xaml
├── PrivacyFlyout.xaml.cs
├── Properties
│ └── AssemblyInfo.cs
├── StandardResponse.cs
└── packages.config
├── OneNoteServiceCreatePagesSample.sln
└── README.md
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample.sln.DotSettings:
--------------------------------------------------------------------------------
1 |
2 | <Policy Inspect="True" Prefix="" Suffix="" Style="aaBb" />
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/AccountFlyout.xaml:
--------------------------------------------------------------------------------
1 |
21 |
22 |
34 |
35 |
36 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/AccountFlyout.xaml.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 Microsoft.Live;
21 | using OneNoteCloudCreatePagesSample.Common;
22 | using Windows.UI.Xaml;
23 |
24 | namespace OneNoteCloudCreatePagesSample
25 | {
26 | ///
27 | /// Reepresents a settings flyout for handlign account sign in/sign out
28 | ///
29 | public sealed partial class AccountFlyout : SettingsFlyout
30 | {
31 | public static readonly DependencyProperty SignInNameProperty =
32 | DependencyProperty.Register("SignInName", typeof (string), typeof (AccountFlyout),
33 | new PropertyMetadata(null));
34 |
35 | public static readonly DependencyProperty IsSignedInProperty =
36 | DependencyProperty.Register("IsSignedIn", typeof(bool), typeof(AccountFlyout),
37 | new PropertyMetadata(null));
38 | ///
39 | /// Name shown as currently signed in user
40 | ///
41 | public string SignInName
42 | {
43 | get { return (string)this.GetValue(SignInNameProperty); }
44 | set { this.SetValue(SignInNameProperty, value); }
45 | }
46 |
47 | ///
48 | /// Is the user currently signed in
49 | ///
50 | public bool IsSignedIn
51 | {
52 | get { return (bool)this.GetValue(IsSignedInProperty); }
53 | set { this.SetValue(IsSignedInProperty, value); }
54 | }
55 |
56 | ///
57 | /// Constructor
58 | ///
59 | public AccountFlyout()
60 | {
61 | this.InitializeComponent();
62 | }
63 |
64 | ///
65 | /// Opportunity to do flyout-specific logic when it the flyout is opened
66 | ///
67 | protected override void OnOpening()
68 | {
69 | base.OnOpening();
70 | this.UpdateState();
71 | }
72 |
73 | ///
74 | /// Click handler for sign in button
75 | ///
76 | private async void SignInClick(object sender, RoutedEventArgs e)
77 | {
78 | try
79 | {
80 | await MainPage.Current.SignIn();
81 | this.UpdateState();
82 | }
83 | catch (LiveConnectException)
84 | {
85 | // Handle exception.
86 | }
87 | }
88 |
89 | ///
90 | /// Click handler for sign out button
91 | ///
92 | private async void SignOutClick(object sender, RoutedEventArgs e)
93 | {
94 | try
95 | {
96 | await MainPage.Current.SignOut();
97 | this.UpdateState();
98 | }
99 | catch (LiveConnectException)
100 | {
101 | // Handle exception.
102 | }
103 | }
104 |
105 | ///
106 | /// Update the UI state to match the live status
107 | ///
108 | public void UpdateState()
109 | {
110 | try
111 | {
112 | this.SignInName = MainPage.Current.SignInName;
113 | this.IsSignedIn = MainPage.Current.IsSignedIn;
114 | if (this.IsSignedIn)
115 | {
116 | // Show sign-out button if they can sign out.
117 | signOutBtn.Visibility = (MainPage.Current.AuthClient.CanLogout
118 | ? Visibility.Visible
119 | : Visibility.Collapsed);
120 | signInBtn.Visibility = Visibility.Collapsed;
121 | }
122 | else
123 | {
124 | // Show sign-in button.
125 | signInBtn.Visibility = Visibility.Visible;
126 | signOutBtn.Visibility = Visibility.Collapsed;
127 | }
128 | }
129 | catch (LiveConnectException)
130 | {
131 | // Handle exception.
132 | }
133 | }
134 | }
135 | }
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/App.xaml:
--------------------------------------------------------------------------------
1 |
21 |
25 |
26 |
27 |
28 |
29 |
30 |
34 |
35 |
36 |
37 |
38 |
39 | OneNoteCloudCreatePagesSample
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/App.xaml.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 OneNoteCloudCreatePagesSample.Common;
21 |
22 | using System;
23 | using Windows.ApplicationModel;
24 | using Windows.ApplicationModel.Activation;
25 | using Windows.UI.ApplicationSettings;
26 | using Windows.UI.Xaml;
27 | using Windows.UI.Xaml.Controls;
28 |
29 | // The Split App template is documented at http://go.microsoft.com/fwlink/?LinkId=234228
30 |
31 | namespace OneNoteCloudCreatePagesSample
32 | {
33 | ///
34 | /// Provides application-specific behavior to supplement the default Application class.
35 | ///
36 | sealed partial class App : Application
37 | {
38 | ///
39 | /// Initializes the singleton Application object. This is the first line of authored code
40 | /// executed, and as such is the logical equivalent of main() or WinMain().
41 | ///
42 | public App()
43 | {
44 | this.InitializeComponent();
45 | this.Suspending += OnSuspending;
46 | }
47 |
48 | ///
49 | /// Invoked when the application is launched normally by the end user. Other entry points
50 | /// will be used when the application is launched to open a specific file, to display
51 | /// search results, and so forth.
52 | ///
53 | /// Details about the launch request and process.
54 | protected override async void OnLaunched(LaunchActivatedEventArgs args)
55 | {
56 | var rootFrame = Window.Current.Content as Frame;
57 |
58 | // Do not repeat app initialization when the Window already has content,
59 | // just ensure that the window is active
60 |
61 | if (rootFrame == null)
62 | {
63 | // Create a Frame to act as the navigation context and navigate to the first page
64 | rootFrame = new Frame();
65 | //Associate the frame with a SuspensionManager key
66 | SuspensionManager.RegisterFrame(rootFrame, "AppFrame");
67 |
68 | if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
69 | {
70 | // Restore the saved session state only when appropriate
71 | try
72 | {
73 | await SuspensionManager.RestoreAsync();
74 | }
75 | catch (SuspensionManagerException)
76 | {
77 | //Something went wrong restoring state.
78 | //Assume there is no state and continue
79 | }
80 | }
81 |
82 | // Place the frame in the current Window
83 | Window.Current.Content = rootFrame;
84 | }
85 | if (rootFrame.Content == null)
86 | {
87 | // When the navigation stack isn't restored navigate to the first page,
88 | // configuring the new page by passing required information as a navigation
89 | // parameter
90 | if (!rootFrame.Navigate(typeof(MainPage), "CreateScenarios"))
91 | {
92 | throw new Exception("Failed to create initial page");
93 | }
94 | }
95 | // Ensure the current window is active
96 | Window.Current.Activate();
97 | }
98 |
99 | ///
100 | /// Invoked when application execution is being suspended. Application state is saved
101 | /// without knowing whether the application will be terminated or resumed with the contents
102 | /// of memory still intact.
103 | ///
104 | /// The source of the suspend request.
105 | /// Details about the suspend request.
106 | private async void OnSuspending(object sender, SuspendingEventArgs e)
107 | {
108 | var deferral = e.SuspendingOperation.GetDeferral();
109 | await SuspensionManager.SaveAsync();
110 | deferral.Complete();
111 | }
112 |
113 | ///
114 | /// Invoked when the window is created
115 | ///
116 | protected override void OnWindowCreated(WindowCreatedEventArgs args)
117 | {
118 | base.OnWindowCreated(args);
119 | SettingsPane.GetForCurrentView().CommandsRequested += App_CommandsRequested;
120 | }
121 |
122 | ///
123 | /// Invoked when the settings pane is shown
124 | ///
125 | void App_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
126 | {
127 | var privacyCommand = new SettingsCommand("{69B8340C-C388-41D7-BA46-DB4E791928DD}", "Privacy",
128 | handler => MainPage.Current.OpenPrivacySettingsFlyout(handler));
129 | args.Request.ApplicationCommands.Add(privacyCommand);
130 | var accountCommand = new SettingsCommand("{D0EB2AC6-D51D-420A-A463-48B707AA232C}", "Account",
131 | handler => MainPage.Current.OpenAccountSettingsFlyout(handler));
132 | args.Request.ApplicationCommands.Add(accountCommand);
133 | }
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Assets/DarkGray.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinStore/15c75fab203e6530274dd6a84cff9b76909a2806/OneNoteCloudCreatePagesSample/Assets/DarkGray.png
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Assets/LightGray.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinStore/15c75fab203e6530274dd6a84cff9b76909a2806/OneNoteCloudCreatePagesSample/Assets/LightGray.png
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Assets/Logo.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinStore/15c75fab203e6530274dd6a84cff9b76909a2806/OneNoteCloudCreatePagesSample/Assets/Logo.jpg
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Assets/Logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinStore/15c75fab203e6530274dd6a84cff9b76909a2806/OneNoteCloudCreatePagesSample/Assets/Logo.png
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Assets/MediumGray.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinStore/15c75fab203e6530274dd6a84cff9b76909a2806/OneNoteCloudCreatePagesSample/Assets/MediumGray.png
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Assets/SmallLogo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinStore/15c75fab203e6530274dd6a84cff9b76909a2806/OneNoteCloudCreatePagesSample/Assets/SmallLogo.png
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Assets/SplashScreen.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinStore/15c75fab203e6530274dd6a84cff9b76909a2806/OneNoteCloudCreatePagesSample/Assets/SplashScreen.png
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Assets/StoreLogo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinStore/15c75fab203e6530274dd6a84cff9b76909a2806/OneNoteCloudCreatePagesSample/Assets/StoreLogo.png
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Assets/attachment.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/OneNoteDev/OneNoteAPISampleWinStore/15c75fab203e6530274dd6a84cff9b76909a2806/OneNoteCloudCreatePagesSample/Assets/attachment.pdf
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Common/BindableBase.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.ComponentModel;
22 | using System.Runtime.CompilerServices;
23 |
24 | namespace OneNoteCloudCreatePagesSample.Common
25 | {
26 | ///
27 | /// Implementation of to simplify models.
28 | ///
29 | [Windows.Foundation.Metadata.WebHostHidden]
30 | public abstract class BindableBase : INotifyPropertyChanged
31 | {
32 | ///
33 | /// Multicast event for property change notifications.
34 | ///
35 | public event PropertyChangedEventHandler PropertyChanged;
36 |
37 | ///
38 | /// Checks if a property already matches a desired value. Sets the property and
39 | /// notifies listeners only when necessary.
40 | ///
41 | /// Type of the property.
42 | /// Reference to a property with both getter and setter.
43 | /// Desired value for the property.
44 | /// Name of the property used to notify listeners. This
45 | /// value is optional and can be provided automatically when invoked from compilers that
46 | /// support CallerMemberName.
47 | /// True if the value was changed, false if the existing value matched the
48 | /// desired value.
49 | protected bool SetProperty(ref T storage, T value, [CallerMemberName] String propertyName = null)
50 | {
51 | if (object.Equals(storage, value)) return false;
52 |
53 | storage = value;
54 | // ReSharper disable ExplicitCallerInfoArgument
55 | this.OnPropertyChanged(propertyName);
56 | // ReSharper restore ExplicitCallerInfoArgument
57 | return true;
58 | }
59 |
60 | ///
61 | /// Notifies listeners that a property value has changed.
62 | ///
63 | /// Name of the property used to notify listeners. This
64 | /// value is optional and can be provided automatically when invoked from compilers
65 | /// that support .
66 | protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
67 | {
68 | var eventHandler = this.PropertyChanged;
69 | if (eventHandler != null)
70 | {
71 | eventHandler(this, new PropertyChangedEventArgs(propertyName));
72 | }
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Common/BooleanNegationConverter.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 Windows.UI.Xaml.Data;
22 |
23 | namespace OneNoteCloudCreatePagesSample.Common
24 | {
25 | ///
26 | /// Value converter that translates true to false and vice versa.
27 | ///
28 | public sealed class BooleanNegationConverter : IValueConverter
29 | {
30 | public object Convert(object value, Type targetType, object parameter, string language)
31 | {
32 | return !(value is bool && (bool)value);
33 | }
34 |
35 | public object ConvertBack(object value, Type targetType, object parameter, string language)
36 | {
37 | return !(value is bool && (bool)value);
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Common/BooleanToVisibilityConverter.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 Windows.UI.Xaml;
22 | using Windows.UI.Xaml.Data;
23 |
24 | namespace OneNoteCloudCreatePagesSample.Common
25 | {
26 | ///
27 | /// Value converter that translates true to and false to
28 | /// .
29 | ///
30 | public sealed class BooleanToVisibilityConverter : IValueConverter
31 | {
32 | public object Convert(object value, Type targetType, object parameter, string language)
33 | {
34 | return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;
35 | }
36 |
37 | public object ConvertBack(object value, Type targetType, object parameter, string language)
38 | {
39 | return value is Visibility && (Visibility)value == Visibility.Visible;
40 | }
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Common/LayoutAwarePage.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.Collections.Generic;
22 | using System.Linq;
23 | using Windows.Foundation.Collections;
24 | using Windows.System;
25 | using Windows.UI.Core;
26 | using Windows.UI.ViewManagement;
27 | using Windows.UI.Xaml;
28 | using Windows.UI.Xaml.Controls;
29 | using Windows.UI.Xaml.Navigation;
30 |
31 | namespace OneNoteCloudCreatePagesSample.Common
32 | {
33 | ///
34 | /// Typical implementation of Page that provides several important conveniences:
35 | ///
36 | ///
37 | /// Application view state to visual state mapping
38 | ///
39 | ///
40 | /// GoBack, GoForward, and GoHome event handlers
41 | ///
42 | ///
43 | /// Mouse and keyboard shortcuts for navigation
44 | ///
45 | ///
46 | /// State management for navigation and process lifetime management
47 | ///
48 | ///
49 | /// A default view model
50 | ///
51 | ///
52 | ///
53 | [Windows.Foundation.Metadata.WebHostHidden]
54 | public class LayoutAwarePage : Windows.UI.Xaml.Controls.Page
55 | {
56 | ///
57 | /// Identifies the dependency property.
58 | ///
59 | public static readonly DependencyProperty DefaultViewModelProperty =
60 | DependencyProperty.Register("DefaultViewModel", typeof(IObservableMap),
61 | typeof(LayoutAwarePage), null);
62 |
63 | private List _layoutAwareControls;
64 |
65 | ///
66 | /// Initializes a new instance of the class.
67 | ///
68 | public LayoutAwarePage()
69 | {
70 | if (Windows.ApplicationModel.DesignMode.DesignModeEnabled) return;
71 |
72 | // Create an empty default view model
73 | this.DefaultViewModel = new ObservableDictionary();
74 |
75 | // When this page is part of the visual tree make two changes:
76 | // 1) Map application view state to visual state for the page
77 | // 2) Handle keyboard and mouse navigation requests
78 | this.Loaded += (sender, e) =>
79 | {
80 | this.StartLayoutUpdates(sender, e);
81 |
82 | // Keyboard and mouse navigation only apply when occupying the entire window
83 | if (this.ActualHeight == Window.Current.Bounds.Height &&
84 | this.ActualWidth == Window.Current.Bounds.Width)
85 | {
86 | // Listen to the window directly so focus isn't required
87 | Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated +=
88 | CoreDispatcher_AcceleratorKeyActivated;
89 | Window.Current.CoreWindow.PointerPressed +=
90 | this.CoreWindow_PointerPressed;
91 | }
92 | };
93 |
94 | // Undo the same changes when the page is no longer visible
95 | this.Unloaded += (sender, e) =>
96 | {
97 | this.StopLayoutUpdates(sender, e);
98 | Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated -=
99 | CoreDispatcher_AcceleratorKeyActivated;
100 | Window.Current.CoreWindow.PointerPressed -=
101 | this.CoreWindow_PointerPressed;
102 | };
103 | }
104 |
105 | ///
106 | /// An implementation of designed to be
107 | /// used as a trivial view model.
108 | ///
109 | protected IObservableMap DefaultViewModel
110 | {
111 | get
112 | {
113 | return this.GetValue(DefaultViewModelProperty) as IObservableMap;
114 | }
115 |
116 | set
117 | {
118 | this.SetValue(DefaultViewModelProperty, value);
119 | }
120 | }
121 |
122 | #region Navigation support
123 |
124 | ///
125 | /// Invoked as an event handler to navigate backward in the page's associated
126 | /// until it reaches the top of the navigation stack.
127 | ///
128 | /// Instance that triggered the event.
129 | /// Event data describing the conditions that led to the event.
130 | protected virtual void GoHome(object sender, RoutedEventArgs e)
131 | {
132 | // Use the navigation frame to return to the topmost page
133 | if (this.Frame != null)
134 | {
135 | while (this.Frame.CanGoBack) this.Frame.GoBack();
136 | }
137 | }
138 |
139 | ///
140 | /// Invoked as an event handler to navigate backward in the navigation stack
141 | /// associated with this page's .
142 | ///
143 | /// Instance that triggered the event.
144 | /// Event data describing the conditions that led to the
145 | /// event.
146 | protected virtual void GoBack(object sender, RoutedEventArgs e)
147 | {
148 | // Use the navigation frame to return to the previous page
149 | if (this.Frame != null && this.Frame.CanGoBack) this.Frame.GoBack();
150 | }
151 |
152 | ///
153 | /// Invoked as an event handler to navigate forward in the navigation stack
154 | /// associated with this page's .
155 | ///
156 | /// Instance that triggered the event.
157 | /// Event data describing the conditions that led to the
158 | /// event.
159 | protected virtual void GoForward(object sender, RoutedEventArgs e)
160 | {
161 | // Use the navigation frame to move to the next page
162 | if (this.Frame != null && this.Frame.CanGoForward) this.Frame.GoForward();
163 | }
164 |
165 | ///
166 | /// Invoked on every keystroke, including system keys such as Alt key combinations, when
167 | /// this page is active and occupies the entire window. Used to detect keyboard navigation
168 | /// between pages even when the page itself doesn't have focus.
169 | ///
170 | /// Instance that triggered the event.
171 | /// Event data describing the conditions that led to the event.
172 | private void CoreDispatcher_AcceleratorKeyActivated(CoreDispatcher sender,
173 | AcceleratorKeyEventArgs args)
174 | {
175 | var virtualKey = args.VirtualKey;
176 |
177 | // Only investigate further when Left, Right, or the dedicated Previous or Next keys
178 | // are pressed
179 | if ((args.EventType == CoreAcceleratorKeyEventType.SystemKeyDown ||
180 | args.EventType == CoreAcceleratorKeyEventType.KeyDown) &&
181 | (virtualKey == VirtualKey.Left || virtualKey == VirtualKey.Right ||
182 | (int)virtualKey == 166 || (int)virtualKey == 167))
183 | {
184 | var coreWindow = Window.Current.CoreWindow;
185 | const CoreVirtualKeyStates downState = CoreVirtualKeyStates.Down;
186 | bool menuKey = (coreWindow.GetKeyState(VirtualKey.Menu) & downState) == downState;
187 | bool controlKey = (coreWindow.GetKeyState(VirtualKey.Control) & downState) == downState;
188 | bool shiftKey = (coreWindow.GetKeyState(VirtualKey.Shift) & downState) == downState;
189 | bool noModifiers = !menuKey && !controlKey && !shiftKey;
190 | bool onlyAlt = menuKey && !controlKey && !shiftKey;
191 |
192 | if (((int)virtualKey == 166 && noModifiers) ||
193 | (virtualKey == VirtualKey.Left && onlyAlt))
194 | {
195 | // When the previous key or Alt+Left are pressed navigate back
196 | args.Handled = true;
197 | this.GoBack(this, new RoutedEventArgs());
198 | }
199 | else if (((int)virtualKey == 167 && noModifiers) ||
200 | (virtualKey == VirtualKey.Right && onlyAlt))
201 | {
202 | // When the next key or Alt+Right are pressed navigate forward
203 | args.Handled = true;
204 | this.GoForward(this, new RoutedEventArgs());
205 | }
206 | }
207 | }
208 |
209 | ///
210 | /// Invoked on every mouse click, touch screen tap, or equivalent interaction when this
211 | /// page is active and occupies the entire window. Used to detect browser-style next and
212 | /// previous mouse button clicks to navigate between pages.
213 | ///
214 | /// Instance that triggered the event.
215 | /// Event data describing the conditions that led to the event.
216 | private void CoreWindow_PointerPressed(CoreWindow sender,
217 | PointerEventArgs args)
218 | {
219 | var properties = args.CurrentPoint.Properties;
220 |
221 | // Ignore button chords with the left, right, and middle buttons
222 | if (properties.IsLeftButtonPressed || properties.IsRightButtonPressed ||
223 | properties.IsMiddleButtonPressed) return;
224 |
225 | // If back or foward are pressed (but not both) navigate appropriately
226 | bool backPressed = properties.IsXButton1Pressed;
227 | bool forwardPressed = properties.IsXButton2Pressed;
228 | if (backPressed ^ forwardPressed)
229 | {
230 | args.Handled = true;
231 | if (backPressed) this.GoBack(this, new RoutedEventArgs());
232 | if (forwardPressed) this.GoForward(this, new RoutedEventArgs());
233 | }
234 | }
235 |
236 | #endregion
237 |
238 | #region Visual state switching
239 |
240 | ///
241 | /// Invoked as an event handler, typically on the
242 | /// event of a within the page, to indicate that the sender should
243 | /// start receiving visual state management changes that correspond to application view
244 | /// state changes.
245 | ///
246 | /// Instance of that supports visual state
247 | /// management corresponding to view states.
248 | /// Event data that describes how the request was made.
249 | /// The current view state will immediately be used to set the corresponding
250 | /// visual state when layout updates are requested. A corresponding
251 | /// event handler connected to
252 | /// is strongly encouraged. Instances of
253 | /// automatically invoke these handlers in their Loaded and
254 | /// Unloaded events.
255 | ///
256 | ///
257 | public void StartLayoutUpdates(object sender, RoutedEventArgs e)
258 | {
259 | var control = sender as Control;
260 | if (control == null) return;
261 | if (this._layoutAwareControls == null)
262 | {
263 | // Start listening to view state changes when there are controls interested in updates
264 | Window.Current.SizeChanged += this.WindowSizeChanged;
265 | this._layoutAwareControls = new List();
266 | }
267 | this._layoutAwareControls.Add(control);
268 |
269 | // Set the initial visual state of the control
270 | VisualStateManager.GoToState(control, DetermineVisualState(ApplicationView.Value), false);
271 | }
272 |
273 | private void WindowSizeChanged(object sender, WindowSizeChangedEventArgs e)
274 | {
275 | this.InvalidateVisualState();
276 | }
277 |
278 | ///
279 | /// Invoked as an event handler, typically on the
280 | /// event of a , to indicate that the sender should start receiving
281 | /// visual state management changes that correspond to application view state changes.
282 | ///
283 | /// Instance of that supports visual state
284 | /// management corresponding to view states.
285 | /// Event data that describes how the request was made.
286 | /// The current view state will immediately be used to set the corresponding
287 | /// visual state when layout updates are requested.
288 | ///
289 | public void StopLayoutUpdates(object sender, RoutedEventArgs e)
290 | {
291 | var control = sender as Control;
292 | if (control == null || this._layoutAwareControls == null) return;
293 | this._layoutAwareControls.Remove(control);
294 | if (this._layoutAwareControls.Count == 0)
295 | {
296 | // Stop listening to view state changes when no controls are interested in updates
297 | this._layoutAwareControls = null;
298 | Window.Current.SizeChanged -= this.WindowSizeChanged;
299 | }
300 | }
301 |
302 | ///
303 | /// Translates values into strings for visual state
304 | /// management within the page. The default implementation uses the names of enum values.
305 | /// Subclasses may override this method to control the mapping scheme used.
306 | ///
307 | /// View state for which a visual state is desired.
308 | /// Visual state name used to drive the
309 | ///
310 | ///
311 | protected virtual string DetermineVisualState(ApplicationViewState viewState)
312 | {
313 | return viewState.ToString();
314 | }
315 |
316 | ///
317 | /// Updates all controls that are listening for visual state changes with the correct
318 | /// visual state.
319 | ///
320 | ///
321 | /// Typically used in conjunction with overriding to
322 | /// signal that a different value may be returned even though the view state has not
323 | /// changed.
324 | ///
325 | public void InvalidateVisualState()
326 | {
327 | if (this._layoutAwareControls != null)
328 | {
329 | string visualState = DetermineVisualState(ApplicationView.Value);
330 | foreach (var layoutAwareControl in this._layoutAwareControls)
331 | {
332 | VisualStateManager.GoToState(layoutAwareControl, visualState, false);
333 | }
334 | }
335 | }
336 |
337 | #endregion
338 |
339 | #region Process lifetime management
340 |
341 | private String _pageKey;
342 |
343 | ///
344 | /// Invoked when this page is about to be displayed in a Frame.
345 | ///
346 | /// Event data that describes how this page was reached. The Parameter
347 | /// property provides the group to be displayed.
348 | protected override void OnNavigatedTo(NavigationEventArgs e)
349 | {
350 | // Returning to a cached page through navigation shouldn't trigger state loading
351 | if (this._pageKey != null) return;
352 |
353 | var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
354 | this._pageKey = "Page-" + this.Frame.BackStackDepth;
355 |
356 | if (e.NavigationMode == NavigationMode.New)
357 | {
358 | // Clear existing state for forward navigation when adding a new page to the
359 | // navigation stack
360 | var nextPageKey = this._pageKey;
361 | int nextPageIndex = this.Frame.BackStackDepth;
362 | while (frameState.Remove(nextPageKey))
363 | {
364 | nextPageIndex++;
365 | nextPageKey = "Page-" + nextPageIndex;
366 | }
367 |
368 | // Pass the navigation parameter to the new page
369 | this.LoadState(e.Parameter, null);
370 | }
371 | else
372 | {
373 | // Pass the navigation parameter and preserved page state to the page, using
374 | // the same strategy for loading suspended state and recreating pages discarded
375 | // from cache
376 | this.LoadState(e.Parameter, (Dictionary)frameState[this._pageKey]);
377 | }
378 | }
379 |
380 | ///
381 | /// Invoked when this page will no longer be displayed in a Frame.
382 | ///
383 | /// Event data that describes how this page was reached. The Parameter
384 | /// property provides the group to be displayed.
385 | protected override void OnNavigatedFrom(NavigationEventArgs e)
386 | {
387 | var frameState = SuspensionManager.SessionStateForFrame(this.Frame);
388 | var pageState = new Dictionary();
389 | this.SaveState(pageState);
390 | frameState[_pageKey] = pageState;
391 | }
392 |
393 | ///
394 | /// Populates the page with content passed during navigation. Any saved state is also
395 | /// provided when recreating a page from a prior session.
396 | ///
397 | /// The parameter value passed to
398 | /// when this page was initially requested.
399 | ///
400 | /// A dictionary of state preserved by this page during an earlier
401 | /// session. This will be null the first time a page is visited.
402 | protected virtual void LoadState(Object navigationParameter, Dictionary pageState)
403 | {
404 | }
405 |
406 | ///
407 | /// Preserves state associated with this page in case the application is suspended or the
408 | /// page is discarded from the navigation cache. Values must conform to the serialization
409 | /// requirements of .
410 | ///
411 | /// An empty dictionary to be populated with serializable state.
412 | protected virtual void SaveState(Dictionary pageState)
413 | {
414 | }
415 |
416 | #endregion
417 |
418 | ///
419 | /// Implementation of IObservableMap that supports reentrancy for use as a default view
420 | /// model.
421 | ///
422 | private class ObservableDictionary : IObservableMap
423 | {
424 | private class ObservableDictionaryChangedEventArgs : IMapChangedEventArgs
425 | {
426 | public ObservableDictionaryChangedEventArgs(CollectionChange change, TKey key)
427 | {
428 | this.CollectionChange = change;
429 | this.Key = key;
430 | }
431 |
432 | public CollectionChange CollectionChange { get; private set; }
433 | public TKey Key { get; private set; }
434 | }
435 |
436 | private readonly Dictionary _dictionary = new Dictionary();
437 | public event MapChangedEventHandler MapChanged;
438 |
439 | private void InvokeMapChanged(CollectionChange change, TKey key)
440 | {
441 | var eventHandler = MapChanged;
442 | if (eventHandler != null)
443 | {
444 | eventHandler(this, new ObservableDictionaryChangedEventArgs(change, key));
445 | }
446 | }
447 |
448 | public void Add(TKey key, TValue value)
449 | {
450 | this._dictionary.Add(key, value);
451 | this.InvokeMapChanged(CollectionChange.ItemInserted, key);
452 | }
453 |
454 | public void Add(KeyValuePair item)
455 | {
456 | this.Add(item.Key, item.Value);
457 | }
458 |
459 | public bool Remove(TKey key)
460 | {
461 | if (this._dictionary.Remove(key))
462 | {
463 | this.InvokeMapChanged(CollectionChange.ItemRemoved, key);
464 | return true;
465 | }
466 | return false;
467 | }
468 |
469 | public bool Remove(KeyValuePair item)
470 | {
471 | TValue currentValue;
472 | if (this._dictionary.TryGetValue(item.Key, out currentValue) &&
473 | Object.Equals(item.Value, currentValue) && this._dictionary.Remove(item.Key))
474 | {
475 | this.InvokeMapChanged(CollectionChange.ItemRemoved, item.Key);
476 | return true;
477 | }
478 | return false;
479 | }
480 |
481 | public TValue this[TKey key]
482 | {
483 | get
484 | {
485 | return this._dictionary[key];
486 | }
487 | set
488 | {
489 | this._dictionary[key] = value;
490 | this.InvokeMapChanged(CollectionChange.ItemChanged, key);
491 | }
492 | }
493 |
494 | public void Clear()
495 | {
496 | var priorKeys = this._dictionary.Keys.ToArray();
497 | this._dictionary.Clear();
498 | foreach (var key in priorKeys)
499 | {
500 | this.InvokeMapChanged(CollectionChange.ItemRemoved, key);
501 | }
502 | }
503 |
504 | public ICollection Keys
505 | {
506 | get { return this._dictionary.Keys; }
507 | }
508 |
509 | public bool ContainsKey(TKey key)
510 | {
511 | return this._dictionary.ContainsKey(key);
512 | }
513 |
514 | public bool TryGetValue(TKey key, out TValue value)
515 | {
516 | return this._dictionary.TryGetValue(key, out value);
517 | }
518 |
519 | public ICollection Values
520 | {
521 | get { return this._dictionary.Values; }
522 | }
523 |
524 | public bool Contains(KeyValuePair item)
525 | {
526 | return this._dictionary.Contains(item);
527 | }
528 |
529 | public int Count
530 | {
531 | get { return this._dictionary.Count; }
532 | }
533 |
534 | public bool IsReadOnly
535 | {
536 | get { return false; }
537 | }
538 |
539 | public IEnumerator> GetEnumerator()
540 | {
541 | return this._dictionary.GetEnumerator();
542 | }
543 |
544 | System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
545 | {
546 | return this._dictionary.GetEnumerator();
547 | }
548 |
549 | public void CopyTo(KeyValuePair[] array, int arrayIndex)
550 | {
551 | int arraySize = array.Length;
552 | foreach (var pair in this._dictionary)
553 | {
554 | if (arrayIndex >= arraySize) break;
555 | array[arrayIndex++] = pair;
556 | }
557 | }
558 | }
559 | }
560 | }
561 |
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Common/ReadMe.txt:
--------------------------------------------------------------------------------
1 | The Common directory contains classes and XAML styles that simplify application development.
2 |
3 | These are not merely convenient, but are required by most Visual Studio project and item templates.
4 | If you need a variation on one of the styles in StandardStyles it is recommended that you make a
5 | copy in your own resource dictionary. When right-clicking on a styled control in the design
6 | surface the context menu includes an option to Edit a Copy to simplify this process.
7 |
8 | Classes in the Common directory form part of your project and may be further enhanced to meet your
9 | needs. Care should be taken when altering existing methods and properties as incompatible changes
10 | will require corresponding changes to code included in a variety of Visual Studio templates. For
11 | example, additional pages added to your project are written assuming that the original methods and
12 | properties in Common classes are still present and that the names of the types have not changed.
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Common/RichTextColumns.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.Collections.Generic;
22 | using Windows.Foundation;
23 | using Windows.UI.Xaml;
24 | using Windows.UI.Xaml.Controls;
25 |
26 | namespace OneNoteCloudCreatePagesSample.Common
27 | {
28 | ///
29 | /// Wrapper for that creates as many additional overflow
30 | /// columns as needed to fit the available content.
31 | ///
32 | ///
33 | /// The following creates a collection of 400-pixel wide columns spaced 50 pixels apart
34 | /// to contain arbitrary data-bound content:
35 | ///
36 | ///
37 | ///
38 | ///
39 | ///
40 | ///
41 | ///
42 | ///
43 | ///
44 | ///
45 | ///
46 | ///
47 | ///
48 | ///
49 | ///
50 | ///
51 | /// Typically used in a horizontally scrolling region where an unbounded amount of
52 | /// space allows for all needed columns to be created. When used in a vertically scrolling
53 | /// space there will never be any additional columns.
54 | [Windows.UI.Xaml.Markup.ContentProperty(Name = "RichTextContent")]
55 | public sealed class RichTextColumns : Panel
56 | {
57 | ///
58 | /// Identifies the dependency property.
59 | ///
60 | public static readonly DependencyProperty RichTextContentProperty =
61 | DependencyProperty.Register("RichTextContent", typeof(RichTextBlock),
62 | typeof(RichTextColumns), new PropertyMetadata(null, ResetOverflowLayout));
63 |
64 | ///
65 | /// Identifies the dependency property.
66 | ///
67 | public static readonly DependencyProperty ColumnTemplateProperty =
68 | DependencyProperty.Register("ColumnTemplate", typeof(DataTemplate),
69 | typeof(RichTextColumns), new PropertyMetadata(null, ResetOverflowLayout));
70 |
71 | ///
72 | /// Initializes a new instance of the class.
73 | ///
74 | public RichTextColumns()
75 | {
76 | this.HorizontalAlignment = HorizontalAlignment.Left;
77 | }
78 |
79 | ///
80 | /// Gets or sets the initial rich text content to be used as the first column.
81 | ///
82 | public RichTextBlock RichTextContent
83 | {
84 | get { return (RichTextBlock)GetValue(RichTextContentProperty); }
85 | set { SetValue(RichTextContentProperty, value); }
86 | }
87 |
88 | ///
89 | /// Gets or sets the template used to create additional
90 | /// instances.
91 | ///
92 | public DataTemplate ColumnTemplate
93 | {
94 | get { return (DataTemplate)GetValue(ColumnTemplateProperty); }
95 | set { SetValue(ColumnTemplateProperty, value); }
96 | }
97 |
98 | ///
99 | /// Invoked when the content or overflow template is changed to recreate the column layout.
100 | ///
101 | /// Instance of where the change
102 | /// occurred.
103 | /// Event data describing the specific change.
104 | private static void ResetOverflowLayout(DependencyObject d, DependencyPropertyChangedEventArgs e)
105 | {
106 | // When dramatic changes occur, rebuild the column layout from scratch
107 | var target = d as RichTextColumns;
108 | if (target != null)
109 | {
110 | target._overflowColumns = null;
111 | target.Children.Clear();
112 | target.InvalidateMeasure();
113 | }
114 | }
115 |
116 | ///
117 | /// Lists overflow columns already created. Must maintain a 1:1 relationship with
118 | /// instances in the collection following the initial
119 | /// RichTextBlock child.
120 | ///
121 | private List _overflowColumns;
122 |
123 | ///
124 | /// Determines whether additional overflow columns are needed and if existing columns can
125 | /// be removed.
126 | ///
127 | /// The size of the space available, used to constrain the
128 | /// number of additional columns that can be created.
129 | /// The resulting size of the original content plus any extra columns.
130 | protected override Size MeasureOverride(Size availableSize)
131 | {
132 | if (this.RichTextContent == null) return new Size(0, 0);
133 |
134 | // Make sure the RichTextBlock is a child, using the lack of
135 | // a list of additional columns as a sign that this hasn't been
136 | // done yet
137 | if (this._overflowColumns == null)
138 | {
139 | Children.Add(this.RichTextContent);
140 | this._overflowColumns = new List();
141 | }
142 |
143 | // Start by measuring the original RichTextBlock content
144 | this.RichTextContent.Measure(availableSize);
145 | var maxWidth = this.RichTextContent.DesiredSize.Width;
146 | var maxHeight = this.RichTextContent.DesiredSize.Height;
147 | var hasOverflow = this.RichTextContent.HasOverflowContent;
148 |
149 | // Make sure there are enough overflow columns
150 | int overflowIndex = 0;
151 | while (hasOverflow && maxWidth < availableSize.Width && this.ColumnTemplate != null)
152 | {
153 | // Use existing overflow columns until we run out, then create
154 | // more from the supplied template
155 | RichTextBlockOverflow overflow;
156 | if (this._overflowColumns.Count > overflowIndex)
157 | {
158 | overflow = this._overflowColumns[overflowIndex];
159 | }
160 | else
161 | {
162 | overflow = (RichTextBlockOverflow)this.ColumnTemplate.LoadContent();
163 | this._overflowColumns.Add(overflow);
164 | this.Children.Add(overflow);
165 | if (overflowIndex == 0)
166 | {
167 | this.RichTextContent.OverflowContentTarget = overflow;
168 | }
169 | else
170 | {
171 | this._overflowColumns[overflowIndex - 1].OverflowContentTarget = overflow;
172 | }
173 | }
174 |
175 | // Measure the new column and prepare to repeat as necessary
176 | overflow.Measure(new Size(availableSize.Width - maxWidth, availableSize.Height));
177 | maxWidth += overflow.DesiredSize.Width;
178 | maxHeight = Math.Max(maxHeight, overflow.DesiredSize.Height);
179 | hasOverflow = overflow.HasOverflowContent;
180 | overflowIndex++;
181 | }
182 |
183 | // Disconnect extra columns from the overflow chain, remove them from our private list
184 | // of columns, and remove them as children
185 | if (this._overflowColumns.Count > overflowIndex)
186 | {
187 | if (overflowIndex == 0)
188 | {
189 | this.RichTextContent.OverflowContentTarget = null;
190 | }
191 | else
192 | {
193 | this._overflowColumns[overflowIndex - 1].OverflowContentTarget = null;
194 | }
195 | while (this._overflowColumns.Count > overflowIndex)
196 | {
197 | this._overflowColumns.RemoveAt(overflowIndex);
198 | this.Children.RemoveAt(overflowIndex + 1);
199 | }
200 | }
201 |
202 | // Report final determined size
203 | return new Size(maxWidth, maxHeight);
204 | }
205 |
206 | ///
207 | /// Arranges the original content and all extra columns.
208 | ///
209 | /// Defines the size of the area the children must be arranged
210 | /// within.
211 | /// The size of the area the children actually required.
212 | protected override Size ArrangeOverride(Size finalSize)
213 | {
214 | double maxWidth = 0;
215 | double maxHeight = 0;
216 | foreach (var child in Children)
217 | {
218 | child.Arrange(new Rect(maxWidth, 0, child.DesiredSize.Width, finalSize.Height));
219 | maxWidth += child.DesiredSize.Width;
220 | maxHeight = Math.Max(maxHeight, child.DesiredSize.Height);
221 | }
222 | return new Size(maxWidth, maxHeight);
223 | }
224 | }
225 | }
226 |
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Common/SettingsFlyout.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 OneNoteCloudCreatePagesSample.Common
21 | {
22 | using System;
23 | using System.Windows.Input;
24 | using Windows.UI.ApplicationSettings;
25 | using Windows.UI.Xaml;
26 | using Windows.UI.Xaml.Controls;
27 | using Windows.UI.Xaml.Markup;
28 | using Windows.UI.Xaml.Media.Animation;
29 |
30 | ///
31 | /// Base class for a settings flyout. Note there is a built-in SettingsFlyout class in Windows 8.1
32 | ///
33 | [ContentProperty(Name = "Content")]
34 | public abstract class SettingsFlyout : ContentControl
35 | {
36 | public static readonly DependencyProperty IsOpenProperty =
37 | DependencyProperty.Register("IsOpen", typeof(bool), typeof(SettingsFlyout), new PropertyMetadata(null));
38 | public static readonly DependencyProperty HeaderTextProperty =
39 | DependencyProperty.Register("HeaderText", typeof(string), typeof(SettingsFlyout), new PropertyMetadata(null));
40 | public static readonly DependencyProperty BackCommandProperty =
41 | DependencyProperty.Register("BackCommand", typeof(ICommand), typeof(SettingsFlyout), new PropertyMetadata(null));
42 | public static readonly DependencyProperty MainContentTransitionsProperty =
43 | DependencyProperty.Register("MainContentTransitions", typeof(TransitionCollection), typeof(SettingsFlyout), new PropertyMetadata(null));
44 |
45 | private const int ContentAnimationOffset = 100; // UX guidelines
46 | private const int WideWidth = 646; // UX guidelines (wide is 646 and narrow is 346)
47 |
48 | ///
49 | /// Initializes a new instance of the class.
50 | ///
51 | protected SettingsFlyout()
52 | {
53 | Width = WideWidth;
54 | DefaultStyleKey = typeof(SettingsFlyout);
55 | BackCommand = new Command(HandleBackCommand);
56 | MainContentTransitions = new TransitionCollection
57 | {
58 | new EntranceThemeTransition
59 | {
60 | // The settings window may be invoked from the left side of the screen
61 | // if the system's text direction is right-to-left
62 | FromHorizontalOffset = SettingsPane.Edge == SettingsEdgeLocation.Right
63 | ? ContentAnimationOffset
64 | : -ContentAnimationOffset,
65 | },
66 | };
67 |
68 | SizeChanged += HandleSizeChanged;
69 | Position();
70 | }
71 |
72 | ///
73 | /// Gets the back command.
74 | ///
75 | ///
76 | /// The back command.
77 | ///
78 | public ICommand BackCommand
79 | {
80 | get { return (ICommand)GetValue(BackCommandProperty); }
81 | private set { SetValue(BackCommandProperty, value); }
82 | }
83 |
84 | ///
85 | /// Gets or sets a value that indicates whether the is visible.
86 | ///
87 | ///
88 | /// true if the is visible; otherwise, false. The default is false.
89 | ///
90 | public bool IsOpen
91 | {
92 | get { return (bool)GetValue(IsOpenProperty); }
93 | set
94 | {
95 | // Light-dismissal leaves IsOpen = true, which means we can't reopen the popup; we need to reset IsOpen first
96 | SetValue(IsOpenProperty, false);
97 | SetValue(IsOpenProperty, value);
98 | }
99 | }
100 |
101 | ///
102 | /// Gets or sets the header text.
103 | ///
104 | ///
105 | /// The header text.
106 | ///
107 | public string HeaderText
108 | {
109 | get { return (string)GetValue(HeaderTextProperty); }
110 | set { SetValue(HeaderTextProperty, value); }
111 | }
112 |
113 | ///
114 | /// Gets or sets the collection of style elements that apply to the main content of a .
115 | ///
116 | /// The strongly typed collection of style elements.
117 | ///
118 | /// This property is different than the inherited ContentTransitions;
119 | /// since it only applies to the main content and not the header of the flyout.
120 | ///
121 | public TransitionCollection MainContentTransitions
122 | {
123 | get { return (TransitionCollection)GetValue(MainContentTransitionsProperty); }
124 | set { SetValue(MainContentTransitionsProperty, value); }
125 | }
126 |
127 | ///
128 | /// Opens this .
129 | ///
130 | internal void Open()
131 | {
132 | this.OnOpening();
133 | Position();
134 | IsOpen = true;
135 | }
136 |
137 | ///
138 | /// Override point for derived classes to add their logic before the pane is shown.
139 | ///
140 | protected virtual void OnOpening()
141 | {
142 |
143 | }
144 |
145 | ///
146 | /// Positions this .
147 | ///
148 | private void Position()
149 | {
150 | // The settings window may be invoked from the left side of the screen
151 | // if the system's text direction is right-to-left
152 | double left = SettingsPane.Edge == SettingsEdgeLocation.Right
153 | ? Window.Current.Bounds.Width - WideWidth
154 | : 0;
155 |
156 | this.Margin = new Thickness(left, top: 0, right: 0, bottom: 0);
157 | this.Height = Window.Current.Bounds.Height;
158 | }
159 |
160 | ///
161 | /// Handles the event of the control.
162 | ///
163 | /// The source of the event.
164 | /// The instance containing the event data.
165 | private void HandleSizeChanged(object sender, SizeChangedEventArgs e)
166 | {
167 | Height = e.NewSize.Height;
168 | }
169 |
170 | ///
171 | /// Handles the back command.
172 | ///
173 | private void HandleBackCommand()
174 | {
175 | IsOpen = false;
176 | SettingsPane.Show();
177 | }
178 |
179 | ///
180 | /// Represents a settings flyout command.
181 | ///
182 | private class Command : ICommand
183 | {
184 | ///
185 | /// Occurs when changes occur that affect whether the command should execute.
186 | ///
187 | public event EventHandler CanExecuteChanged;
188 |
189 | protected virtual void OnCanExecuteChanged()
190 | {
191 | EventHandler handler = CanExecuteChanged;
192 | if (handler != null) handler(this, EventArgs.Empty);
193 | }
194 |
195 | private readonly Action _action;
196 |
197 | ///
198 | /// Initializes a new instance of the class.
199 | ///
200 | /// The action to execute when the command is issued.
201 | public Command(Action action)
202 | {
203 | _action = action;
204 | }
205 |
206 | ///
207 | /// Defines the method that determines whether the command can execute in its current state.
208 | ///
209 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
210 | ///
211 | /// true if this command can be executed; otherwise, false.
212 | ///
213 | ///
214 | public bool CanExecute(object parameter)
215 | {
216 | return true;
217 | }
218 |
219 | ///
220 | /// Defines the method to be called when the command is invoked.
221 | ///
222 | /// Data used by the command. If the command does not require data to be passed, this object can be set to null.
223 | ///
224 | public void Execute(object parameter)
225 | {
226 | _action();
227 | }
228 | }
229 | }
230 | }
231 |
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/Common/SuspensionManager.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.Collections.Generic;
22 | using System.IO;
23 | using System.Runtime.Serialization;
24 | using System.Threading.Tasks;
25 | using Windows.Storage;
26 | using Windows.Storage.Streams;
27 | using Windows.UI.Xaml;
28 | using Windows.UI.Xaml.Controls;
29 |
30 | namespace OneNoteCloudCreatePagesSample.Common
31 | {
32 | ///
33 | /// SuspensionManager captures global session state to simplify process lifetime management
34 | /// for an application. Note that session state will be automatically cleared under a variety
35 | /// of conditions and should only be used to store information that would be convenient to
36 | /// carry across sessions, but that should be discarded when an application crashes or is
37 | /// upgraded.
38 | ///
39 | internal sealed class SuspensionManager
40 | {
41 | private static Dictionary _sessionState = new Dictionary();
42 | // ReSharper disable InconsistentNaming
43 | private static readonly List _knownTypes = new List();
44 | // ReSharper restore InconsistentNaming
45 | private const string SessionStateFilename = "_sessionState.xml";
46 |
47 | ///
48 | /// Provides access to global session state for the current session. This state is
49 | /// serialized by and restored by
50 | /// , so values must be serializable by
51 | /// and should be as compact as possible. Strings
52 | /// and other self-contained data types are strongly recommended.
53 | ///
54 | public static Dictionary SessionState
55 | {
56 | get { return _sessionState; }
57 | }
58 |
59 | ///
60 | /// List of custom types provided to the when
61 | /// reading and writing session state. Initially empty, additional types may be
62 | /// added to customize the serialization process.
63 | ///
64 | public static List KnownTypes
65 | {
66 | get { return _knownTypes; }
67 | }
68 |
69 | ///
70 | /// Save the current . Any instances
71 | /// registered with will also preserve their current
72 | /// navigation stack, which in turn gives their active an opportunity
73 | /// to save its state.
74 | ///
75 | /// An asynchronous task that reflects when session state has been saved.
76 | public static async Task SaveAsync()
77 | {
78 | try
79 | {
80 | // Save the navigation state for all registered frames
81 | foreach (var weakFrameReference in RegisteredFrames)
82 | {
83 | Frame frame;
84 | if (weakFrameReference.TryGetTarget(out frame))
85 | {
86 | SaveFrameNavigationState(frame);
87 | }
88 | }
89 |
90 | // Serialize the session state synchronously to avoid asynchronous access to shared
91 | // state
92 | var sessionData = new MemoryStream();
93 | var serializer = new DataContractSerializer(typeof(Dictionary), _knownTypes);
94 | serializer.WriteObject(sessionData, _sessionState);
95 |
96 | // Get an output stream for the SessionState file and write the state asynchronously
97 | StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(SessionStateFilename, CreationCollisionOption.ReplaceExisting);
98 | using (Stream fileStream = await file.OpenStreamForWriteAsync())
99 | {
100 | sessionData.Seek(0, SeekOrigin.Begin);
101 | await sessionData.CopyToAsync(fileStream);
102 | await fileStream.FlushAsync();
103 | }
104 | }
105 | catch (Exception e)
106 | {
107 | throw new SuspensionManagerException(e);
108 | }
109 | }
110 |
111 | ///
112 | /// Restores previously saved . Any instances
113 | /// registered with will also restore their prior navigation
114 | /// state, which in turn gives their active an opportunity restore its
115 | /// state.
116 | ///
117 | /// An asynchronous task that reflects when session state has been read. The
118 | /// content of should not be relied upon until this task
119 | /// completes.
120 | public static async Task RestoreAsync()
121 | {
122 | _sessionState = new Dictionary();
123 |
124 | try
125 | {
126 | // Get the input stream for the SessionState file
127 | StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(SessionStateFilename);
128 | using (IInputStream inStream = await file.OpenSequentialReadAsync())
129 | {
130 | // Deserialize the Session State
131 | var serializer = new DataContractSerializer(typeof(Dictionary), _knownTypes);
132 | _sessionState = (Dictionary)serializer.ReadObject(inStream.AsStreamForRead());
133 | }
134 |
135 | // Restore any registered frames to their saved state
136 | foreach (var weakFrameReference in RegisteredFrames)
137 | {
138 | Frame frame;
139 | if (weakFrameReference.TryGetTarget(out frame))
140 | {
141 | frame.ClearValue(FrameSessionStateProperty);
142 | RestoreFrameNavigationState(frame);
143 | }
144 | }
145 | }
146 | catch (Exception e)
147 | {
148 | throw new SuspensionManagerException(e);
149 | }
150 | }
151 |
152 | private static readonly DependencyProperty FrameSessionStateKeyProperty =
153 | DependencyProperty.RegisterAttached("_FrameSessionStateKey", typeof(String), typeof(SuspensionManager), null);
154 | private static readonly DependencyProperty FrameSessionStateProperty =
155 | DependencyProperty.RegisterAttached("_FrameSessionState", typeof(Dictionary), typeof(SuspensionManager), null);
156 | private static readonly List> RegisteredFrames = new List>();
157 |
158 | ///
159 | /// Registers a instance to allow its navigation history to be saved to
160 | /// and restored from . Frames should be registered once
161 | /// immediately after creation if they will participate in session state management. Upon
162 | /// registration if state has already been restored for the specified key
163 | /// the navigation history will immediately be restored. Subsequent invocations of
164 | /// will also restore navigation history.
165 | ///
166 | /// An instance whose navigation history should be managed by
167 | ///
168 | /// A unique key into used to
169 | /// store navigation-related information.
170 | public static void RegisterFrame(Frame frame, String sessionStateKey)
171 | {
172 | if (frame.GetValue(FrameSessionStateKeyProperty) != null)
173 | {
174 | throw new InvalidOperationException("Frames can only be registered to one session state key");
175 | }
176 |
177 | if (frame.GetValue(FrameSessionStateProperty) != null)
178 | {
179 | throw new InvalidOperationException("Frames must be either be registered before accessing frame session state, or not registered at all");
180 | }
181 |
182 | // Use a dependency property to associate the session key with a frame, and keep a list of frames whose
183 | // navigation state should be managed
184 | frame.SetValue(FrameSessionStateKeyProperty, sessionStateKey);
185 | RegisteredFrames.Add(new WeakReference(frame));
186 |
187 | // Check to see if navigation state can be restored
188 | RestoreFrameNavigationState(frame);
189 | }
190 |
191 | ///
192 | /// Disassociates a previously registered by
193 | /// from . Any navigation state previously captured will be
194 | /// removed.
195 | ///
196 | /// An instance whose navigation history should no longer be
197 | /// managed.
198 | public static void UnregisterFrame(Frame frame)
199 | {
200 | // Remove session state and remove the frame from the list of frames whose navigation
201 | // state will be saved (along with any weak references that are no longer reachable)
202 | SessionState.Remove((String)frame.GetValue(FrameSessionStateKeyProperty));
203 | RegisteredFrames.RemoveAll(weakFrameReference =>
204 | {
205 | Frame testFrame;
206 | return !weakFrameReference.TryGetTarget(out testFrame) || testFrame == frame;
207 | });
208 | }
209 |
210 | ///
211 | /// Provides storage for session state associated with the specified .
212 | /// Frames that have been previously registered with have
213 | /// their session state saved and restored automatically as a part of the global
214 | /// . Frames that are not registered have transient state
215 | /// that can still be useful when restoring pages that have been discarded from the
216 | /// navigation cache.
217 | ///
218 | /// Apps may choose to rely on to manage
219 | /// page-specific state instead of working with frame session state directly.
220 | /// The instance for which session state is desired.
221 | /// A collection of state subject to the same serialization mechanism as
222 | /// .
223 | public static Dictionary SessionStateForFrame(Frame frame)
224 | {
225 | var frameState = (Dictionary)frame.GetValue(FrameSessionStateProperty);
226 |
227 | if (frameState == null)
228 | {
229 | var frameSessionKey = (String)frame.GetValue(FrameSessionStateKeyProperty);
230 | if (frameSessionKey != null)
231 | {
232 | // Registered frames reflect the corresponding session state
233 | if (!_sessionState.ContainsKey(frameSessionKey))
234 | {
235 | _sessionState[frameSessionKey] = new Dictionary();
236 | }
237 | frameState = (Dictionary)_sessionState[frameSessionKey];
238 | }
239 | else
240 | {
241 | // Frames that aren't registered have transient state
242 | frameState = new Dictionary();
243 | }
244 | frame.SetValue(FrameSessionStateProperty, frameState);
245 | }
246 | return frameState;
247 | }
248 |
249 | private static void RestoreFrameNavigationState(Frame frame)
250 | {
251 | var frameState = SessionStateForFrame(frame);
252 | if (frameState.ContainsKey("Navigation"))
253 | {
254 | frame.SetNavigationState((String)frameState["Navigation"]);
255 | }
256 | }
257 |
258 | private static void SaveFrameNavigationState(Frame frame)
259 | {
260 | var frameState = SessionStateForFrame(frame);
261 | frameState["Navigation"] = frame.GetNavigationState();
262 | }
263 | }
264 | public class SuspensionManagerException : Exception
265 | {
266 | public SuspensionManagerException()
267 | {
268 | }
269 |
270 | public SuspensionManagerException(Exception e) : base("SuspensionManager failed", e)
271 | {
272 |
273 | }
274 | }
275 | }
276 |
--------------------------------------------------------------------------------
/OneNoteCloudCreatePagesSample/CreateExamples.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.IO;
21 | using Microsoft.Live;
22 | using Newtonsoft.Json;
23 | using System;
24 | using System.Collections.Generic;
25 | using System.Diagnostics;
26 | using System.Linq;
27 | using System.Net;
28 | using System.Net.Http;
29 | using System.Net.Http.Headers;
30 | using System.Threading.Tasks;
31 | using Windows.ApplicationModel;
32 |
33 | namespace OneNoteCloudCreatePagesSample
34 | {
35 | ///
36 | /// Class to show a selection of examples of creating posts via the OneNote Cloud API
37 | ///
38 | public class CreateExamples
39 | {
40 | private static readonly string PagesEndPoint = "https://www.onenote.com/api/v1.0/pages";
41 |
42 | private string SectionName = "Quick Notes";
43 |
44 | private string DEFAULT_SECTION_NAME = "Quick Notes";
45 |
46 | ///
47 | /// Client to do OAUTH against Microsoft Live Connect service
48 | ///
49 | private readonly LiveAuthClient _authClient;
50 |
51 | public CreateExamples(LiveAuthClient authClient)
52 | {
53 | _authClient = authClient;
54 | }
55 |
56 | public Uri GetPagesEndpoint(string specifiedSectionName)
57 | {
58 | string sectionNameToUse;
59 | if(specifiedSectionName != null)
60 | {
61 | sectionNameToUse = specifiedSectionName;
62 | }
63 | else
64 | {
65 | sectionNameToUse = DEFAULT_SECTION_NAME;
66 | }
67 | return new Uri(PagesEndPoint + "/?sectionName=" + sectionNameToUse);
68 | }
69 |
70 | ///
71 | /// Does the object currently have a valid authenticated state
72 | ///
73 | public bool IsAuthenticated
74 | {
75 | get { return _authClient.Session != null && !string.IsNullOrEmpty(_authClient.Session.AccessToken); }
76 | }
77 |
78 | ///
79 | /// Create a very simple page with some formatted text.
80 | ///
81 | /// Run the code under the debugger
82 | async public Task CreateSimplePage(bool debug, string sectionName)
83 | {
84 | if (debug)
85 | {
86 | Debugger.Launch();
87 | Debugger.Break();
88 | }
89 |
90 | var client = new HttpClient();
91 |
92 | // Note: API only supports JSON return type.
93 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
94 |
95 | // This allows you to see what happens when an unauthenticated call is made.
96 | if (IsAuthenticated)
97 | {
98 | client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _authClient.Session.AccessToken);
99 | }
100 |
101 | string date = GetDate();
102 | string simpleHtml = "" +
103 | "" +
104 | "A simple page created from basic HTML-formatted text on Windows 8" +
105 | "" +
106 | "" +
107 | "" +
108 | "
This is a page that just contains some simple formattedtext
" +
110 | "" +
111 | "";
112 |
113 | var createMessage = new HttpRequestMessage(HttpMethod.Post, GetPagesEndpoint(sectionName))
114 | {
115 | Content = new StringContent(simpleHtml, System.Text.Encoding.UTF8, "text/html")
116 | };
117 |
118 | HttpResponseMessage response = await client.SendAsync(createMessage);
119 |
120 | return await TranslateResponse(response);
121 | }
122 |
123 | ///
124 | /// Create a page with an image on it.
125 | ///
126 | /// Run the code under the debugger
127 | async public Task CreatePageWithImage(bool debug, string sectionName)
128 | {
129 | if (debug)
130 | {
131 | Debugger.Launch();
132 | Debugger.Break();
133 | }
134 |
135 | var client = new HttpClient();
136 |
137 | // Note: API only supports JSON return type.
138 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
139 |
140 | // This allows you to see what happens when an unauthenticated call is made.
141 | if (IsAuthenticated)
142 | {
143 | client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _authClient.Session.AccessToken);
144 | }
145 |
146 | const string imagePartName = "image1";
147 | string date = GetDate();
148 | string simpleHtml = "" +
149 | "" +
150 | "A simple page created with an image on it" +
151 | "" +
152 | "" +
153 | "" +
154 | "
This is a page with an image on it
" +
155 | "" +
156 | "" +
157 | "";
158 |
159 | // Create the image part - make sure it is disposed after we've sent the message in order to close the stream.
160 | HttpResponseMessage response;
161 | using (var imageContent = new StreamContent(await GetBinaryStream("assets\\Logo.jpg")))
162 | {
163 | imageContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
164 | HttpRequestMessage createMessage = new HttpRequestMessage(HttpMethod.Post, GetPagesEndpoint(sectionName))
165 | {
166 | Content = new MultipartFormDataContent
167 | {
168 | {new StringContent(simpleHtml, System.Text.Encoding.UTF8, "text/html"), "Presentation"},
169 | {imageContent, imagePartName}
170 | }
171 | };
172 |
173 |
174 | // Must send the request within the using block, or the image stream will have been disposed.
175 | response = await client.SendAsync(createMessage);
176 | }
177 |
178 | return await TranslateResponse(response);
179 | }
180 |
181 | ///
182 | /// Create a page with a PDF document attached and rendered
183 | ///
184 | /// Determines whether to execute this method under the debugger
185 | /// The converted HTTP response message
186 | async public Task CreatePageWithPDFAttachedAndRendered(bool debug, string sectionName)
187 | {
188 | if(debug)
189 | {
190 | Debugger.Launch();
191 | Debugger.Break();
192 | }
193 |
194 | var client = new HttpClient();
195 | string date = GetDate();
196 | //Note: API only supports JSON return type
197 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
198 |
199 | // This allows you to see what happens when an unauthenticated call is made.
200 | if (IsAuthenticated)
201 | {
202 | client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _authClient.Session.AccessToken);
203 | }
204 | const string attachmentPartName = "pdfattachment1";
205 | string attachmentRequestHtml = "" +
206 | "" +
207 | "A page created with a PDF document attached and rendered" +
208 | "" +
209 | "" +
210 | "" +
211 | "
This is a page with a PDF file attachment
" +
212 | "" +
213 | "
Here's the content of the PDF document :
" +
214 | "" +
215 | "" +
216 | "";
217 | HttpResponseMessage response;
218 | using (var attachmentContent = new StreamContent(await GetBinaryStream("assets\\attachment.pdf")))
219 | {
220 | attachmentContent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
221 | HttpRequestMessage createMessage = new HttpRequestMessage(HttpMethod.Post, GetPagesEndpoint(sectionName))
222 | {
223 | Content = new MultipartFormDataContent
224 | {
225 | {new StringContent(attachmentRequestHtml, System.Text.Encoding.UTF8, "text/html"), "Presentation"},
226 | {attachmentContent, attachmentPartName}
227 | }
228 | };
229 | // Must send the request within the using block, or the binary stream will have been disposed.
230 | response = await client.SendAsync(createMessage);
231 | }
232 | return await TranslateResponse(response);
233 | }
234 |
235 | ///
236 | /// Create a page with an image of an embedded webpage on it.
237 | ///
238 | /// Run the code under the debugger
239 | async public Task CreatePageWithEmbeddedWebPage(bool debug, string sectionName)
240 | {
241 | if (debug)
242 | {
243 | Debugger.Launch();
244 | Debugger.Break();
245 | }
246 |
247 | var client = new HttpClient();
248 |
249 | // Note: API only supports JSON return type.
250 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
251 |
252 | // This allows you to see what happens when an unauthenticated call is made.
253 | if (IsAuthenticated)
254 | {
255 | client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _authClient.Session.AccessToken);
256 | }
257 | const string embeddedPartName = "embedded1";
258 | const string embeddedWebPage =
259 | "" +
260 | "" +
261 | "An embedded webpage" +
262 | "" +
263 | "" +
264 | "
This is a screen grab of a web page
" +
265 | "
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vehicula magna quis mauris accumsan, nec imperdiet nisi tempus. Suspendisse potenti. " +
266 | "Duis vel nulla sit amet turpis venenatis elementum. Cras laoreet quis nisi et sagittis. Donec euismod at tortor ut porta. Duis libero urna, viverra id " +
267 | "aliquam in, ornare sed orci. Pellentesque condimentum gravida felis, sed pulvinar erat suscipit sit amet. Nulla id felis quis sem blandit dapibus. Ut " +
268 | "viverra auctor nisi ac egestas. Quisque ac neque nec velit fringilla sagittis porttitor sit amet quam.
" +
269 | "" +
270 | "";
271 |
272 | string date = GetDate();
273 |
274 | string simpleHtml = "" +
275 | "" +
276 | "A page created with an image of an html page on it" +
277 | "" +
278 | "" +
279 | "" +
280 | "
This is a page with an image of an html page on it.
" +
281 | "" +
282 | "" +
283 | "";
284 |
285 | var createMessage = new HttpRequestMessage(HttpMethod.Post, GetPagesEndpoint(sectionName))
286 | {
287 | Content = new MultipartFormDataContent
288 | {
289 | {new StringContent(simpleHtml, System.Text.Encoding.UTF8, "text/html"), "Presentation"},
290 | {new StringContent(embeddedWebPage, System.Text.Encoding.UTF8, "text/html"), embeddedPartName}
291 | }
292 | };
293 |
294 | HttpResponseMessage response = await client.SendAsync(createMessage);
295 |
296 | return await TranslateResponse(response);
297 | }
298 |
299 | ///
300 | /// Create a page with an image of a URL on it.
301 | ///
302 | /// Run the code under the debugger
303 | async public Task CreatePageWithUrl(bool debug, string sectionName)
304 | {
305 | if (debug)
306 | {
307 | Debugger.Launch();
308 | Debugger.Break();
309 | }
310 |
311 | var client = new HttpClient();
312 |
313 | // Note: API only supports JSON return type.
314 | client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
315 |
316 | // This allows you to see what happens when an unauthenticated call is made.
317 | if (IsAuthenticated)
318 | {
319 | client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _authClient.Session.AccessToken);
320 | }
321 |
322 | string date = GetDate();
323 | string simpleHtml = @"" +
324 | "" +
325 | "A page created with an image from a URL on it" +
326 | "" +
327 | "" +
328 | "" +
329 | "
This is a page with an image of an html page rendered from a URL on it.