diff --git a/Samples/ApplicationData/README.md b/Samples/ApplicationData/README.md index 5b6b5f3069..6cd6b5e36d 100644 --- a/Samples/ApplicationData/README.md +++ b/Samples/ApplicationData/README.md @@ -2,7 +2,8 @@ page_type: sample languages: - csharp -- vb +- cpp +- cppwinrt products: - windows - windows-uwp @@ -37,41 +38,41 @@ Shows how to store and retrieve data that is specific to each user and app by us Application data includes session state, user preferences, and other settings. It is created, read, updated, and deleted when the app is running. The operating system manages these data stores for your app: - local: Data that exists on the current device and is backed up in the cloud -- roaming: Data that exists on all devices on which the user has installed the app - temporary: Data that could be removed by the system any time the app isn't running - localcache: Persistent data that exists only on the current device -If you use roaming data in your app, your users can easily keep your app's application data in sync across multiple devices. The operating system replicates roaming data to the cloud when it is updated, and synchronizes the data to any other devices on which the app is installed, reducing the amount of setup work that the user needs to do to install your app on multiple devices. - If you use local data in your app, your users can back up application data in the cloud. This application data can then be restored back on any other device while setting up the device with the same account. +The system also manages a roaming data store, +but the data no longer roams starting in Windows 11. + The sample covers these key tasks: - Reading and writing settings to an app data store - Reading and writing files to an app data store -- Responding to roaming events - -## Guidelines -[Guidelines for roaming application data](http://msdn.microsoft.com/library/windows/apps/hh465094) +## Related topics -## Concepts +### Concepts [Store and retrieve settings and other app data](https://msdn.microsoft.com/library/windows/apps/mt299098) -## Reference +### Related samples + +* [ApplicationData sample](/archived/ApplicationData/) for Visual Basic (archived) + +### Reference [Windows.Storage.ApplicationData](http://msdn.microsoft.com/library/windows/apps/br241587) [Windows.Storage.ApplicationDataCompositeValue](http://msdn.microsoft.com/library/windows/apps/br241588) [Windows.Storage.ApplicationDataContainer](http://msdn.microsoft.com/library/windows/apps/br241599) [Windows.Storage.ApplicationDataContainerSettings](http://msdn.microsoft.com/library/windows/apps/br241600) -[WinJS.Application](http://msdn.microsoft.com/library/windows/apps/br229774) ## System requirements **Client:** Windows 10 -**Server:** Windows Server 2016 Technical Preview +**Server:** Windows Server 2016 **Phone:** Windows 10 diff --git a/Samples/ApplicationData/cppwinrt/ApplicationData.sln b/Samples/ApplicationData/cppwinrt/ApplicationData.sln new file mode 100644 index 0000000000..3bb3abc95e --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/ApplicationData.sln @@ -0,0 +1,43 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.31424.327 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ApplicationData", "ApplicationData.vcxproj", "{83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|ARM = Debug|ARM + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|ARM = Release|ARM + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Debug|ARM.ActiveCfg = Debug|ARM + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Debug|ARM.Build.0 = Debug|ARM + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Debug|ARM.Deploy.0 = Debug|ARM + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Debug|x64.ActiveCfg = Debug|x64 + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Debug|x64.Build.0 = Debug|x64 + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Debug|x64.Deploy.0 = Debug|x64 + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Debug|x86.ActiveCfg = Debug|Win32 + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Debug|x86.Build.0 = Debug|Win32 + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Debug|x86.Deploy.0 = Debug|Win32 + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Release|ARM.ActiveCfg = Release|ARM + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Release|ARM.Build.0 = Release|ARM + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Release|ARM.Deploy.0 = Release|ARM + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Release|x64.ActiveCfg = Release|x64 + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Release|x64.Build.0 = Release|x64 + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Release|x64.Deploy.0 = Release|x64 + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Release|x86.ActiveCfg = Release|Win32 + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Release|x86.Build.0 = Release|Win32 + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5}.Release|x86.Deploy.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {391ED8DE-38FA-49C2-A23C-4D0CE73F0017} + EndGlobalSection +EndGlobal diff --git a/Samples/ApplicationData/cppwinrt/ApplicationData.vcxproj b/Samples/ApplicationData/cppwinrt/ApplicationData.vcxproj new file mode 100644 index 0000000000..3d4f729b4d --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/ApplicationData.vcxproj @@ -0,0 +1,253 @@ + + + + + $([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), LICENSE))\SharedContent + + + true + {83665FC5-1A28-4FF1-A403-2A7ACBA3E6A5} + ApplicationData + SDKTemplate + en-US + 15.0 + true + Windows Store + 10.0 + 10.0.22000.0 + $(WindowsTargetPlatformVersion) + + + + + Debug + ARM + + + Debug + Win32 + + + Debug + x64 + + + Release + ARM + + + Release + Win32 + + + Release + x64 + + + + Application + v142 + Unicode + + + true + true + + + false + true + false + + + + + + + + $(VC_IncludePath);$(UniversalCRT_IncludePath);$(WindowsSDK_IncludePath);$(SharedContentDir)\cppwinrt + true + + + + Use + pch.h + $(IntDir)pch.pch + Level4 + %(AdditionalOptions) /bigobj + 4453;28204 + + + + + _DEBUG;%(PreprocessorDefinitions) + + + WindowsApp.lib;onecoreuap.lib;%(AdditionalDependencies) + + + WindowsApp.lib;onecoreuap.lib;%(AdditionalDependencies) + + + WindowsApp.lib;onecoreuap.lib;%(AdditionalDependencies) + + + + + NDEBUG;%(PreprocessorDefinitions) + + + WindowsApp.lib;onecoreuap.lib;%(AdditionalDependencies) + + + WindowsApp.lib;onecoreuap.lib;%(AdditionalDependencies) + + + WindowsApp.lib;onecoreuap.lib;%(AdditionalDependencies) + + + + + $(SharedContentDir)\xaml\App.xaml + + + $(SharedContentDir)\xaml\MainPage.xaml + + + + ..\shared\Scenario1_Files.xaml + + + ..\shared\Scenario2_Settings.xaml + + + ..\shared\Scenario3_SettingContainer.xaml + + + ..\shared\Scenario4_CompositeSettings.xaml + + + ..\shared\Scenario5_Msappdata.xaml + + + ..\shared\Scenario6_ClearScenario.xaml + + + ..\shared\Scenario7_SetVersion.xaml + + + + + + Designer + + + Designer + + + + + + + + + + Styles\Styles.xaml + + + + + $(SharedContentDir)\xaml\App.xaml + + + $(SharedContentDir)\xaml\MainPage.xaml + + + SampleConfiguration.h + + + ..\shared\Scenario1_Files.xaml + + + ..\shared\Scenario2_Settings.xaml + + + ..\shared\Scenario3_SettingContainer.xaml + + + ..\shared\Scenario4_CompositeSettings.xaml + + + ..\shared\Scenario5_Msappdata.xaml + + + ..\shared\Scenario6_ClearScenario.xaml + + + ..\shared\Scenario7_SetVersion.xaml + + + Create + pch.h + + + Project.idl + + + + + $(SharedContentDir)\xaml\MainPage.xaml + + + + + + Designer + + + + + Assets\microsoft-sdk.png + + + Assets\smallTile-sdk.png + + + Assets\splash-sdk.png + + + Assets\squareTile-sdk.png + + + Assets\storeLogo-sdk.png + + + Assets\tile-sdk.png + + + Assets\windows-sdk.png + + + Assets\appDataLocal.png + + + Assets\appDataRoaming.png + + + Assets\appDataTemp.png + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + \ No newline at end of file diff --git a/Samples/ApplicationData/cppwinrt/ApplicationData.vcxproj.filters b/Samples/ApplicationData/cppwinrt/ApplicationData.vcxproj.filters new file mode 100644 index 0000000000..e79512ca25 --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/ApplicationData.vcxproj.filters @@ -0,0 +1,78 @@ + + + + + 4416d50a-7676-4d0a-9b2c-91ff70c6047f + bmp;fbx;gif;jpg;jpeg;tga;tiff;tif;png + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Assets + + + Assets + + + Assets + + + Assets + + + Assets + + + Assets + + + Assets + + + Assets + + + Assets + + + Assets + + + + + + + + + \ No newline at end of file diff --git a/Samples/ApplicationData/cppwinrt/Package.appxmanifest b/Samples/ApplicationData/cppwinrt/Package.appxmanifest new file mode 100644 index 0000000000..185d8fef63 --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Package.appxmanifest @@ -0,0 +1,42 @@ + + + + + + ApplicationData C++/WinRT Sample + Microsoft Corporation + Assets\storelogo-sdk.png + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Samples/ApplicationData/cppwinrt/Project.idl b/Samples/ApplicationData/cppwinrt/Project.idl new file mode 100644 index 0000000000..08be53dfbd --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Project.idl @@ -0,0 +1,45 @@ +namespace SDKTemplate +{ + + [default_interface] + runtimeclass Scenario1_Files : Windows.UI.Xaml.Controls.Page + { + Scenario1_Files(); + } + + [default_interface] + runtimeclass Scenario2_Settings : Windows.UI.Xaml.Controls.Page + { + Scenario2_Settings(); + } + + [default_interface] + runtimeclass Scenario3_SettingContainer : Windows.UI.Xaml.Controls.Page + { + Scenario3_SettingContainer(); + } + + [default_interface] + runtimeclass Scenario4_CompositeSettings : Windows.UI.Xaml.Controls.Page + { + Scenario4_CompositeSettings(); + } + + [default_interface] + runtimeclass Scenario5_Msappdata : Windows.UI.Xaml.Controls.Page + { + Scenario5_Msappdata(); + } + + [default_interface] + runtimeclass Scenario6_ClearScenario : Windows.UI.Xaml.Controls.Page + { + Scenario6_ClearScenario(); + } + + [default_interface] + runtimeclass Scenario7_SetVersion : Windows.UI.Xaml.Controls.Page + { + Scenario7_SetVersion(); + } +} \ No newline at end of file diff --git a/Samples/ApplicationData/cppwinrt/SampleConfiguration.cpp b/Samples/ApplicationData/cppwinrt/SampleConfiguration.cpp new file mode 100644 index 0000000000..e1c0c0cedb --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/SampleConfiguration.cpp @@ -0,0 +1,35 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include +#include "MainPage.h" +#include "SampleConfiguration.h" + +using namespace winrt; +using namespace Windows::Foundation::Collections; +using namespace SDKTemplate; + +hstring implementation::MainPage::FEATURE_NAME() +{ + return L"ApplicationData C++/WinRT Sample"; +} + +IVector implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector( +{ + Scenario{ L"Files", xaml_typename() }, + Scenario{ L"Settings", xaml_typename() }, + Scenario{ L"Setting Containers", xaml_typename() }, + Scenario{ L"Composite Settings", xaml_typename() }, + Scenario{ L"ms-appdata:// Protocol", xaml_typename() }, + Scenario{ L"Clear", xaml_typename() }, + Scenario{ L"SetVersion", xaml_typename() }, +}); diff --git a/Samples/ApplicationData/cppwinrt/SampleConfiguration.h b/Samples/ApplicationData/cppwinrt/SampleConfiguration.h new file mode 100644 index 0000000000..ba0eb7c8c2 --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/SampleConfiguration.h @@ -0,0 +1,17 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once +#include "pch.h" + +namespace winrt::SDKTemplate +{ +} diff --git a/Samples/ApplicationData/cppwinrt/Scenario1_Files.cpp b/Samples/ApplicationData/cppwinrt/Scenario1_Files.cpp new file mode 100644 index 0000000000..16a7bac90f --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario1_Files.cpp @@ -0,0 +1,150 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include "Scenario1_Files.h" +#include "Scenario1_Files.g.cpp" + +using namespace winrt; +using namespace Windows::Foundation; +using namespace Windows::Storage; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Navigation; + +namespace winrt::SDKTemplate::implementation +{ + Scenario1_Files::Scenario1_Files() + { + InitializeComponent(); + } + + // Guidance for Local, LocalCache, and Temporary files. + // + // Files are ideal for storing large data-sets, databases, or data that is + // in a common file-format. + // + // Files can exist in either the Local, LocalCache, or Temporary folders. + // (They can also be put in Roaming folders, but the data no longer roams.) + // + // Local files are not synchronized, but they are backed up, and can then be restored to a + // machine different than where they were originally written. These should be for + // important files that allow the feel that the user did not lose anything + // when they restored to a new device. + // + // Temporary files are subject to deletion when not in use. The system + // considers factors such as available disk capacity and the age of a file when + // determining when or whether to delete a temporary file. + // + // LocalCache files are for larger files that can be recreated by the app, and for + // machine specific or private files that should not be restored to a new device. + + fire_and_forget Scenario1_Files::Increment_Local_Click(IInspectable const&, RoutedEventArgs const&) + { + auto strong = get_strong(); + + localCounter++; + + StorageFile file = co_await localFolder.CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting); + co_await FileIO::WriteTextAsync(file, std::to_wstring(localCounter)); + + Read_Local_Counter(); + } + + fire_and_forget Scenario1_Files::Read_Local_Counter() + { + auto strong = get_strong(); + + StorageFile file = (co_await localFolder.TryGetItemAsync(filename)).as(); + if (file != nullptr) + { + hstring text = co_await FileIO::ReadTextAsync(file); + + LocalOutputTextBlock().Text(L"Local Counter: " + text); + + localCounter = wcstol(text.c_str(), nullptr, 10); + } + else + { + LocalOutputTextBlock().Text(L"Local Counter: "); + } + } + + fire_and_forget Scenario1_Files::Increment_LocalCache_Click(IInspectable const&, RoutedEventArgs const&) + { + auto strong = get_strong(); + localCacheCounter++; + + StorageFile file = co_await localCacheFolder.CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting); + co_await FileIO::WriteTextAsync(file, std::to_wstring(localCacheCounter)); + + Read_LocalCache_Counter(); + } + + fire_and_forget Scenario1_Files::Read_LocalCache_Counter() + { + auto strong = get_strong(); + + StorageFile file = (co_await localCacheFolder.TryGetItemAsync(filename)).as(); + if (file != nullptr) + { + hstring text = co_await FileIO::ReadTextAsync(file); + + LocalCacheOutputTextBlock().Text(L"LocalCache Counter: " + text); + + localCacheCounter = wcstol(text.c_str(), nullptr, 10); + } + else + { + LocalCacheOutputTextBlock().Text(L"LocalCache Counter: "); + } + } + + fire_and_forget Scenario1_Files::Increment_Temporary_Click(IInspectable const&, RoutedEventArgs const&) + { + auto strong = get_strong(); + temporaryCounter++; + + StorageFile file = co_await temporaryFolder.CreateFileAsync(filename, CreationCollisionOption::ReplaceExisting); + co_await FileIO::WriteTextAsync(file, std::to_wstring(temporaryCounter)); + + Read_Temporary_Counter(); + } + + fire_and_forget Scenario1_Files::Read_Temporary_Counter() + { + StorageFile file = (co_await temporaryFolder.TryGetItemAsync(filename)).as(); + if (file != nullptr) + { + hstring text = co_await FileIO::ReadTextAsync(file); + + TemporaryOutputTextBlock().Text(L"Temporary Counter: " + text); + + temporaryCounter = wcstol(text.c_str(), nullptr, 10); + } + else + { + TemporaryOutputTextBlock().Text(L"Temporary Counter: "); + } + } + + void Scenario1_Files::DisplayOutput() + { + Read_Local_Counter(); + Read_LocalCache_Counter(); + Read_Temporary_Counter(); + } + + void Scenario1_Files::OnNavigatedTo(NavigationEventArgs const&) + { + DisplayOutput(); + } +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario1_Files.h b/Samples/ApplicationData/cppwinrt/Scenario1_Files.h new file mode 100644 index 0000000000..f34e96738c --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario1_Files.h @@ -0,0 +1,53 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once + +#include "Scenario1_Files.g.h" +#include "MainPage.h" + +namespace winrt::SDKTemplate::implementation +{ + struct Scenario1_Files : Scenario1_FilesT + { + Scenario1_Files(); + + void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&); + fire_and_forget Increment_Local_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + fire_and_forget Increment_LocalCache_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + fire_and_forget Increment_Temporary_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + + void DisplayOutput(); + + private: + + fire_and_forget Read_Local_Counter(); + fire_and_forget Read_LocalCache_Counter(); + fire_and_forget Read_Temporary_Counter(); + + Windows::Storage::StorageFolder localFolder = Windows::Storage::ApplicationData::Current().LocalFolder(); + int localCounter = 0; + Windows::Storage::StorageFolder localCacheFolder = Windows::Storage::ApplicationData::Current().LocalCacheFolder(); + int localCacheCounter = 0; + Windows::Storage::StorageFolder temporaryFolder = Windows::Storage::ApplicationData::Current().TemporaryFolder(); + int temporaryCounter = 0; + + inline static const auto filename = L"sampleFile.txt"; + }; +} + +namespace winrt::SDKTemplate::factory_implementation +{ + struct Scenario1_Files : Scenario1_FilesT + { + }; +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario2_Settings.cpp b/Samples/ApplicationData/cppwinrt/Scenario2_Settings.cpp new file mode 100644 index 0000000000..03f7ec477a --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario2_Settings.cpp @@ -0,0 +1,71 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include "Scenario2_Settings.h" +#include "Scenario2_Settings.g.cpp" + +using namespace winrt; +using namespace Windows::Foundation; +using namespace Windows::Storage; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Navigation; + +namespace winrt::SDKTemplate::implementation +{ + Scenario2_Settings::Scenario2_Settings() + { + InitializeComponent(); + } + + // Guidance for Settings. + // + // Settings are a convenient way of storing small pieces of configuration data + // for your application. + // + // There are two storage containers for settings: Local and Roaming. However, + // Roaming settings no longer roam, so they are functionally equivalent to Local. + // + // Care should be taken to guard against an excessive volume of data being + // stored in settings. Settings are not intended to be used as a database. + // Large data sets will take longer to load from disk during your application's + // launch. + + // This sample illustrates reading and writing from a local setting. + + void Scenario2_Settings::WriteSetting_Click(IInspectable const&, RoutedEventArgs const&) + { + hstring toSet = L"Hello World"; + localSettings.Values().Insert(SettingName, box_value(toSet)); // example value + + DisplayOutput(); + } + + void Scenario2_Settings::DeleteSetting_Click(IInspectable const&, RoutedEventArgs const&) + { + localSettings.Values().Remove(SettingName); + + DisplayOutput(); + } + + void Scenario2_Settings::DisplayOutput() + { + auto stringValue = localSettings.Values().TryLookup(SettingName).try_as(); + + OutputTextBlock().Text(L"Setting: " + (stringValue.has_value() ? L"\"" + stringValue.value() + L"\"" : L"")); + } + + void Scenario2_Settings::OnNavigatedTo(NavigationEventArgs const&) + { + DisplayOutput(); + } +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario2_Settings.h b/Samples/ApplicationData/cppwinrt/Scenario2_Settings.h new file mode 100644 index 0000000000..fa6e2f9f2d --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario2_Settings.h @@ -0,0 +1,43 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once + +#include "Scenario2_Settings.g.h" +#include "MainPage.h" + +namespace winrt::SDKTemplate::implementation +{ + struct Scenario2_Settings : Scenario2_SettingsT + { + Scenario2_Settings(); + + void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&); + void WriteSetting_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const& e); + void DeleteSetting_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + + private: + + void DisplayOutput(); + + Windows::Storage::ApplicationDataContainer localSettings = Windows::Storage::ApplicationData::Current().LocalSettings(); + + inline static const auto SettingName = L"exampleSetting"; + }; +} + +namespace winrt::SDKTemplate::factory_implementation +{ + struct Scenario2_Settings : Scenario2_SettingsT + { + }; +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario3_SettingContainer.cpp b/Samples/ApplicationData/cppwinrt/Scenario3_SettingContainer.cpp new file mode 100644 index 0000000000..9293832efd --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario3_SettingContainer.cpp @@ -0,0 +1,78 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include +#include "Scenario3_SettingContainer.h" +#include "Scenario3_SettingContainer.g.cpp" + +using namespace winrt; +using namespace Windows::Foundation; +using namespace Windows::Storage; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Navigation; + +namespace winrt::SDKTemplate::implementation +{ + Scenario3_SettingContainer::Scenario3_SettingContainer() + { + InitializeComponent(); + } + + void Scenario3_SettingContainer::CreateContainer_Click(IInspectable const&, RoutedEventArgs const&) + { + ApplicationDataContainer container = localSettings.CreateContainer(containerName, ApplicationDataCreateDisposition::Always); + + DisplayOutput(); + } + + void Scenario3_SettingContainer::DeleteContainer_Click(IInspectable const&, RoutedEventArgs const&) + { + localSettings.DeleteContainer(containerName); + + DisplayOutput(); + } + + void Scenario3_SettingContainer::WriteSetting_Click(IInspectable const&, RoutedEventArgs const&) + { + localSettings.Containers().Lookup(containerName).Values().Insert(settingName, box_value(L"Hello World")); // example value + + DisplayOutput(); + } + + void Scenario3_SettingContainer::DeleteSetting_Click(IInspectable const&, RoutedEventArgs const&) + { + localSettings.Containers().Lookup(containerName).Values().Remove(settingName); + + DisplayOutput(); + } + + void Scenario3_SettingContainer::DisplayOutput() + { + ApplicationDataContainer container = localSettings.Containers().TryLookup(containerName); + bool hasSetting = container ? container.Values().HasKey(settingName) : false; + + std::wstringstream formatted; + formatted << std::boolalpha << L"Container Exists: " << (container != nullptr) << std::endl; + formatted << L"Setting Exists: " << hasSetting << std::endl; + + OutputTextBlock().Text(formatted.str()); + + WriteSetting().IsEnabled(container != nullptr); + DeleteSetting().IsEnabled(container != nullptr); + } + + void Scenario3_SettingContainer::OnNavigatedTo(NavigationEventArgs const&) + { + DisplayOutput(); + } +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario3_SettingContainer.h b/Samples/ApplicationData/cppwinrt/Scenario3_SettingContainer.h new file mode 100644 index 0000000000..5eb770d2cd --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario3_SettingContainer.h @@ -0,0 +1,46 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once + +#include "Scenario3_SettingContainer.g.h" +#include "MainPage.h" + +namespace winrt::SDKTemplate::implementation +{ + struct Scenario3_SettingContainer : Scenario3_SettingContainerT + { + Scenario3_SettingContainer(); + + void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&); + void CreateContainer_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + void DeleteContainer_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + void WriteSetting_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + void DeleteSetting_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + + private: + + void DisplayOutput(); + + Windows::Storage::ApplicationDataContainer localSettings = Windows::Storage::ApplicationData::Current().LocalSettings(); + + inline static const auto containerName = L"exampleContainer"; + inline static const auto settingName = L"exampleSetting"; + }; +} + +namespace winrt::SDKTemplate::factory_implementation +{ + struct Scenario3_SettingContainer : Scenario3_SettingContainerT + { + }; +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario4_CompositeSettings.cpp b/Samples/ApplicationData/cppwinrt/Scenario4_CompositeSettings.cpp new file mode 100644 index 0000000000..36bc962683 --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario4_CompositeSettings.cpp @@ -0,0 +1,73 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include +#include "Scenario4_CompositeSettings.h" +#include "Scenario4_CompositeSettings.g.cpp" + +using namespace winrt; +using namespace Windows::Foundation; +using namespace Windows::Storage; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Navigation; + +namespace winrt::SDKTemplate::implementation +{ + Scenario4_CompositeSettings::Scenario4_CompositeSettings() + { + InitializeComponent(); + } + + void Scenario4_CompositeSettings::WriteCompositeSetting_Click(IInspectable const&, RoutedEventArgs const&) + { + // Composite settings are used to group multiple settings. + // Note that Composite settings may not be nested. + ApplicationDataCompositeValue composite; + composite.Insert(settingName1, box_value(1)); // example value + composite.Insert(settingName2, box_value(L"world")); // example value + + localSettings.Values().Insert(settingName, composite); + + DisplayOutput(); + } + + void Scenario4_CompositeSettings::DeleteCompositeSetting_Click(IInspectable const&, RoutedEventArgs const&) + { + localSettings.Values().Remove(settingName); + + DisplayOutput(); + } + + void Scenario4_CompositeSettings::DisplayOutput() + { + auto composite = localSettings.Values().Lookup(settingName).as(); + + std::wstringstream output; + if (!composite) + { + output << L"Composite Setting: "; + } + else + { + output << L"Composite setting: {" << settingName1 << L" = " << composite.Lookup(settingName1).as() << L", "; + output << settingName2 << L" = \"" << composite.Lookup(settingName2).as().c_str() << "\"}"; + } + + OutputTextBlock().Text(output.str()); + } + + void Scenario4_CompositeSettings::OnNavigatedTo(NavigationEventArgs const&) + { + DisplayOutput(); + } +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario4_CompositeSettings.h b/Samples/ApplicationData/cppwinrt/Scenario4_CompositeSettings.h new file mode 100644 index 0000000000..92f3eb6c08 --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario4_CompositeSettings.h @@ -0,0 +1,45 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once + +#include "Scenario4_CompositeSettings.g.h" +#include "MainPage.h" + +namespace winrt::SDKTemplate::implementation +{ + struct Scenario4_CompositeSettings : Scenario4_CompositeSettingsT + { + Scenario4_CompositeSettings(); + + void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&); + void WriteCompositeSetting_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + void DeleteCompositeSetting_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + + private: + + void DisplayOutput(); + + Windows::Storage::ApplicationDataContainer localSettings = Windows::Storage::ApplicationData::Current().LocalSettings(); + + inline static const auto settingName = L"exampleCompositeSetting"; + inline static const auto settingName1 = L"one"; + inline static const auto settingName2 = L"hello"; + }; +} + +namespace winrt::SDKTemplate::factory_implementation +{ + struct Scenario4_CompositeSettings : Scenario4_CompositeSettingsT + { + }; +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario5_Msappdata.cpp b/Samples/ApplicationData/cppwinrt/Scenario5_Msappdata.cpp new file mode 100644 index 0000000000..bc86b04dd1 --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario5_Msappdata.cpp @@ -0,0 +1,61 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include "Scenario5_Msappdata.h" +#include "Scenario5_Msappdata.g.cpp" + +using namespace winrt; +using namespace Windows::Foundation; +using namespace Windows::Storage; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Media::Imaging; +using namespace Windows::UI::Xaml::Navigation; + +namespace winrt::SDKTemplate::implementation +{ + Scenario5_Msappdata::Scenario5_Msappdata() + { + InitializeComponent(); + } + + IAsyncAction Scenario5_Msappdata::CopyAssetToFolderIfNecessaryAsync(hstring name, StorageFolder const& folder) + { + if (co_await folder.TryGetItemAsync(name) == nullptr) + { + auto sourceFile = co_await StorageFile::GetFileFromApplicationUriAsync(Uri{ L"ms-appx:///assets/" + name }); + co_await sourceFile.CopyAsync(folder); + } + } + + fire_and_forget Scenario5_Msappdata::OnNavigatedTo(NavigationEventArgs const&) + { + auto strong = get_strong(); + ApplicationData appData = ApplicationData::Current(); + + co_await CopyAssetToFolderIfNecessaryAsync(L"appDataLocal.png", appData.LocalFolder()); + co_await CopyAssetToFolderIfNecessaryAsync(L"appDataRoaming.png", appData.RoamingFolder()); + co_await CopyAssetToFolderIfNecessaryAsync(L"appDataTemp.png", appData.TemporaryFolder()); + + LocalImage().Source(BitmapImage{ Uri{L"ms-appdata:///local/appDataLocal.png"} }); + RoamingImage().Source(BitmapImage{ Uri{L"ms-appdata:///roaming/appDataRoaming.png"} }); + TempImage().Source(BitmapImage{ Uri{L"ms-appdata:///temp/appDataTemp.png"} }); + } + + void Scenario5_Msappdata::OnNavigatingFrom(NavigatingCancelEventArgs const&) + { + LocalImage().Source(nullptr); + RoamingImage().Source(nullptr); + TempImage().Source(nullptr); + } + +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario5_Msappdata.h b/Samples/ApplicationData/cppwinrt/Scenario5_Msappdata.h new file mode 100644 index 0000000000..5df7037880 --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario5_Msappdata.h @@ -0,0 +1,37 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once + +#include "Scenario5_Msappdata.g.h" +#include "MainPage.h" + +namespace winrt::SDKTemplate::implementation +{ + struct Scenario5_Msappdata : Scenario5_MsappdataT + { + Scenario5_Msappdata(); + + fire_and_forget OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const&); + void OnNavigatingFrom(Windows::UI::Xaml::Navigation::NavigatingCancelEventArgs const&); + + private: + Windows::Foundation::IAsyncAction CopyAssetToFolderIfNecessaryAsync(hstring name, Windows::Storage::StorageFolder const& folder); + }; +} + +namespace winrt::SDKTemplate::factory_implementation +{ + struct Scenario5_Msappdata : Scenario5_MsappdataT + { + }; +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario6_ClearScenario.cpp b/Samples/ApplicationData/cppwinrt/Scenario6_ClearScenario.cpp new file mode 100644 index 0000000000..2d65f295cf --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario6_ClearScenario.cpp @@ -0,0 +1,41 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include "Scenario6_ClearScenario.h" +#include "Scenario6_ClearScenario.g.cpp" + +using namespace winrt; +using namespace Windows::Foundation; +using namespace Windows::UI::Xaml; +using namespace Windows::Storage; + +namespace winrt::SDKTemplate::implementation +{ + Scenario6_ClearScenario::Scenario6_ClearScenario() + { + InitializeComponent(); + } + + fire_and_forget Scenario6_ClearScenario::Clear_Click(IInspectable const&, RoutedEventArgs const&) + { + try + { + co_await ApplicationData::Current().ClearAsync(); + OutputTextBlock().Text(L"ApplicationData has been cleared. Visit the other scenarios to see that their data has been cleared."); + } + catch (...) + { + OutputTextBlock().Text(L"Unable to clear settings. This can happen when files are in use."); + } + } +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario6_ClearScenario.h b/Samples/ApplicationData/cppwinrt/Scenario6_ClearScenario.h new file mode 100644 index 0000000000..93c0299487 --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario6_ClearScenario.h @@ -0,0 +1,33 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once + +#include "Scenario6_ClearScenario.g.h" +#include "MainPage.h" + +namespace winrt::SDKTemplate::implementation +{ + struct Scenario6_ClearScenario : Scenario6_ClearScenarioT + { + Scenario6_ClearScenario(); + + fire_and_forget Clear_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + }; +} + +namespace winrt::SDKTemplate::factory_implementation +{ + struct Scenario6_ClearScenario : Scenario6_ClearScenarioT + { + }; +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario7_SetVersion.cpp b/Samples/ApplicationData/cppwinrt/Scenario7_SetVersion.cpp new file mode 100644 index 0000000000..d0b6d4fe0d --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario7_SetVersion.cpp @@ -0,0 +1,109 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#include "pch.h" +#include "Scenario7_SetVersion.h" +#include "Scenario7_SetVersion.g.cpp" + +using namespace winrt; +using namespace Windows::Foundation; +using namespace Windows::Storage; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Navigation; + +namespace winrt::SDKTemplate::implementation +{ + Scenario7_SetVersion::Scenario7_SetVersion() + { + InitializeComponent(); + + DisplayOutput(); + } + + void Scenario7_SetVersion::SetVersionHandler0(SetVersionRequest const& request) + { + auto deferral = request.GetDeferral(); + + uint32_t version = appData.Version(); + + switch (version) + { + case 0: + // Version is already 0. Nothing to do. + break; + + case 1: + // Need to convert data from v1 to v0. + + // This sample simulates that conversion by writing a version-specific value. + appData.LocalSettings().Values().Insert(settingName, box_value(settingValue0)); + + break; + + default: + throw hresult_invalid_argument(L"Unexpected ApplicationData Version: " + to_hstring(version)); + } + + deferral.Complete(); + } + + void Scenario7_SetVersion::SetVersionHandler1(SetVersionRequest const& request) + { + auto deferral = request.GetDeferral(); + + uint32_t version = appData.Version(); + + switch (version) + { + case 0: + // Need to convert data from v0 to v1. + + // This sample simulates that conversion by writing a version-specific value. + appData.LocalSettings().Values().Insert(settingName, box_value(settingValue1)); + + break; + + case 1: + // Version is already 1. Nothing to do. + break; + + default: + throw hresult_invalid_argument(L"Unexpected ApplicationData Version: " + to_hstring(version)); + } + + deferral.Complete(); + } + + fire_and_forget Scenario7_SetVersion::SetVersion0_Click(IInspectable const&, RoutedEventArgs const&) + { + auto strong = get_strong(); + co_await appData.SetVersionAsync(0, { get_weak(), &Scenario7_SetVersion::SetVersionHandler0 }); + DisplayOutput(); + } + + fire_and_forget Scenario7_SetVersion::SetVersion1_Click(IInspectable const&, RoutedEventArgs const&) + { + auto strong = get_strong(); + co_await appData.SetVersionAsync(1, { get_weak(), &Scenario7_SetVersion::SetVersionHandler1 }); + DisplayOutput(); + } + + void Scenario7_SetVersion::DisplayOutput() + { + OutputTextBlock().Text(L"Version: " + to_hstring(appData.Version())); + } + + void Scenario7_SetVersion::OnNavigatedTo(NavigationEventArgs const&) + { + DisplayOutput(); + } +} + diff --git a/Samples/ApplicationData/cppwinrt/Scenario7_SetVersion.h b/Samples/ApplicationData/cppwinrt/Scenario7_SetVersion.h new file mode 100644 index 0000000000..7fc407f356 --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/Scenario7_SetVersion.h @@ -0,0 +1,48 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +#pragma once + +#include "Scenario7_SetVersion.g.h" +#include "MainPage.h" + +namespace winrt::SDKTemplate::implementation +{ + struct Scenario7_SetVersion : Scenario7_SetVersionT + { + Scenario7_SetVersion(); + + void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e); + fire_and_forget SetVersion0_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + fire_and_forget SetVersion1_Click(Windows::Foundation::IInspectable const&, Windows::UI::Xaml::RoutedEventArgs const&); + + void DisplayOutput(); + + private: + + void SetVersionHandler0(Windows::Storage::SetVersionRequest const& request); + void SetVersionHandler1(Windows::Storage::SetVersionRequest const& request); + + Windows::Storage::ApplicationData appData = Windows::Storage::ApplicationData::Current(); + + inline static const auto settingName = L"SetVersionSetting"; + inline static const auto settingValue0 = L"Data.v0"; + inline static const auto settingValue1 = L"Data.v1"; + }; +} + +namespace winrt::SDKTemplate::factory_implementation +{ + struct Scenario7_SetVersion : Scenario7_SetVersionT + { + }; +} + diff --git a/Samples/ApplicationData/cppwinrt/packages.config b/Samples/ApplicationData/cppwinrt/packages.config new file mode 100644 index 0000000000..dc8ede20f0 --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Samples/ApplicationData/cppwinrt/pch.cpp b/Samples/ApplicationData/cppwinrt/pch.cpp new file mode 100644 index 0000000000..01484ff5aa --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/pch.cpp @@ -0,0 +1,6 @@ +// +// pch.cpp +// Include the standard header and generate the precompiled header. +// + +#include "pch.h" diff --git a/Samples/ApplicationData/cppwinrt/pch.h b/Samples/ApplicationData/cppwinrt/pch.h new file mode 100644 index 0000000000..b47bbb808d --- /dev/null +++ b/Samples/ApplicationData/cppwinrt/pch.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include "winrt/Windows.Foundation.h" +#include "winrt/Windows.Foundation.Collections.h" +#include "winrt/Windows.ApplicationModel.Activation.h" +#include "winrt/Windows.System.h" +#include "winrt/Windows.UI.Core.h" +#include "winrt/Windows.UI.Xaml.h" +#include "winrt/Windows.UI.Xaml.Automation.Peers.h" +#include "winrt/Windows.UI.Xaml.Controls.h" +#include "winrt/Windows.UI.Xaml.Controls.Primitives.h" +#include "winrt/Windows.UI.Xaml.Documents.h" +#include "winrt/Windows.UI.Xaml.Interop.h" +#include "winrt/Windows.UI.Xaml.Markup.h" +#include "winrt/Windows.UI.Xaml.Media.h" +#include "winrt/Windows.UI.Xaml.Media.Imaging.h" +#include "winrt/Windows.UI.Xaml.Navigation.h" +#include "winrt/Windows.Storage.h" \ No newline at end of file diff --git a/Samples/ApplicationData/cs/App.xaml.cs b/Samples/ApplicationData/cs/App.xaml.cs deleted file mode 100644 index 2e620f964b..0000000000 --- a/Samples/ApplicationData/cs/App.xaml.cs +++ /dev/null @@ -1,110 +0,0 @@ -//********************************************************* -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//********************************************************* - -using System; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Navigation; - -// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=402347&clcid=0x409 - -namespace SDKTemplate -{ - /// - /// Provides application-specific behavior to supplement the default Application class. - /// - sealed partial class App : Application - { - /// - /// Initializes the singleton application object. This is the first line of authored code - /// executed, and as such is the logical equivalent of main() or WinMain(). - /// - public App() - { - this.InitializeComponent(); - this.Suspending += OnSuspending; - } - - /// - /// Invoked when the application is launched normally by the end user. Other entry points - /// will be used such as when the application is launched to open a specific file. - /// - /// Details about the launch request and process. - protected override void OnLaunched(LaunchActivatedEventArgs e) - { - -#if DEBUG - if (System.Diagnostics.Debugger.IsAttached) - { - this.DebugSettings.EnableFrameRateCounter = false; - } -#endif - - Frame rootFrame = Window.Current.Content as Frame; - - // Do not repeat app initialization when the Window already has content, - // just ensure that the window is active - if (rootFrame == null) - { - // Create a Frame to act as the navigation context and navigate to the first page - rootFrame = new Frame(); - // Set the default language - rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0]; - - rootFrame.NavigationFailed += OnNavigationFailed; - - if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) - { - //TODO: Load state from previously suspended application - } - - // Place the frame in the current Window - Window.Current.Content = rootFrame; - } - - if (rootFrame.Content == null) - { - // When the navigation stack isn't restored navigate to the first page, - // configuring the new page by passing required information as a navigation - // parameter - rootFrame.Navigate(typeof(MainPage), e.Arguments); - } - // Ensure the current window is active - Window.Current.Activate(); - } - - /// - /// Invoked when Navigation to a certain page fails - /// - /// The Frame which failed navigation - /// Details about the navigation failure - void OnNavigationFailed(object sender, NavigationFailedEventArgs e) - { - throw new Exception("Failed to load Page " + e.SourcePageType.FullName); - } - - /// - /// Invoked when application execution is being suspended. Application state is saved - /// without knowing whether the application will be terminated or resumed with the contents - /// of memory still intact. - /// - /// The source of the suspend request. - /// Details about the suspend request. - private void OnSuspending(object sender, SuspendingEventArgs e) - { - var deferral = e.SuspendingOperation.GetDeferral(); - //TODO: Save application state and stop any background activity - deferral.Complete(); - } - } -} diff --git a/Samples/ApplicationData/cs/ApplicationData.csproj b/Samples/ApplicationData/cs/ApplicationData.csproj index bde7cb8425..89f06800c6 100644 --- a/Samples/ApplicationData/cs/ApplicationData.csproj +++ b/Samples/ApplicationData/cs/ApplicationData.csproj @@ -6,7 +6,7 @@ Debug - AnyCPU + x64 {E3631F30-6FD8-5AE6-88E0-CA94395F48CA} AppContainerExe Properties @@ -15,31 +15,12 @@ en-US UAP 10.0.22000.0 - 10.0.22000.0 + $(TargetPlatformVersion) 14 true 512 {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UAP - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE;NETFX_CORE;WINDOWS_UAP - prompt - 4 - true bin\ARM\Debug\ @@ -110,10 +91,12 @@ true - + + App.xaml.cs App.xaml - + + MainPage.xaml.cs MainPage.xaml @@ -132,22 +115,13 @@ Scenario4_CompositeSettings.xaml - - Scenario5_DataChangedEvent.xaml - - - Scenario6_HighPriority.xaml + + + Scenario6_ClearScenario.xaml - - Scenario7_Msappdata.xaml + + Scenario7_SetVersion.xaml - - Scenario8_ClearScenario.xaml - - - Scenario9_SetVersion.xaml - - @@ -155,12 +129,12 @@ - + App.xaml MSBuild:Compile Designer - + MainPage.xaml MSBuild:Compile Designer @@ -185,28 +159,18 @@ MSBuild:Compile Designer - - Scenario5_DataChangedEvent.xaml - MSBuild:Compile - Designer - - - Scenario6_HighPriority.xaml + + Scenario5_Msappdata.xaml MSBuild:Compile Designer - - Scenario7_Msappdata.xaml + + Scenario6_ClearScenario.xaml MSBuild:Compile Designer - - Scenario8_ClearScenario.xaml - MSBuild:Compile - Designer - - - Scenario9_SetVersion.xaml + + Scenario7_SetVersion.xaml MSBuild:Compile Designer @@ -220,9 +184,15 @@ Properties\Default.rd.xml - - - + + Assets\appDataLocal.png + + + Assets\appDataRoaming.png + + + Assets\appDataTemp.png + Assets\microsoft-sdk.png diff --git a/Samples/ApplicationData/cs/MainPage.xaml.cs b/Samples/ApplicationData/cs/MainPage.xaml.cs deleted file mode 100644 index 1de60df818..0000000000 --- a/Samples/ApplicationData/cs/MainPage.xaml.cs +++ /dev/null @@ -1,136 +0,0 @@ -//********************************************************* -// -// Copyright (c) Microsoft. All rights reserved. -// This code is licensed under the Microsoft Public License. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//********************************************************* - -using System; -using System.Collections.Generic; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Data; -using Windows.UI.Xaml.Media; -using Windows.UI.Xaml.Navigation; - -// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 - -namespace SDKTemplate -{ - /// - /// An empty page that can be used on its own or navigated to within a Frame. - /// - public sealed partial class MainPage : Page - { - public static MainPage Current; - - public MainPage() - { - this.InitializeComponent(); - - // This is a static public property that allows downstream pages to get a handle to the MainPage instance - // in order to call methods that are in this class. - Current = this; - SampleTitle.Text = FEATURE_NAME; - } - - protected override void OnNavigatedTo(NavigationEventArgs e) - { - // Populate the scenario list from the SampleConfiguration.cs file - ScenarioControl.ItemsSource = scenarios; - if (Window.Current.Bounds.Width < 640) - { - ScenarioControl.SelectedIndex = -1; - } - else - { - ScenarioControl.SelectedIndex = 0; - } - } - - /// - /// Called whenever the user changes selection in the scenarios list. This method will navigate to the respective - /// sample scenario page. - /// - /// - /// - private void ScenarioControl_SelectionChanged(object sender, SelectionChangedEventArgs e) - { - // Clear the status block when navigating scenarios. - NotifyUser(String.Empty, NotifyType.StatusMessage); - - ListBox scenarioListBox = sender as ListBox; - Scenario s = scenarioListBox.SelectedItem as Scenario; - if (s != null) - { - ScenarioFrame.Navigate(s.ClassType); - if (Window.Current.Bounds.Width < 640) - { - Splitter.IsPaneOpen = false; - StatusBorder.Visibility = Visibility.Collapsed; - } - } - } - - public List Scenarios - { - get { return this.scenarios; } - } - - /// - /// Used to display messages to the user - /// - /// - /// - public void NotifyUser(string strMessage, NotifyType type) - { - switch (type) - { - case NotifyType.StatusMessage: - StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Green); - break; - case NotifyType.ErrorMessage: - StatusBorder.Background = new SolidColorBrush(Windows.UI.Colors.Red); - break; - } - StatusBlock.Text = strMessage; - - // Collapse the StatusBlock if it has no text to conserve real estate. - StatusBorder.Visibility = (StatusBlock.Text != String.Empty) ? Visibility.Visible : Visibility.Collapsed; - } - - async void Footer_Click(object sender, RoutedEventArgs e) - { - await Windows.System.Launcher.LaunchUriAsync(new Uri(((HyperlinkButton)sender).Tag.ToString())); - } - - private void Button_Click(object sender, RoutedEventArgs e) - { - Splitter.IsPaneOpen = (Splitter.IsPaneOpen == true) ? false : true; - StatusBorder.Visibility = Visibility.Collapsed; - } - } - public enum NotifyType - { - StatusMessage, - ErrorMessage - }; - - public class ScenarioBindingConverter : IValueConverter - { - public object Convert(object value, Type targetType, object parameter, string language) - { - Scenario s = value as Scenario; - return (MainPage.Current.Scenarios.IndexOf(s) + 1) + ") " + s.Title; - } - - public object ConvertBack(object value, Type targetType, object parameter, string language) - { - return true; - } - } -} diff --git a/Samples/ApplicationData/cs/SampleConfiguration.cs b/Samples/ApplicationData/cs/SampleConfiguration.cs index 6d9e27cc2f..31ebd23601 100644 --- a/Samples/ApplicationData/cs/SampleConfiguration.cs +++ b/Samples/ApplicationData/cs/SampleConfiguration.cs @@ -19,22 +19,15 @@ public partial class MainPage : Page { public const string FEATURE_NAME = "ApplicationData"; - // Change the array below to reflect the name of your scenarios. - // This will be used to populate the list of scenarios on the main page with - // which the user will choose the specific scenario that they are interested in. - // These should be in the form: "Navigating to a web page". - // The code in MainPage will take care of turning this into: "1) Navigating to a web page" List scenarios = new List { - new Scenario() { Title = "Files", ClassType = typeof(ApplicationDataSample.Files) }, - new Scenario() { Title = "Settings", ClassType = typeof(ApplicationDataSample.Settings) }, - new Scenario() { Title = "Setting Containers", ClassType = typeof(ApplicationDataSample.SettingContainer) }, - new Scenario() { Title = "Composite Settings", ClassType = typeof(ApplicationDataSample.CompositeSettings) }, - new Scenario() { Title = "DataChanged Event", ClassType = typeof(ApplicationDataSample.DataChangedEvent) }, - new Scenario() { Title = "Roaming: HighPriority", ClassType = typeof(ApplicationDataSample.HighPriority) }, - new Scenario() { Title = "ms-appdata:// Protocol", ClassType = typeof(ApplicationDataSample.Msappdata) }, - new Scenario() { Title = "Clear", ClassType = typeof(ApplicationDataSample.ClearScenario) }, - new Scenario() { Title = "SetVersion", ClassType = typeof(ApplicationDataSample.SetVersion) }, + new Scenario() { Title = "Files", ClassType = typeof(Scenario1_Files) }, + new Scenario() { Title = "Settings", ClassType = typeof(Scenario2_Settings) }, + new Scenario() { Title = "Setting Containers", ClassType = typeof(Scenario3_SettingContainer) }, + new Scenario() { Title = "Composite Settings", ClassType = typeof(Scenario4_CompositeSettings) }, + new Scenario() { Title = "ms-appdata:// Protocol", ClassType = typeof(Scenario5_Msappdata) }, + new Scenario() { Title = "Clear", ClassType = typeof(Scenario6_ClearScenario) }, + new Scenario() { Title = "SetVersion", ClassType = typeof(Scenario7_SetVersion) }, }; } diff --git a/Samples/ApplicationData/cs/Scenario1_Files.xaml.cs b/Samples/ApplicationData/cs/Scenario1_Files.xaml.cs index 3fbdf2d0da..bc0f5c61f6 100644 --- a/Samples/ApplicationData/cs/Scenario1_Files.xaml.cs +++ b/Samples/ApplicationData/cs/Scenario1_Files.xaml.cs @@ -1,4 +1,4 @@ -//********************************************************* +//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF @@ -8,64 +8,41 @@ // //********************************************************* +using System; +using Windows.Storage; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; -using SDKTemplate; -using System; -using Windows.Storage; -namespace ApplicationDataSample +namespace SDKTemplate { - /// - /// An empty page that can be used on its own or navigated to within a Frame. - /// - public sealed partial class Files : Page + public sealed partial class Scenario1_Files : Page { - // A pointer back to the main page. This is needed if you want to call methods in MainPage such - // as NotifyUser() - MainPage rootPage = MainPage.Current; - StorageFolder localFolder = null; + StorageFolder localFolder = ApplicationData.Current.LocalFolder; int localCounter = 0; - StorageFolder localCacheFolder = null; + StorageFolder localCacheFolder = ApplicationData.Current.LocalCacheFolder; int localCacheCounter = 0; - StorageFolder roamingFolder = null; - int roamingCounter = 0; - StorageFolder temporaryFolder = null; + StorageFolder temporaryFolder = ApplicationData.Current.TemporaryFolder; int temporaryCounter = 0; const string filename = "sampleFile.txt"; - public Files() + public Scenario1_Files() { - this.InitializeComponent(); - - localFolder = ApplicationData.Current.LocalFolder; - localCacheFolder = ApplicationData.Current.LocalCacheFolder; - roamingFolder = ApplicationData.Current.RoamingFolder; - temporaryFolder = ApplicationData.Current.TemporaryFolder; - - DisplayOutput(); + InitializeComponent(); } - // Guidance for Local, LocalCache, Roaming, and Temporary files. + // Guidance for Local, LocalCache, and Temporary files. // // Files are ideal for storing large data-sets, databases, or data that is // in a common file-format. // - // Files can exist in either the Local, LocalCache, Roaming, or Temporary folders. - // - // Roaming files will be synchronized across machines on which the user has - // singed in with a connected account. Roaming of files is not instant; the - // system weighs several factors when determining when to send the data. Usage - // of roaming data should be kept below the quota (available via the - // RoamingStorageQuota property), or else roaming of data will be suspended. - // Files cannot be roamed while an application is writing to them, so be sure - // to close your application's file objects when they are no longer needed. + // Files can exist in either the Local, LocalCache, or Temporary folders. + // (They can also be put in Roaming folders, but the data no longer roams.) // - // Local files are not synchronized, but are backed up, and can then be restored to a + // Local files are not synchronized, but they are backed up, and can then be restored to a // machine different than where they were originally written. These should be for - // important files that allow the feel that the user did not loose anything + // important files that allow the feel that the user did not lose anything // when they restored to a new device. // // Temporary files are subject to deletion when not in use. The system @@ -87,16 +64,16 @@ async void Increment_Local_Click(Object sender, RoutedEventArgs e) async void Read_Local_Counter() { - try + StorageFile file = (await localFolder.TryGetItemAsync(filename)) as StorageFile; + if (file != null) { - StorageFile file = await localFolder.GetFileAsync(filename); string text = await FileIO.ReadTextAsync(file); LocalOutputTextBlock.Text = "Local Counter: " + text; localCounter = int.Parse(text); } - catch (Exception) + else { LocalOutputTextBlock.Text = "Local Counter: "; } @@ -113,49 +90,22 @@ async void Increment_LocalCache_Click(Object sender, RoutedEventArgs e) } async void Read_LocalCache_Counter() - { - try + { + StorageFile file = (await localCacheFolder.TryGetItemAsync(filename)) as StorageFile; + if (file != null) { - StorageFile file = await localCacheFolder.GetFileAsync(filename); string text = await FileIO.ReadTextAsync(file); LocalCacheOutputTextBlock.Text = "LocalCache Counter: " + text; localCacheCounter = int.Parse(text); } - catch (Exception) + else { LocalCacheOutputTextBlock.Text = "LocalCache Counter: "; } } - async void Increment_Roaming_Click(Object sender, RoutedEventArgs e) - { - roamingCounter++; - - StorageFile file = await roamingFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting); - await FileIO.WriteTextAsync(file, roamingCounter.ToString()); - - Read_Roaming_Counter(); - } - - async void Read_Roaming_Counter() - { - try - { - StorageFile file = await roamingFolder.GetFileAsync(filename); - string text = await FileIO.ReadTextAsync(file); - - RoamingOutputTextBlock.Text = "Roaming Counter: " + text; - - roamingCounter = int.Parse(text); - } - catch (Exception) - { - RoamingOutputTextBlock.Text = "Roaming Counter: "; - } - } - async void Increment_Temporary_Click(Object sender, RoutedEventArgs e) { temporaryCounter++; @@ -168,16 +118,16 @@ async void Increment_Temporary_Click(Object sender, RoutedEventArgs e) async void Read_Temporary_Counter() { - try + StorageFile file = (await temporaryFolder.TryGetItemAsync(filename)) as StorageFile; + if (file != null) { - StorageFile file = await temporaryFolder.GetFileAsync(filename); string text = await FileIO.ReadTextAsync(file); TemporaryOutputTextBlock.Text = "Temporary Counter: " + text; temporaryCounter = int.Parse(text); } - catch (Exception) + else { TemporaryOutputTextBlock.Text = "Temporary Counter: "; } @@ -187,17 +137,12 @@ void DisplayOutput() { Read_Local_Counter(); Read_LocalCache_Counter(); - Read_Roaming_Counter(); Read_Temporary_Counter(); } - /// - /// Invoked when this page is about to be displayed in a Frame. - /// - /// Event data that describes how this page was reached. The Parameter - /// property is typically used to configure the page. protected override void OnNavigatedTo(NavigationEventArgs e) { + DisplayOutput(); } } -} \ No newline at end of file +} diff --git a/Samples/ApplicationData/cs/Scenario2_Settings.xaml.cs b/Samples/ApplicationData/cs/Scenario2_Settings.xaml.cs index 54493851a1..6b22b8fa3d 100644 --- a/Samples/ApplicationData/cs/Scenario2_Settings.xaml.cs +++ b/Samples/ApplicationData/cs/Scenario2_Settings.xaml.cs @@ -1,4 +1,4 @@ -//********************************************************* +//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF @@ -11,31 +11,20 @@ using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; -using SDKTemplate; using System; using Windows.Storage; -namespace ApplicationDataSample +namespace SDKTemplate { - /// - /// An empty page that can be used on its own or navigated to within a Frame. - /// - public sealed partial class Settings : Page + public sealed partial class Scenario2_Settings : Page { - // A pointer back to the main page. This is needed if you want to call methods in MainPage such - // as NotifyUser() - MainPage rootPage = MainPage.Current; - ApplicationDataContainer roamingSettings = null; + ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; const string SettingName = "exampleSetting"; - public Settings() + public Scenario2_Settings() { - this.InitializeComponent(); - - roamingSettings = ApplicationData.Current.RoamingSettings; - - DisplayOutput(); + InitializeComponent(); } // Guidance for Settings. @@ -43,58 +32,40 @@ public Settings() // Settings are a convenient way of storing small pieces of configuration data // for your application. // - // Settings can be either Local or Roaming. - // - // Roaming settings will be synchronized across machines on which the user has - // signed in with a Microsoft Account. Roaming of settings is not instant; the - // system weighs several factors when determining when to send the data. Usage - // of roaming data should be kept below the quota (available via the - // RoamingStorageQuota property), or else roaming of data will be suspended. - // - // User preferences for your application are a great match for roaming settings. - // User preferences are usually fixed in number and small in size. Users will - // appreciated that your application is customized the way they prefer across - // all of their machines. - // - // Local settings are not synchronized and remain on the machine on which they - // were originally written. + // There are two storage containers for settings: Local and Roaming. However, + // Roaming settings no longer roam, so they are functionally equivalent to Local. // // Care should be taken to guard against an excessive volume of data being // stored in settings. Settings are not intended to be used as a database. // Large data sets will take longer to load from disk during your application's // launch. - // This sample illustrates reading and writing from a roaming setting, though a - // local setting could be used just as easily. + // This sample illustrates reading and writing from a local setting. void WriteSetting_Click(Object sender, RoutedEventArgs e) { - roamingSettings.Values[SettingName] = "Hello World"; // example value + localSettings.Values[SettingName] = "Hello World"; // example value DisplayOutput(); } void DeleteSetting_Click(Object sender, RoutedEventArgs e) { - roamingSettings.Values.Remove(SettingName); + localSettings.Values.Remove(SettingName); DisplayOutput(); } void DisplayOutput() { - Object value = roamingSettings.Values[SettingName]; + Object value = localSettings.Values[SettingName]; OutputTextBlock.Text = String.Format("Setting: {0}", (value == null ? "" : ("\"" + value + "\""))); } - /// - /// Invoked when this page is about to be displayed in a Frame. - /// - /// Event data that describes how this page was reached. The Parameter - /// property is typically used to configure the page. protected override void OnNavigatedTo(NavigationEventArgs e) { + DisplayOutput(); } } } diff --git a/Samples/ApplicationData/cs/Scenario3_SettingContainer.xaml.cs b/Samples/ApplicationData/cs/Scenario3_SettingContainer.xaml.cs index 5c723836c2..7d51ce4017 100644 --- a/Samples/ApplicationData/cs/Scenario3_SettingContainer.xaml.cs +++ b/Samples/ApplicationData/cs/Scenario3_SettingContainer.xaml.cs @@ -1,4 +1,4 @@ -//********************************************************* +//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF @@ -11,32 +11,25 @@ using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; -using SDKTemplate; using System; using Windows.Storage; -namespace ApplicationDataSample +namespace SDKTemplate { /// /// An empty page that can be used on its own or navigated to within a Frame. /// - public sealed partial class SettingContainer : Page + public sealed partial class Scenario3_SettingContainer : Page { - // A pointer back to the main page. This is needed if you want to call methods in MainPage such - // as NotifyUser() MainPage rootPage = MainPage.Current; - ApplicationDataContainer localSettings = null; + ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; const string containerName = "exampleContainer"; const string settingName = "exampleSetting"; - public SettingContainer() + public Scenario3_SettingContainer() { - this.InitializeComponent(); - - localSettings = ApplicationData.Current.LocalSettings; - - DisplayOutput(); + InitializeComponent(); } void CreateContainer_Click(Object sender, RoutedEventArgs e) @@ -55,44 +48,32 @@ void DeleteContainer_Click(Object sender, RoutedEventArgs e) void WriteSetting_Click(Object sender, RoutedEventArgs e) { - if (localSettings.Containers.ContainsKey(containerName)) - { - localSettings.Containers[containerName].Values[settingName] = "Hello World"; // example value - } + localSettings.Containers[containerName].Values[settingName] = "Hello World"; // example value DisplayOutput(); } void DeleteSetting_Click(Object sender, RoutedEventArgs e) { - if (localSettings.Containers.ContainsKey(containerName)) - { - localSettings.Containers[containerName].Values.Remove(settingName); - } + localSettings.Containers[containerName].Values.Remove(settingName); DisplayOutput(); } void DisplayOutput() { - bool hasContainer = localSettings.Containers.ContainsKey(containerName); - bool hasSetting = hasContainer ? localSettings.Containers[containerName].Values.ContainsKey(settingName) : false; + bool hasContainer = localSettings.Containers.TryGetValue(containerName, out ApplicationDataContainer container); + bool hasSetting = hasContainer ? container.Values.ContainsKey(settingName) : false; - String output = String.Format("Container Exists: {0}\n" + - "Setting Exists: {1}", - hasContainer ? "true" : "false", - hasSetting ? "true" : "false"); + OutputTextBlock.Text = $"Container Exists: {hasContainer}\nSetting Exists: {hasSetting}"; - OutputTextBlock.Text = output; + WriteSetting.IsEnabled = hasContainer; + DeleteSetting.IsEnabled = hasContainer; } - /// - /// Invoked when this page is about to be displayed in a Frame. - /// - /// Event data that describes how this page was reached. The Parameter - /// property is typically used to configure the page. protected override void OnNavigatedTo(NavigationEventArgs e) { + DisplayOutput(); } } } diff --git a/Samples/ApplicationData/cs/Scenario4_CompositeSettings.xaml.cs b/Samples/ApplicationData/cs/Scenario4_CompositeSettings.xaml.cs index 21500c7e9a..939681595f 100644 --- a/Samples/ApplicationData/cs/Scenario4_CompositeSettings.xaml.cs +++ b/Samples/ApplicationData/cs/Scenario4_CompositeSettings.xaml.cs @@ -1,4 +1,4 @@ -//********************************************************* +//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF @@ -11,56 +11,47 @@ using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; -using SDKTemplate; using System; using Windows.Storage; -namespace ApplicationDataSample +namespace SDKTemplate { - /// - /// An empty page that can be used on its own or navigated to within a Frame. - /// - public sealed partial class CompositeSettings : Page + public sealed partial class Scenario4_CompositeSettings : Page { - // A pointer back to the main page. This is needed if you want to call methods in MainPage such - // as NotifyUser() - MainPage rootPage = MainPage.Current; - ApplicationDataContainer roamingSettings = null; + ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; const string settingName = "exampleCompositeSetting"; const string settingName1 = "one"; const string settingName2 = "hello"; - public CompositeSettings() + public Scenario4_CompositeSettings() { - this.InitializeComponent(); - - roamingSettings = ApplicationData.Current.RoamingSettings; - - DisplayOutput(); + InitializeComponent(); } void WriteCompositeSetting_Click(Object sender, RoutedEventArgs e) { + // Composite settings are used to group multiple settings. + // Note that Composite settings may not be nested. ApplicationDataCompositeValue composite = new ApplicationDataCompositeValue(); composite[settingName1] = 1; // example value composite[settingName2] = "world"; // example value - roamingSettings.Values[settingName] = composite; + localSettings.Values[settingName] = composite; DisplayOutput(); } void DeleteCompositeSetting_Click(Object sender, RoutedEventArgs e) { - roamingSettings.Values.Remove(settingName); + localSettings.Values.Remove(settingName); DisplayOutput(); } void DisplayOutput() { - ApplicationDataCompositeValue composite = (ApplicationDataCompositeValue)roamingSettings.Values[settingName]; + ApplicationDataCompositeValue composite = (ApplicationDataCompositeValue)localSettings.Values[settingName]; String output; if (composite == null) @@ -75,13 +66,9 @@ void DisplayOutput() OutputTextBlock.Text = output; } - /// - /// Invoked when this page is about to be displayed in a Frame. - /// - /// Event data that describes how this page was reached. The Parameter - /// property is typically used to configure the page. protected override void OnNavigatedTo(NavigationEventArgs e) { + DisplayOutput(); } } } diff --git a/Samples/ApplicationData/cs/Scenario5_DataChangedEvent.xaml.cs b/Samples/ApplicationData/cs/Scenario5_DataChangedEvent.xaml.cs deleted file mode 100644 index f47a74eea6..0000000000 --- a/Samples/ApplicationData/cs/Scenario5_DataChangedEvent.xaml.cs +++ /dev/null @@ -1,95 +0,0 @@ -//********************************************************* -// -// Copyright (c) Microsoft. All rights reserved. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//********************************************************* - -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Navigation; -using SDKTemplate; -using System; -using Windows.Foundation; -using Windows.UI.Core; -using Windows.Storage; - -namespace ApplicationDataSample -{ - /// - /// An empty page that can be used on its own or navigated to within a Frame. - /// - public sealed partial class DataChangedEvent : Page - { - // A pointer back to the main page. This is needed if you want to call methods in MainPage such - // as NotifyUser() - MainPage rootPage = MainPage.Current; - ApplicationData applicationData = null; - ApplicationDataContainer roamingSettings = null; - TypedEventHandler dataChangedHandler = null; - - const string settingName = "userName"; - - public DataChangedEvent() - { - this.InitializeComponent(); - - applicationData = ApplicationData.Current; - roamingSettings = applicationData.RoamingSettings; - - DisplayOutput(); - } - - void SimulateRoaming_Click(Object sender, RoutedEventArgs e) - { - roamingSettings.Values[settingName] = UserName.Text; - - // Simulate roaming by intentionally signaling a data changed event. - applicationData.SignalDataChanged(); - } - - async void DataChangedHandler(Windows.Storage.ApplicationData appData, object o) - { - // DataChangeHandler may be invoked on a background thread, so use the Dispatcher to invoke the UI-related code on the UI thread. - await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => - { - DisplayOutput(); - }); - } - - void DisplayOutput() - { - Object value = roamingSettings.Values[settingName]; - OutputTextBlock.Text = "Name: " + (value == null ? "" : ("\"" + value + "\"")); ; - } - - /// - /// Invoked when this page is about to be displayed in a Frame. - /// - /// Event data that describes how this page was reached. The Parameter - /// property is typically used to configure the page. - protected override void OnNavigatedTo(NavigationEventArgs e) - { - dataChangedHandler = new TypedEventHandler(DataChangedHandler); - applicationData.DataChanged += dataChangedHandler; - } - - /// - /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame. - /// - /// - /// Event data that can be examined by overriding code. The event data is representative - /// of the navigation that will unload the current Page unless canceled. The - /// navigation can potentially be canceled by setting Cancel. - /// - protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) - { - base.OnNavigatingFrom(e); - applicationData.DataChanged -= dataChangedHandler; - dataChangedHandler = null; - } - } -} diff --git a/Samples/ApplicationData/cs/Scenario7_Msappdata.xaml.cs b/Samples/ApplicationData/cs/Scenario5_Msappdata.xaml.cs similarity index 51% rename from Samples/ApplicationData/cs/Scenario7_Msappdata.xaml.cs rename to Samples/ApplicationData/cs/Scenario5_Msappdata.xaml.cs index dc91ae7faa..7bee6542ef 100644 --- a/Samples/ApplicationData/cs/Scenario7_Msappdata.xaml.cs +++ b/Samples/ApplicationData/cs/Scenario5_Msappdata.xaml.cs @@ -1,4 +1,4 @@ -//********************************************************* +//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF @@ -8,41 +8,28 @@ // //********************************************************* -using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; +using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; -using SDKTemplate; using System; using Windows.Storage; -namespace ApplicationDataSample +namespace SDKTemplate { - /// - /// An empty page that can be used on its own or navigated to within a Frame. - /// - public sealed partial class Msappdata : Page + public sealed partial class Scenario5_Msappdata : Page { - // A pointer back to the main page. This is needed if you want to call methods in MainPage such - // as NotifyUser() - MainPage rootPage = MainPage.Current; - - public Msappdata() + public Scenario5_Msappdata() { - this.InitializeComponent(); + InitializeComponent(); } - /// - /// Invoked when this page is about to be displayed in a Frame. - /// - /// Event data that describes how this page was reached. The Parameter - /// property is typically used to configure the page. protected override async void OnNavigatedTo(NavigationEventArgs e) { ApplicationData appData = ApplicationData.Current; + StorageFile sourceFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///assets/appDataLocal.png")); try { - StorageFile sourceFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///assets/appDataLocal.png")); await sourceFile.CopyAsync(appData.LocalFolder); } catch (Exception) @@ -51,9 +38,9 @@ protected override async void OnNavigatedTo(NavigationEventArgs e) // Ignore this error. } + sourceFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///assets/appDataRoaming.png")); try { - StorageFile sourceFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///assets/appDataRoaming.png")); await sourceFile.CopyAsync(appData.RoamingFolder); } catch (Exception) @@ -62,9 +49,9 @@ protected override async void OnNavigatedTo(NavigationEventArgs e) // Ignore this error. } + sourceFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///assets/appDataTemp.png")); try - { - StorageFile sourceFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///assets/appDataTemp.png")); + { await sourceFile.CopyAsync(appData.TemporaryFolder); } catch (Exception) @@ -73,9 +60,9 @@ protected override async void OnNavigatedTo(NavigationEventArgs e) // Ignore this error. } - LocalImage.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appdata:///local/appDataLocal.png")); - RoamingImage.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appdata:///roaming/appDataRoaming.png")); - TempImage.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appdata:///temp/appDataTemp.png")); + LocalImage.Source = new BitmapImage(new Uri("ms-appdata:///local/appDataLocal.png")); + RoamingImage.Source = new BitmapImage(new Uri("ms-appdata:///roaming/appDataRoaming.png")); + TempImage.Source = new BitmapImage(new Uri("ms-appdata:///temp/appDataTemp.png")); } protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) diff --git a/Samples/ApplicationData/cs/Scenario6_ClearScenario.xaml.cs b/Samples/ApplicationData/cs/Scenario6_ClearScenario.xaml.cs new file mode 100644 index 0000000000..0049f6e37b --- /dev/null +++ b/Samples/ApplicationData/cs/Scenario6_ClearScenario.xaml.cs @@ -0,0 +1,37 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +using Windows.UI.Xaml; +using Windows.UI.Xaml.Controls; +using System; + +namespace SDKTemplate +{ + public sealed partial class Scenario6_ClearScenario : Page + { + public Scenario6_ClearScenario() + { + InitializeComponent(); + } + + async void Clear_Click(Object sender, RoutedEventArgs e) + { + try + { + await Windows.Storage.ApplicationData.Current.ClearAsync(); + OutputTextBlock.Text = "ApplicationData has been cleared. Visit the other scenarios to see that their data has been cleared."; + } + catch (Exception) + { + OutputTextBlock.Text = "Unable to clear settings. This can happen when files are in use."; + } + } + } +} diff --git a/Samples/ApplicationData/cs/Scenario6_HighPriority.xaml.cs b/Samples/ApplicationData/cs/Scenario6_HighPriority.xaml.cs deleted file mode 100644 index 5adfc72595..0000000000 --- a/Samples/ApplicationData/cs/Scenario6_HighPriority.xaml.cs +++ /dev/null @@ -1,112 +0,0 @@ -//********************************************************* -// -// Copyright (c) Microsoft. All rights reserved. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//********************************************************* - -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Navigation; -using SDKTemplate; -using System; -using Windows.Foundation; -using Windows.UI.Core; -using Windows.Storage; - -namespace ApplicationDataSample -{ - /// - /// An empty page that can be used on its own or navigated to within a Frame. - /// - public sealed partial class HighPriority : Page - { - // A pointer back to the main page. This is needed if you want to call methods in MainPage such - // as NotifyUser() - MainPage rootPage = MainPage.Current; - ApplicationDataContainer roamingSettings = null; - ApplicationData applicationData = null; - TypedEventHandler dataChangedHandler = null; - - public HighPriority() - { - this.InitializeComponent(); - - applicationData = ApplicationData.Current; - roamingSettings = applicationData.RoamingSettings; - - DisplayOutput(false); - } - - // Guidance for using the HighPriority setting. - // - // Writing to the HighPriority setting enables a developer to store a small amount of - // data that will be roamed out to the cloud with higher priority than other roaming - // data, when possible. - // - // Applications should carefully consider which data should be stored in the - // HighPriority setting. "Context" data such as the user's location within - // media, or their current game-baord and high-score, can make the most sense to - // roam with high priority. By using the HighPriority setting, this information has - // a higher likelihood of being available to the user when they begin to use another - // machine. - // - // Applications should update their HighPriority setting when the user makes - // a significant change to the data it represents. Examples could include changing - // music tracks, turning the page in a book, or finishing a level in a game. - - void IncrementHighPriority_Click(Object sender, RoutedEventArgs e) - { - int counter = Convert.ToInt32(roamingSettings.Values["HighPriority"]); - - roamingSettings.Values["HighPriority"] = counter + 1; - - DisplayOutput(false); - } - - async void DataChangedHandler(Windows.Storage.ApplicationData appData, object o) - { - // DataChangeHandler may be invoked on a background thread, so use the Dispatcher to invoke the UI-related code on the UI thread. - await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => - { - DisplayOutput(true); - }); - } - - void DisplayOutput(bool remoteUpdate) - { - int counter = Convert.ToInt32(roamingSettings.Values["HighPriority"]); - - OutputTextBlock.Text = "Counter: " + counter + (remoteUpdate ? " (updated remotely)" : ""); - } - - /// - /// Invoked when this page is about to be displayed in a Frame. - /// - /// Event data that describes how this page was reached. The Parameter - /// property is typically used to configure the page. - protected override void OnNavigatedTo(NavigationEventArgs e) - { - dataChangedHandler = new TypedEventHandler(DataChangedHandler); - applicationData.DataChanged += dataChangedHandler; - } - - /// - /// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame. - /// - /// - /// Event data that can be examined by overriding code. The event data is representative - /// of the navigation that will unload the current Page unless canceled. The - /// navigation can potentially be canceled by setting Cancel. - /// - protected override void OnNavigatingFrom(NavigatingCancelEventArgs e) - { - base.OnNavigatingFrom(e); - applicationData.DataChanged -= dataChangedHandler; - dataChangedHandler = null; - } - } -} diff --git a/Samples/ApplicationData/cs/Scenario9_SetVersion.xaml.cs b/Samples/ApplicationData/cs/Scenario7_SetVersion.xaml.cs similarity index 71% rename from Samples/ApplicationData/cs/Scenario9_SetVersion.xaml.cs rename to Samples/ApplicationData/cs/Scenario7_SetVersion.xaml.cs index bf1c7185e9..b3ffa987cf 100644 --- a/Samples/ApplicationData/cs/Scenario9_SetVersion.xaml.cs +++ b/Samples/ApplicationData/cs/Scenario7_SetVersion.xaml.cs @@ -1,4 +1,4 @@ -//********************************************************* +//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF @@ -15,30 +15,19 @@ using System; using Windows.Storage; -namespace ApplicationDataSample +namespace SDKTemplate { - /// - /// An empty page that can be used on its own or navigated to within a Frame. - /// - public sealed partial class SetVersion : Page + public sealed partial class Scenario7_SetVersion : Page { - // A pointer back to the main page. This is needed if you want to call methods in MainPage such - // as NotifyUser() - MainPage rootPage = MainPage.Current; - - ApplicationData appData = null; + ApplicationData appData = ApplicationData.Current; const string settingName = "SetVersionSetting"; const string settingValue0 = "Data.v0"; const string settingValue1 = "Data.v1"; - public SetVersion() + public Scenario7_SetVersion() { - this.InitializeComponent(); - - appData = ApplicationData.Current; - - DisplayOutput(); + InitializeComponent(); } void SetVersionHandler0(SetVersionRequest request) @@ -97,13 +86,13 @@ void SetVersionHandler1(SetVersionRequest request) async void SetVersion0_Click(Object sender, RoutedEventArgs e) { - await appData.SetVersionAsync(0, new ApplicationDataSetVersionHandler(SetVersionHandler0)); + await appData.SetVersionAsync(0, SetVersionHandler0); DisplayOutput(); } async void SetVersion1_Click(Object sender, RoutedEventArgs e) { - await appData.SetVersionAsync(1, new ApplicationDataSetVersionHandler(SetVersionHandler1)); + await appData.SetVersionAsync(1, SetVersionHandler1); DisplayOutput(); } @@ -112,13 +101,9 @@ void DisplayOutput() OutputTextBlock.Text = "Version: " + appData.Version; } - /// - /// Invoked when this page is about to be displayed in a Frame. - /// - /// Event data that describes how this page was reached. The Parameter - /// property is typically used to configure the page. protected override void OnNavigatedTo(NavigationEventArgs e) { + DisplayOutput(); } } } diff --git a/Samples/ApplicationData/cs/Scenario8_ClearScenario.xaml.cs b/Samples/ApplicationData/cs/Scenario8_ClearScenario.xaml.cs deleted file mode 100644 index 27f8b7e22d..0000000000 --- a/Samples/ApplicationData/cs/Scenario8_ClearScenario.xaml.cs +++ /dev/null @@ -1,56 +0,0 @@ -//********************************************************* -// -// Copyright (c) Microsoft. All rights reserved. -// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF -// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY -// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR -// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. -// -//********************************************************* - -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; -using Windows.UI.Xaml.Navigation; -using SDKTemplate; -using System; -using Windows.Storage; - -namespace ApplicationDataSample -{ - /// - /// An empty page that can be used on its own or navigated to within a Frame. - /// - public sealed partial class ClearScenario : Page - { - // A pointer back to the main page. This is needed if you want to call methods in MainPage such - // as NotifyUser() - MainPage rootPage = MainPage.Current; - - public ClearScenario() - { - this.InitializeComponent(); - } - - async void Clear_Click(Object sender, RoutedEventArgs e) - { - try - { - await Windows.Storage.ApplicationData.Current.ClearAsync(); - OutputTextBlock.Text = "ApplicationData has been cleared. Visit the other scenarios to see that their data has been cleared."; - } - catch (Exception) - { - OutputTextBlock.Text = "Unable to clear settings. This can happen when files are in use."; - } - } - - /// - /// Invoked when this page is about to be displayed in a Frame. - /// - /// Event data that describes how this page was reached. The Parameter - /// property is typically used to configure the page. - protected override void OnNavigatedTo(NavigationEventArgs e) - { - } - } -} diff --git a/Samples/ApplicationData/cs/SuspensionManager.cs b/Samples/ApplicationData/cs/SuspensionManager.cs deleted file mode 100644 index 0d8abafc74..0000000000 --- a/Samples/ApplicationData/cs/SuspensionManager.cs +++ /dev/null @@ -1,269 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.Serialization; -using System.Text; -using System.Threading.Tasks; -using Windows.ApplicationModel; -using Windows.Storage; -using Windows.Storage.Streams; -using Windows.UI.Xaml; -using Windows.UI.Xaml.Controls; - -namespace SDKTemplate.Common -{ - /// - /// SuspensionManager captures global session state to simplify process lifetime management - /// for an application. Note that session state will be automatically cleared under a variety - /// of conditions and should only be used to store information that would be convenient to - /// carry across sessions, but that should be discarded when an application crashes or is - /// upgraded. - /// - internal sealed class SuspensionManager - { - private static Dictionary _sessionState = new Dictionary(); - private static List _knownTypes = new List(); - private const string sessionStateFilename = "_sessionState.xml"; - - /// - /// Provides access to global session state for the current session. This state is - /// serialized by and restored by - /// , so values must be serializable by - /// and should be as compact as possible. Strings - /// and other self-contained data types are strongly recommended. - /// - public static Dictionary SessionState - { - get { return _sessionState; } - } - - /// - /// List of custom types provided to the when - /// reading and writing session state. Initially empty, additional types may be - /// added to customize the serialization process. - /// - public static List KnownTypes - { - get { return _knownTypes; } - } - - /// - /// Save the current . Any instances - /// registered with will also preserve their current - /// navigation stack, which in turn gives their active an opportunity - /// to save its state. - /// - /// An asynchronous task that reflects when session state has been saved. - public static async Task SaveAsync() - { - try - { - // Save the navigation state for all registered frames - foreach (var weakFrameReference in _registeredFrames) - { - Frame frame; - if (weakFrameReference.TryGetTarget(out frame)) - { - SaveFrameNavigationState(frame); - } - } - - // Serialize the session state synchronously to avoid asynchronous access to shared - // state - MemoryStream sessionData = new MemoryStream(); - DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary), _knownTypes); - serializer.WriteObject(sessionData, _sessionState); - - // Get an output stream for the SessionState file and write the state asynchronously - StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(sessionStateFilename, CreationCollisionOption.ReplaceExisting); - using (Stream fileStream = await file.OpenStreamForWriteAsync()) - { - sessionData.Seek(0, SeekOrigin.Begin); - await sessionData.CopyToAsync(fileStream); - } - } - catch (Exception e) - { - throw new SuspensionManagerException(e); - } - } - - /// - /// Restores previously saved . Any instances - /// registered with will also restore their prior navigation - /// state, which in turn gives their active an opportunity restore its - /// state. - /// - /// An optional key that identifies the type of session. - /// This can be used to distinguish between multiple application launch scenarios. - /// An asynchronous task that reflects when session state has been read. The - /// content of should not be relied upon until this task - /// completes. - public static async Task RestoreAsync(String sessionBaseKey = null) - { - _sessionState = new Dictionary(); - - try - { - // Get the input stream for the SessionState file - StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(sessionStateFilename); - using (IInputStream inStream = await file.OpenSequentialReadAsync()) - { - // Deserialize the Session State - DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary), _knownTypes); - _sessionState = (Dictionary)serializer.ReadObject(inStream.AsStreamForRead()); - } - - // Restore any registered frames to their saved state - foreach (var weakFrameReference in _registeredFrames) - { - Frame frame; - if (weakFrameReference.TryGetTarget(out frame) && (string)frame.GetValue(FrameSessionBaseKeyProperty) == sessionBaseKey) - { - frame.ClearValue(FrameSessionStateProperty); - RestoreFrameNavigationState(frame); - } - } - } - catch (Exception e) - { - throw new SuspensionManagerException(e); - } - } - - private static DependencyProperty FrameSessionStateKeyProperty = - DependencyProperty.RegisterAttached("_FrameSessionStateKey", typeof(String), typeof(SuspensionManager), null); - private static DependencyProperty FrameSessionBaseKeyProperty = - DependencyProperty.RegisterAttached("_FrameSessionBaseKeyParams", typeof(String), typeof(SuspensionManager), null); - private static DependencyProperty FrameSessionStateProperty = - DependencyProperty.RegisterAttached("_FrameSessionState", typeof(Dictionary), typeof(SuspensionManager), null); - private static List> _registeredFrames = new List>(); - - /// - /// Registers a instance to allow its navigation history to be saved to - /// and restored from . Frames should be registered once - /// immediately after creation if they will participate in session state management. Upon - /// registration if state has already been restored for the specified key - /// the navigation history will immediately be restored. Subsequent invocations of - /// will also restore navigation history. - /// - /// An instance whose navigation history should be managed by - /// - /// A unique key into used to - /// store navigation-related information. - /// An optional key that identifies the type of session. - /// This can be used to distinguish between multiple application launch scenarios. - public static void RegisterFrame(Frame frame, String sessionStateKey, String sessionBaseKey = null) - { - if (frame.GetValue(FrameSessionStateKeyProperty) != null) - { - throw new InvalidOperationException("Frames can only be registered to one session state key"); - } - - if (frame.GetValue(FrameSessionStateProperty) != null) - { - throw new InvalidOperationException("Frames must be either be registered before accessing frame session state, or not registered at all"); - } - - if (!string.IsNullOrEmpty(sessionBaseKey)) - { - frame.SetValue(FrameSessionBaseKeyProperty, sessionBaseKey); - sessionStateKey = sessionBaseKey + "_" + sessionStateKey; - } - - // Use a dependency property to associate the session key with a frame, and keep a list of frames whose - // navigation state should be managed - frame.SetValue(FrameSessionStateKeyProperty, sessionStateKey); - _registeredFrames.Add(new WeakReference(frame)); - - // Check to see if navigation state can be restored - RestoreFrameNavigationState(frame); - } - - /// - /// Disassociates a previously registered by - /// from . Any navigation state previously captured will be - /// removed. - /// - /// An instance whose navigation history should no longer be - /// managed. - public static void UnregisterFrame(Frame frame) - { - // Remove session state and remove the frame from the list of frames whose navigation - // state will be saved (along with any weak references that are no longer reachable) - SessionState.Remove((String)frame.GetValue(FrameSessionStateKeyProperty)); - _registeredFrames.RemoveAll((weakFrameReference) => - { - Frame testFrame; - return !weakFrameReference.TryGetTarget(out testFrame) || testFrame == frame; - }); - } - - /// - /// Provides storage for session state associated with the specified . - /// Frames that have been previously registered with have - /// their session state saved and restored automatically as a part of the global - /// . Frames that are not registered have transient state - /// that can still be useful when restoring pages that have been discarded from the - /// navigation cache. - /// - /// Apps may choose to rely on to manage - /// page-specific state instead of working with frame session state directly. - /// The instance for which session state is desired. - /// A collection of state subject to the same serialization mechanism as - /// . - public static Dictionary SessionStateForFrame(Frame frame) - { - var frameState = (Dictionary)frame.GetValue(FrameSessionStateProperty); - - if (frameState == null) - { - var frameSessionKey = (String)frame.GetValue(FrameSessionStateKeyProperty); - if (frameSessionKey != null) - { - // Registered frames reflect the corresponding session state - if (!_sessionState.ContainsKey(frameSessionKey)) - { - _sessionState[frameSessionKey] = new Dictionary(); - } - frameState = (Dictionary)_sessionState[frameSessionKey]; - } - else - { - // Frames that aren't registered have transient state - frameState = new Dictionary(); - } - frame.SetValue(FrameSessionStateProperty, frameState); - } - return frameState; - } - - private static void RestoreFrameNavigationState(Frame frame) - { - var frameState = SessionStateForFrame(frame); - if (frameState.ContainsKey("Navigation")) - { - frame.SetNavigationState((String)frameState["Navigation"]); - } - } - - private static void SaveFrameNavigationState(Frame frame) - { - var frameState = SessionStateForFrame(frame); - frameState["Navigation"] = frame.GetNavigationState(); - } - } - public class SuspensionManagerException : Exception - { - public SuspensionManagerException() - { - } - - public SuspensionManagerException(Exception e) - : base("SuspensionManager failed", e) - { - - } - } -} diff --git a/Samples/ApplicationData/shared/Scenario6_ClearScenario.xaml b/Samples/ApplicationData/shared/Scenario6_ClearScenario.xaml new file mode 100644 index 0000000000..695559c36c --- /dev/null +++ b/Samples/ApplicationData/shared/Scenario6_ClearScenario.xaml @@ -0,0 +1,29 @@ + + + + + + The ClearAsync method clears data from ApplicationData. + + +