Windows 11 Version 22H2 - May 2024 Samples Update

This commit is contained in:
Raymond Chen 2024-05-15 17:00:15 -07:00
Родитель bd31b445b6
Коммит 0db108e9d0
182 изменённых файлов: 1457 добавлений и 15298 удалений

Просмотреть файл

@ -450,16 +450,17 @@ For additional Windows samples, see [Windows on GitHub](http://microsoft.github.
<tr>
<td><a href="Samples/Personalization">Lock screen personalization</a></td>
<td><a href="Samples/MicrosoftPassport">Microsoft Passport and Windows Hello</a></td>
<td><a href="Samples/SmartCard">Smart cards</a></td>
<td><a href="Samples/PersonalDataEncryption">Personal Data Encryption</a></td>
</tr>
<tr>
<td><a href="Samples/SmartCard">Smart cards</a></td>
<td><a href="Samples/UserInfo">User information</a></td>
<td><a href="Samples/UserCertificateStore">UserCertificateStore</a></td>
<td><a href="Samples/UserConsentVerifier">UserConsentVerifier</a></td>
</tr>
<tr>
<td><a href="Samples/WebAccountManagement">Web account management</a></td>
<td><a href="Samples/WebAuthenticationBroker">WebAuthenticationBroker</a></td>
<td><a href="Samples/UserConsentVerifier">UserConsentVerifier</a></td>
</tr>
</table>

Просмотреть файл

@ -27,68 +27,66 @@ and track when the location changes in various ways.
After obtaining access to the user's location, an app can
* Retrieve the current location.
* Receiving events when the location changes.
* Receiving events when the device has entered or exited locations of interest.
* Receiving events when the device has spent significant time in a location (a "visit").
- Retrieve the current location.
- Receiving events when the location changes.
- Receiving events when the device has entered or exited locations of interest.
- Receiving events when the device has spent significant time in a location (a "visit").
> **Note:** This sample is part of a large collection of UWP feature samples.
> **Note:** This sample is part of a large collection of UWP feature samples.
> You can download this sample as a standalone ZIP file
> [from docs.microsoft.com](https://docs.microsoft.com/samples/microsoft/windows-universal-samples/geolocation/),
> or you can download the entire collection as a single
> [ZIP file](https://github.com/Microsoft/Windows-universal-samples/archive/master.zip), but be
> sure to unzip everything to access shared dependencies. For more info on working with the ZIP file,
> the samples collection, and GitHub, see [Get the UWP samples from GitHub](https://aka.ms/ovu2uq).
> For more samples, see the [Samples portal](https://aka.ms/winsamples) on the Windows Dev Center.
> [ZIP file](https://github.com/Microsoft/Windows-universal-samples/archive/master.zip), but be
> sure to unzip everything to access shared dependencies. For more info on working with the ZIP file,
> the samples collection, and GitHub, see [Get the UWP samples from GitHub](https://aka.ms/ovu2uq).
> For more samples, see the [Samples portal](https://aka.ms/winsamples) on the Windows Dev Center.
This sample also shows how to:
- **Use a [geofence](http://msdn.microsoft.com/library/windows/apps/dn263744):** Receive notifications when the user's device has entered or left an area of interest.
- **Handle changes in location permissions**: Register for the Geolocator's StatusChanged event and use the [StatusChangedEventArgs](http://msdn.microsoft.com/library/windows/apps/br225600) to determine the current position status.
- **Get location from a background task**
- **Handle geofencing events from a background task**
- **Handle geovisit events from a background task**
- **Obtain satellite data:** When available, use the [GeocoordinateSatelliteData](http://msdn.microsoft.com/library/windows/apps/jj635260) class to obtain additional information on the quality of the satellite based location data.
- **Display a toast:** Notify the user when a geofencing event has occurred in the background.
- **Refresh geofence binding:** Refresh the binding on resume and after removal of a geofence. Note that removal requires subscribing to removal events if a geofence is set as single use or a duration is set.
- **Use a [geofence](http://msdn.microsoft.com/library/windows/apps/dn263744):** Receive notifications when the user's device has entered or left an area of interest.
- **Handle changes in location permissions**: Register for the Geolocator's StatusChanged event and use the [StatusChangedEventArgs](http://msdn.microsoft.com/library/windows/apps/br225600) to determine the current position status.
- **Get location from a background task**
- **Handle geofencing events from a background task**
- **Handle geovisit events from a background task**
- **Obtain satellite data:** When available, use the [GeocoordinateSatelliteData](http://msdn.microsoft.com/library/windows/apps/jj635260) class to obtain additional information on the quality of the satellite based location data.
- **Display a toast:** Notify the user when a geofencing event has occurred in the background.
- **Refresh geofence binding:** Refresh the binding on resume and after removal of a geofence. Note that removal requires subscribing to removal events if a geofence is set as single use or a duration is set.
- **Request access to the user's location:** Request access to the user's location using the RequestAccessAsync method. Important: call the RequestAccessAsync before accessing the user's location. At that time, your app must be in the foreground and RequestAccessAsync must be called from the UI thread. Until the user grants your app permission to their location, your app can't access location data.
- **Track when the user visits a location:** Poll for or receive notifications when the user spends significant time in a location.
- **Track when the user visits a location:** Poll for or receive notifications when the user spends significant time in a location.
- **Help the user change location settings:** Link to location privacy settings from your app if the user revokes access to location while your app is in the foreground. Call the LaunchUriAsync method with the URI "ms-settings://privacy/location".
Geofences need to be created in the Foreground Geofencing scenario (Scenario 4) and then you can go to Background Geofencing scenario (Scenario 5) to register for background geofencing events.
Geofences need to be created in the foreground geofencing scenario (Scenario 4) and then you can go to background geofencing scenario (Scenario 5) to register for background geofencing events.
The Geolocation sample formats and parses time and dates in the en-US locale using the Gregorian calendar and 24-hour clock. To help other locales in entering data the edit fields have a format example shown below the control. For example, Start Time would be entered mm/dd/yyyy hh:mm:ss format. February 2, 2014 at 10:34 pm would be written 2/2/2014 22:34:00. For the Dwell Time and Duration the format is dd:hh:mm:ss so a time span of 7 days, 23 hours, 45 minutes and 55 seconds would be written as 7:23:45:55.
The Geolocation sample formats and parses time and dates in the en-US locale using the Gregorian calendar and 24-hour clock. To help other locales in entering data the edit fields have a format example shown below the control. For example, Start Time would be entered mm/dd/yyyy hh:mm:ss format. February 2, 2014 at 10:34 pm would be written 2/2/2014 22:34:00. For the Dwell Time and Duration the format is dd:hh:mm:ss so a time span of 7 days, 23 hours, 45 minutes and 55 seconds would be written as 7:23:45:55.
### Declaring the Location capability
## Declaring the Location capability
This sample requires that location capability be set in the *Package.appxmanifest* file to allow the app to access location at runtime. The capability can be set in the app manifest using Microsoft Visual Studio.
## Related topics
### Conceptual
* [Get current location](https://msdn.microsoft.com/library/windows/apps/mt219698)
* [Guidelines for location-aware apps](https://msdn.microsoft.com/library/windows/apps/hh465148)
- [Get current location](https://msdn.microsoft.com/library/windows/apps/mt219698)
- [Guidelines for location-aware apps](https://msdn.microsoft.com/library/windows/apps/hh465148)
### Reference
* [Windows.Devices.Geolocation](http://msdn.microsoft.com/library/windows/apps/br225603)
* [Windows.Devices.Geolocation.Geofencing](https://msdn.microsoft.com/library/windows/apps/dn263744)
- [Windows.Devices.Geolocation](http://msdn.microsoft.com/library/windows/apps/br225603)
- [Windows.Devices.Geolocation.Geofencing](https://msdn.microsoft.com/library/windows/apps/dn263744)
### Related samples
* [Traffic App sample](https://github.com/microsoft/windows-appsample-trafficapp/)
* [Lunch Scheduler app sample](https://github.com/Microsoft/Windows-appsample-lunch-scheduler)
* [Geolocation sample](/archived/Geolocation/) for C++/CX and JavaScript (archived)
- [Traffic App sample](https://github.com/microsoft/windows-appsample-trafficapp/)
- [Lunch Scheduler app sample](https://github.com/Microsoft/Windows-appsample-lunch-scheduler)
## System requirements
* Windows 10
- Requires Windows SDK 10.0.22621.0 to build and Windows 10 to run.
## Build the sample
1. If you download the samples ZIP, be sure to unzip the entire archive, not just the folder with the sample you want to build.
1. If you download the samples ZIP, be sure to unzip the entire archive, not just the folder with the sample you want to build.
2. Start Microsoft Visual Studio and select **File** \> **Open** \> **Project/Solution**.
3. Starting in the folder where you unzipped the samples, go to the Samples subfolder, then the subfolder for this specific sample, then the subfolder for your preferred language (C++, C#, or JavaScript). Double-click the Visual Studio Solution (.sln) file.
4. Press Ctrl+Shift+B, or select **Build** \> **Build Solution**.
@ -99,8 +97,8 @@ The next steps depend on whether you just want to deploy the sample or you want
### Deploying the sample
- Select Build > Deploy Solution.
- Select Build > Deploy Solution.
### Deploying and running the sample
- To debug the sample and then run it, press F5 or select Debug > Start Debugging. To run the sample without debugging, press Ctrl+F5 or selectDebug > Start Without Debugging.
- To debug the sample and then run it, press F5 or select Debug > Start Debugging. To run the sample without debugging, press Ctrl+F5 or selectDebug > Start Without Debugging.

Просмотреть файл

@ -12,6 +12,7 @@
#include "pch.h"
#include "Scenario1_TrackPosition.h"
#include "Scenario1_TrackPosition.g.cpp"
#include "SampleConfiguration.h"
using namespace winrt;
using namespace winrt::Windows::Devices::Geolocation;
@ -173,6 +174,7 @@ namespace winrt::SDKTemplate::implementation
ScenarioOutput_Latitude().Text(L"No data");
ScenarioOutput_Longitude().Text(L"No data");
ScenarioOutput_Accuracy().Text(L"No data");
ScenarioOutput_Source().Text(L"No data");
ScenarioOutput_IsRemoteSource().Text(L"No data");
}
else
@ -180,6 +182,7 @@ namespace winrt::SDKTemplate::implementation
ScenarioOutput_Latitude().Text(to_hstring(position.Coordinate().Point().Position().Latitude));
ScenarioOutput_Longitude().Text(to_hstring(position.Coordinate().Point().Position().Longitude));
ScenarioOutput_Accuracy().Text(to_hstring(position.Coordinate().Accuracy()));
ScenarioOutput_Source().Text(to_hstring(position.Coordinate().PositionSource()));
ScenarioOutput_IsRemoteSource().Text(to_hstring(position.Coordinate().IsRemoteSource()));
}
}

Просмотреть файл

@ -21,6 +21,30 @@
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<NoWarn>;2008</NoWarn>
<NoStdLib>true</NoStdLib>
<DebugType>full</DebugType>
<PlatformTarget>ARM64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM64'">
<OutputPath>bin\ARM64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<NoStdLib>true</NoStdLib>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM\Debug\</OutputPath>
@ -53,7 +77,6 @@
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
@ -64,7 +87,6 @@
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
@ -194,6 +216,9 @@
<Content Include="$(SharedContentDir)\media\smalltile-sdk.png">
<Link>Assets\smallTile-sdk.png</Link>
</Content>
<Content Include="$(SharedContentDir)\media\badge-logo.png">
<Link>Assets\badge-logo.png</Link>
</Content>
<Content Include="$(SharedContentDir)\media\splash-sdk.png">
<Link>Assets\splash-sdk.png</Link>
</Content>
@ -218,12 +243,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>5.0.0</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>5.0.0</Version>
<Version>6.2.14</Version>
</PackageReference>
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' ">
@ -237,4 +257,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

Просмотреть файл

@ -10,9 +10,11 @@ EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM
Debug|ARM64 = Debug|ARM64
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|ARM = Release|ARM
Release|ARM64 = Release|ARM64
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
@ -20,6 +22,9 @@ Global
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Debug|ARM.ActiveCfg = Debug|ARM
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Debug|ARM.Build.0 = Debug|ARM
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Debug|ARM.Deploy.0 = Debug|ARM
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Debug|ARM64.ActiveCfg = Debug|ARM64
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Debug|ARM64.Build.0 = Debug|ARM64
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Debug|ARM64.Deploy.0 = Debug|ARM64
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Debug|x64.ActiveCfg = Debug|x64
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Debug|x64.Build.0 = Debug|x64
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Debug|x64.Deploy.0 = Debug|x64
@ -29,6 +34,9 @@ Global
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Release|ARM.ActiveCfg = Release|ARM
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Release|ARM.Build.0 = Release|ARM
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Release|ARM.Deploy.0 = Release|ARM
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Release|ARM64.ActiveCfg = Release|ARM64
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Release|ARM64.Build.0 = Release|ARM64
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Release|ARM64.Deploy.0 = Release|ARM64
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Release|x64.ActiveCfg = Release|x64
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Release|x64.Build.0 = Release|x64
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Release|x64.Deploy.0 = Release|x64
@ -37,12 +45,16 @@ Global
{C214806D-57CA-5528-89FA-B9A7DEB22DFF}.Release|x86.Deploy.0 = Release|x86
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Debug|ARM.ActiveCfg = Debug|ARM
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Debug|ARM.Build.0 = Debug|ARM
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Debug|ARM64.ActiveCfg = Debug|ARM64
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Debug|ARM64.Build.0 = Debug|ARM64
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Debug|x64.ActiveCfg = Debug|x64
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Debug|x64.Build.0 = Debug|x64
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Debug|x86.ActiveCfg = Debug|x86
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Debug|x86.Build.0 = Debug|x86
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Release|ARM.ActiveCfg = Release|ARM
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Release|ARM.Build.0 = Release|ARM
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Release|ARM64.ActiveCfg = Release|ARM64
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Release|ARM64.Build.0 = Release|ARM64
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Release|x64.ActiveCfg = Release|x64
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Release|x64.Build.0 = Release|x64
{5A7BDE18-030E-5DC9-B9A2-70EA568A6E9D}.Release|x86.ActiveCfg = Release|x86

Просмотреть файл

@ -17,7 +17,7 @@
<Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="Geolocation.App">
<uap:VisualElements DisplayName="Geolocation C# Sample" Square150x150Logo="Assets\SquareTile-sdk.png" Square44x44Logo="Assets\SmallTile-sdk.png" Description="Geolocation C# Sample" BackgroundColor="#00b2f0">
<uap:SplashScreen Image="Assets\Splash-sdk.png" />
<uap:LockScreen Notification="badge" BadgeLogo="Assets\smalltile-sdk.png" />
<uap:LockScreen Notification="badge" BadgeLogo="Assets\badge-logo.png" />
</uap:VisualElements>
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTask.GeofenceBackgroundTask">
@ -41,4 +41,4 @@
<Capabilities>
<DeviceCapability Name="location" />
</Capabilities>
</Package>
</Package>

Просмотреть файл

@ -197,6 +197,7 @@ namespace SDKTemplate
ScenarioOutput_Latitude.Text = "No data";
ScenarioOutput_Longitude.Text = "No data";
ScenarioOutput_Accuracy.Text = "No data";
ScenarioOutput_Source.Text = "No data";
ScenarioOutput_IsRemoteSource.Text = "No data";
}
else
@ -204,6 +205,7 @@ namespace SDKTemplate
ScenarioOutput_Latitude.Text = position.Coordinate.Point.Position.Latitude.ToString();
ScenarioOutput_Longitude.Text = position.Coordinate.Point.Position.Longitude.ToString();
ScenarioOutput_Accuracy.Text = position.Coordinate.Accuracy.ToString();
ScenarioOutput_Source.Text = position.Coordinate.PositionSource.ToString();
ScenarioOutput_IsRemoteSource.Text = position.Coordinate.IsRemoteSource.ToString();
}
}

Просмотреть файл

@ -21,6 +21,30 @@
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<NoWarn>;2008</NoWarn>
<NoStdLib>true</NoStdLib>
<DebugType>full</DebugType>
<PlatformTarget>ARM64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM64'">
<OutputPath>bin\ARM64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<NoStdLib>true</NoStdLib>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
<PlatformTarget>ARM</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
@ -56,7 +80,6 @@
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<PlatformTarget>x64</PlatformTarget>
@ -68,7 +91,6 @@
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
@ -108,7 +130,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>5.0.0</Version>
<Version>6.2.14</Version>
</PackageReference>
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' ">
@ -122,4 +144,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

Просмотреть файл

@ -36,17 +36,20 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="0" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Status: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="1" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Latitude: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="2" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Longitude: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="3" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Accuracy: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="4" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="IsRemoteSource: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="4" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Source: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="5" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="IsRemoteSource: " />
<TextBlock x:Name="ScenarioOutput_Status" TextWrapping="Wrap" Grid.Row="0" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Unknown" />
<TextBlock x:Name="ScenarioOutput_Latitude" TextWrapping="Wrap" Grid.Row="1" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Longitude" TextWrapping="Wrap" Grid.Row="2" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Accuracy" TextWrapping="Wrap" Grid.Row="3" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_IsRemoteSource" TextWrapping="Wrap" Grid.Row="4" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Source" TextWrapping="Wrap" Grid.Row="4" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_IsRemoteSource" TextWrapping="Wrap" Grid.Row="5" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
</Grid>
<TextBlock TextWrapping="Wrap" x:Name="LocationDisabledMessage" Margin="0,10,0,0" FontStyle="Italic" Visibility="Collapsed">
Application is not able to get location data. Go to

Просмотреть файл

@ -2,7 +2,6 @@
page_type: sample
languages:
- csharp
- cpp
- cppwinrt
products:
- windows
@ -33,28 +32,27 @@ This sample also demonstrates how to register for network connectivity change ev
Apps can subscribe to the events instead of building their
own logic to track network connectivity changes.
> **Note:** This sample is part of a large collection of UWP feature samples.
> **Note:** This sample is part of a large collection of UWP feature samples.
> You can download this sample as a standalone ZIP file
> [from docs.microsoft.com](https://docs.microsoft.com/samples/microsoft/windows-universal-samples/networkingconnectivity/),
> or you can download the entire collection as a single
> [ZIP file](https://github.com/Microsoft/Windows-universal-samples/archive/main.zip), but be
> sure to unzip everything to access shared dependencies. For more info on working with the ZIP file,
> the samples collection, and GitHub, see [Get the UWP samples from GitHub](https://aka.ms/ovu2uq).
> For more samples, see the [Samples portal](https://aka.ms/winsamples) on the Windows Dev Center.
> [ZIP file](https://github.com/Microsoft/Windows-universal-samples/archive/main.zip), but be
> sure to unzip everything to access shared dependencies. For more info on working with the ZIP file,
> the samples collection, and GitHub, see [Get the UWP samples from GitHub](https://aka.ms/ovu2uq).
> For more samples, see the [Samples portal](https://aka.ms/winsamples) on the Windows Dev Center.
### Declaring the internetClient capability
## Declaring the internetClient capability
This sample requires that internetClient capability be set in the *Package.appxmanifest* file to allow the app to access the Internet connection at runtime.
The capability can be set in the app manifest using Microsoft Visual Studio.
## System requirements
* Windows 10
- Requires Windows SDK 10.0.22621.0 to build and Windows 10 to run.
## Build the sample
1. If you download the samples ZIP, be sure to unzip the entire archive, not just the folder with the sample you want to build.
1. If you download the samples ZIP, be sure to unzip the entire archive, not just the folder with the sample you want to build.
2. Start Microsoft Visual Studio and select **File** \> **Open** \> **Project/Solution**.
3. Starting in the folder where you unzipped the samples, go to the Samples subfolder, then the subfolder for this specific sample, then the subfolder for your preferred language (C++, C#, or JavaScript). Double-click the Visual Studio Solution (.sln) file.
4. Press Ctrl+Shift+B or select **Build** \> **Build Solution**.
@ -65,8 +63,8 @@ The next steps depend on whether you just want to deploy the sample or you want
### Deploying the sample
- Select Build > Deploy Solution.
- Select Build > Deploy Solution.
### Debugging and running the sample
- To debug the sample and then run it, press F5 or select Debug > Start Debugging. To run the sample without debugging, press Ctrl+F5 or select Debug > Start Without Debugging.
- To debug the sample and then run it, press F5 or select Debug > Start Debugging. To run the sample without debugging, press Ctrl+F5 or select Debug > Start Without Debugging.

Просмотреть файл

@ -37,7 +37,7 @@
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM64'">
<OutputPath>bin\ARM64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UAP;CODE_ANALYSIS</DefineConstants>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<NoStdLib>true</NoStdLib>
@ -185,7 +185,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>5.0.0</Version>
<Version>6.2.14</Version>
</PackageReference>
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' ">
@ -199,4 +199,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

Просмотреть файл

@ -1,65 +1,62 @@
---
topic: sample
page_type: sample
languages:
- csharp
- cplusplus
- cppwinrt
products:
- windows
- windows-uwp
urlFragment: CallerID
urlFragment: PersonalDataEncryption
extendedZipContent:
- path: SharedContent
target: SharedContent
- path: LICENSE
target: LICENSE
description: "Shows how to set Call Origin information for an unrecognized incoming call."
description: "Demonstrates the usage of Personal Data Encryption (Windows Data Protection)."
---
<!---
category: Communications
-->
# Personal Data Encryption sample
# Caller ID sample
Shows how to set Call Origin information for an unrecognized incoming call.
Shows how to use [Personal Data Encryption](https://learn.microsoft.com/windows/security/operating-system-security/data-protection/personal-data-encryption/)
for protecting user files and memory buffers.
> **Note:** This sample is part of a large collection of UWP feature samples.
> You can download this sample as a standalone ZIP file
> [from docs.microsoft.com](https://docs.microsoft.com/samples/microsoft/windows-universal-samples/callerid/),
> [from docs.microsoft.com](https://docs.microsoft.com/samples/microsoft/windows-universal-samples/resizeappview/),
> or you can download the entire collection as a single
> [ZIP file](https://github.com/Microsoft/Windows-universal-samples/archive/master.zip), but be
> sure to unzip everything to access shared dependencies. For more info on working with the ZIP file,
> the samples collection, and GitHub, see [Get the UWP samples from GitHub](https://aka.ms/ovu2uq).
> For more samples, see the [Samples portal](https://aka.ms/winsamples) on the Windows Dev Center.
Specifically, this sample shows how to:
- Register a Caller ID background task to be triggered when an unrecognized incoming call arrives.
The task sets the call location, category, category description, and display name of the call.
- Display the system UI to let the user choose the active Caller ID app.
- Determine whether the app is the the active Caller ID app.
Personal Data Encryption can protect data either while a user is signed ("Level 1" or "L1") out or while a system is locked ("Level 2" or "L2").
See the Package.appxmanifest file for the extensions and capabilities a Caller ID app must declare.
The sample shows the following:
**Note** The Windows universal samples require Visual Studio to build and Windows 10 to execute.
- Marking a folder so that all new files are protected at a particular level, or removing protection.
- Protecting a file at a particular level, or removing protection.
- Protecting a memory buffer at a particular level, or removing protection.
To obtain information about Windows 10 development, go to the [Windows Dev Center](http://go.microsoft.com/fwlink/?LinkID=532421)
**Note** The Windows universal samples require Visual Studio to build and Windows 11 to execute.
To obtain information about Windows development, go to the [Windows Dev Center](http://go.microsoft.com/fwlink/?LinkID=532421)
To obtain information about Microsoft Visual Studio and the tools for developing Windows apps, go to [Visual Studio](http://go.microsoft.com/fwlink/?LinkID=532422)
## Related topics
### Reference
[Windows.ApplicationModel.Calls.Provider namespace](https://msdn.microsoft.com/library/windows/apps/windows.applicationmodel.calls.provider.aspx)
[UserDataProtectionManager class](https://learn.microsoft.com/en-us/uwp/api/windows.security.dataprotection.userdataprotectionmanager)
[PhoneCallOriginManager class](https://msdn.microsoft.com/library/windows/apps/windows.applicationmodel.calls.provider.phonecalloriginmanager.aspx)
### Related samples
[PhoneCallOrigin class](https://msdn.microsoft.com/library/windows/apps/windows.applicationmodel.calls.provider.phonecallorigin.aspx)
* [EnterpriseDataProtection](/Samples/EnterpriseDataProtection)
## System requirements
**Client:** Not Supported
**Server:** Not Supported
**Phone:** Windows 10
* Windows 11 version 22H2 or higher
## Build the sample
@ -78,4 +75,5 @@ The next steps depend on whether you just want to deploy the sample or you want
### Deploying and running the sample
- To debug the sample and then run it, press F5 or select Debug > Start Debugging. To run the sample without debugging, press Ctrl+F5 or selectDebug > Start Without Debugging.
- To debug the sample and then run it, press F5 or select Debug > Start Debugging. To run the sample without debugging, press Ctrl+F5 or select Debug > Start Without Debugging.
- In order for the sample to exercise Personal Data Encryption, [it must be configured](https://learn.microsoft.com/windows/security/operating-system-security/data-protection/personal-data-encryption/configure).

Просмотреть файл

@ -0,0 +1,39 @@
<?xml version='1.0' encoding='utf-8'?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
IgnorableNamespaces="uap mp"
>
<Identity Name="Microsoft.SDKSamples.PersonalDataEncryption.CPP" Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" Version="1.0.0.0"/>
<mp:PhoneIdentity PhoneProductId="30bbe50c-5df6-4891-a34d-3652978d7456" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>Personal Data Encryption C++/WinRT Sample</DisplayName>
<PublisherDisplayName>Microsoft Corporation</PublisherDisplayName>
<Logo>Assets\storelogo-sdk.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.18362.0" MaxVersionTested="10.0.22000.0"/>
</Dependencies>
<Resources>
<Resource Language="x-generate"/>
</Resources>
<Applications>
<Application Id="PersonalDataEncryption.App" Executable="$targetnametoken$.exe" EntryPoint="PersonalDataEncryption.App">
<uap:VisualElements
DisplayName="Personal Data Encryption C++/WinRT Sample"
Square150x150Logo="Assets\squareTile-sdk.png"
Square44x44Logo="Assets\smallTile-sdk.png"
Description="Personal Data Encryption C++/WinRT Sample"
BackgroundColor="#00B2F0"
>
<uap:SplashScreen Image="Assets\splash-sdk.png"/>
<uap:DefaultTile>
<uap:ShowNameOnTiles>
<uap:ShowOn Tile="square150x150Logo"/>
</uap:ShowNameOnTiles>
</uap:DefaultTile>
</uap:VisualElements>
</Application>
</Applications>
</Package>

Просмотреть файл

@ -0,0 +1,40 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27004.2006
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "PersonalDataEncryption", "PersonalDataEncryption.vcxproj", "{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Debug|ARM = Debug|ARM
Release|ARM = Release|ARM
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Debug|ARM.ActiveCfg = Debug|ARM
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Debug|ARM.Build.0 = Debug|ARM
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Debug|ARM.Deploy.0 = Debug|ARM
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Debug|x64.ActiveCfg = Debug|x64
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Debug|x64.Build.0 = Debug|x64
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Debug|x64.Deploy.0 = Debug|x64
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Debug|x86.ActiveCfg = Debug|Win32
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Debug|x86.Build.0 = Debug|Win32
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Debug|x86.Deploy.0 = Debug|Win32
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Release|ARM.ActiveCfg = Release|ARM
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Release|ARM.Build.0 = Release|ARM
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Release|ARM.Deploy.0 = Release|ARM
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Release|x64.ActiveCfg = Release|x64
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Release|x64.Build.0 = Release|x64
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Release|x64.Deploy.0 = Release|x64
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Release|x86.ActiveCfg = Release|Win32
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Release|x86.Build.0 = Release|Win32
{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}.Release|x86.Deploy.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Просмотреть файл

@ -0,0 +1,188 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="packages\Microsoft.Windows.CppWinRT.2.0.240405.15\build\native\Microsoft.Windows.CppWinRT.props" Condition="Exists('packages\Microsoft.Windows.CppWinRT.2.0.240405.15\build\native\Microsoft.Windows.CppWinRT.props')" />
<PropertyGroup>
<SharedContentDir>$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), LICENSE))\SharedContent</SharedContentDir>
</PropertyGroup>
<PropertyGroup Label="Globals">
<CppWinRTEnabled>true</CppWinRTEnabled>
<MinimalCoreWin>true</MinimalCoreWin>
<ProjectGuid>{3180E6C1-8D0E-4120-B794-AEFF6D6055B9}</ProjectGuid>
<ProjectName>PersonalDataEncryption</ProjectName>
<RootNamespace>SDKTemplate</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<MinimumVisualStudioVersion>15.0</MinimumVisualStudioVersion>
<AppContainerApplication>true</AppContainerApplication>
<ApplicationType>Windows Store</ApplicationType>
<ApplicationTypeRevision>10.0</ApplicationTypeRevision>
<WindowsTargetPlatformVersion>10.0.22000.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>$(WindowsTargetPlatformVersion)</WindowsTargetPlatformMinVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Debug'" Label="Configuration">
<UseDebugLibraries>true</UseDebugLibraries>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Release'" Label="Configuration">
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<IncludePath>$(VC_IncludePath);$(UniversalCRT_IncludePath);$(WindowsSDK_IncludePath);$(SharedContentDir)\cppwinrt</IncludePath>
<CppWinRTOptimized>true</CppWinRTOptimized>
</PropertyGroup>
<ItemDefinitionGroup>
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<WarningLevel>Level4</WarningLevel>
<AdditionalOptions>%(AdditionalOptions) /bigobj</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Debug'">
<ClCompile>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)'=='Release'">
<ClCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="$(SharedContentDir)\cppwinrt\App.h">
<DependentUpon>$(SharedContentDir)\xaml\App.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="$(SharedContentDir)\cppwinrt\MainPage.h">
<DependentUpon>$(SharedContentDir)\xaml\MainPage.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="SampleConfiguration.h" />
<ClInclude Include="Scenario1_Files.h">
<DependentUpon>..\shared\Scenario1_Files.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="Scenario2_Memory.h">
<DependentUpon>..\shared\Scenario2_Memory.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="pch.h" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="$(SharedContentDir)\xaml\App.xaml">
<SubType>Designer</SubType>
</ApplicationDefinition>
<Page Include="$(SharedContentDir)\xaml\MainPage.xaml">
<SubType>Designer</SubType>
</Page>
<Page Include="..\shared\Scenario1_Files.xaml" />
<Page Include="..\shared\Scenario2_Memory.xaml" />
<Page Include="$(SharedContentDir)\xaml\Styles.xaml">
<Link>Styles\Styles.xaml</Link>
</Page>
</ItemGroup>
<ItemGroup>
<ClCompile Include="$(SharedContentDir)\cppwinrt\App.cpp">
<DependentUpon>$(SharedContentDir)\xaml\App.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="$(SharedContentDir)\cppwinrt\MainPage.cpp">
<DependentUpon>$(SharedContentDir)\xaml\MainPage.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="SampleConfiguration.cpp" />
<ClCompile Include="Scenario1_Files.cpp">
<DependentUpon>..\shared\Scenario1_Files.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="Scenario2_Memory.cpp">
<DependentUpon>..\shared\Scenario2_Memory.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="pch.cpp">
<PrecompiledHeader>Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="$(GeneratedFilesDir)module.g.cpp">
<DependentUpon>Project.idl</DependentUpon>
</ClCompile>
</ItemGroup>
<ItemGroup>
<Midl Include="$(SharedContentDir)\cppwinrt\MainPage.idl">
<DependentUpon>$(SharedContentDir)\xaml\MainPage.xaml</DependentUpon>
</Midl>
<Midl Include="Project.idl" />
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest">
<SubType>Designer</SubType>
</AppxManifest>
</ItemGroup>
<ItemGroup>
<Image Include="$(SharedContentDir)\media\microsoft-sdk.png">
<Link>Assets\microsoft-sdk.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\smalltile-sdk.png">
<Link>Assets\smallTile-sdk.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\splash-sdk.png">
<Link>Assets\splash-sdk.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\squaretile-sdk.png">
<Link>Assets\squareTile-sdk.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\storelogo-sdk.png">
<Link>Assets\storeLogo-sdk.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\tile-sdk.png">
<Link>Assets\tile-sdk.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\windows-sdk.png">
<Link>Assets\windows-sdk.png</Link>
</Image>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="packages\Microsoft.Windows.CppWinRT.2.0.240405.15\build\native\Microsoft.Windows.CppWinRT.targets" Condition="Exists('packages\Microsoft.Windows.CppWinRT.2.0.240405.15\build\native\Microsoft.Windows.CppWinRT.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>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}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('packages\Microsoft.Windows.CppWinRT.2.0.240405.15\build\native\Microsoft.Windows.CppWinRT.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Microsoft.Windows.CppWinRT.2.0.240405.15\build\native\Microsoft.Windows.CppWinRT.props'))" />
<Error Condition="!Exists('packages\Microsoft.Windows.CppWinRT.2.0.240405.15\build\native\Microsoft.Windows.CppWinRT.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Microsoft.Windows.CppWinRT.2.0.240405.15\build\native\Microsoft.Windows.CppWinRT.targets'))" />
</Target>
</Project>

Просмотреть файл

@ -1,47 +1,41 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Assets">
<UniqueIdentifier>80bfd669-aa83-4537-9611-027cffe0d8af</UniqueIdentifier>
<UniqueIdentifier>4416d50a-7676-4d0a-9b2c-91ff70c6047f</UniqueIdentifier>
<Extensions>bmp;fbx;gif;jpg;jpeg;tga;tiff;tif;png</Extensions>
</Filter>
<Filter Include="Styles">
<UniqueIdentifier>{c6978fb6-bc64-498d-97c8-f5b53997e54e}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="$(SharedContentDir)\xaml\App.xaml" />
<Page Include="..\shared\Scenario1_Files.xaml" />
<Page Include="..\shared\Scenario2_Memory.xaml" />
<Page Include="$(SharedContentDir)\xaml\Styles.xaml" />
<Page Include="$(SharedContentDir)\xaml\MainPage.xaml" />
</ItemGroup>
<ItemGroup>
<Midl Include="Project.idl" />
<Midl Include="$(SharedContentDir)\cppwinrt\MainPage.idl" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="$(SharedContentDir)\cpp\App.xaml.cpp" />
<ClCompile Include="$(SharedContentDir)\cpp\MainPage.xaml.cpp" />
<ClCompile Include="pch.cpp" />
<ClCompile Include="Scenario1_Files.cpp" />
<ClCompile Include="Scenario2_Memory.cpp" />
<ClCompile Include="$(GeneratedFilesDir)module.g.cpp" />
<ClCompile Include="SampleConfiguration.cpp" />
<ClCompile Include="Scenario2_ShortName.xaml.cpp" />
<ClCompile Include="Scenario3_ShortName.xaml.cpp" />
<ClCompile Include="Scenario1_ToggleRadios.xaml.cpp" />
<ClCompile Include="RadioModel.cpp" />
<ClCompile Include="$(SharedContentDir)\cppwinrt\App.cpp" />
<ClCompile Include="$(SharedContentDir)\cppwinrt\MainPage.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="pch.h" />
<ClInclude Include="$(SharedContentDir)\cpp\App.xaml.h" />
<ClInclude Include="$(SharedContentDir)\cpp\MainPage.xaml.h" />
<ClInclude Include="Scenario1_Files.h" />
<ClInclude Include="Scenario2_Memory.h" />
<ClInclude Include="SampleConfiguration.h" />
<ClInclude Include="Scenario2_ShortName.xaml.h" />
<ClInclude Include="Scenario3_ShortName.xaml.h" />
<ClInclude Include="Scenario1_ToggleRadios.xaml.h" />
<ClInclude Include="RadioModel.h" />
<ClInclude Include="$(SharedContentDir)\cppwinrt\App.h" />
<ClInclude Include="$(SharedContentDir)\cppwinrt\MainPage.h" />
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest" />
</ItemGroup>
<ItemGroup>
<Page Include="$(SharedContentDir)\cpp\MainPage.xaml" />
<Page Include="$(SharedContentDir)\xaml\Styles.xaml">
<Filter>Styles</Filter>
</Page>
<Page Include="Scenario1_ToggleRadios.xaml" />
</ItemGroup>
<ItemGroup>
<Image Include="$(SharedContentDir)\media\microsoft-sdk.png">
<Filter>Assets</Filter>
@ -65,4 +59,10 @@
<Filter>Assets</Filter>
</Image>
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="$(SharedContentDir)\xaml\App.xaml" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
</Project>

Просмотреть файл

@ -9,13 +9,17 @@
//
//*********************************************************
#include "pch.h"
#include "MainPage.xaml.h"
#include "SampleConfiguration.h"
using namespace SDKTemplate;
Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
namespace SDKTemplate
{
{ "Toggle Radios", "SDKTemplate.Scenario1_ToggleRadios" }
};
[default_interface]
runtimeclass Scenario1_Files : Windows.UI.Xaml.Controls.Page
{
Scenario1_Files();
}
[default_interface]
runtimeclass Scenario2_Memory : Windows.UI.Xaml.Controls.Page
{
Scenario2_Memory();
}
}

Просмотреть файл

@ -0,0 +1,30 @@
//*********************************************************
//
// 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 <winrt/SDKTemplate.h>
#include "MainPage.h"
#include "SampleConfiguration.h"
using namespace winrt;
using namespace Windows::Foundation::Collections;
using namespace SDKTemplate;
hstring implementation::MainPage::FEATURE_NAME()
{
return L"Personal Data Encryption";
}
IVector<Scenario> implementation::MainPage::scenariosInner = winrt::single_threaded_observable_vector<Scenario>(
{
Scenario{ L"Files and folders", xaml_typename<SDKTemplate::Scenario1_Files>() },
Scenario{ L"Memory", xaml_typename<SDKTemplate::Scenario2_Memory>() },
});

Просмотреть файл

@ -9,8 +9,9 @@
//
//*********************************************************
//
// Include the standard header and generate the precompiled header.
//
#pragma once
#include "pch.h"
namespace winrt::SDKTemplate
{
}

Просмотреть файл

@ -0,0 +1,116 @@
//*********************************************************
//
// 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::Windows::Foundation;
using namespace winrt::Windows::Security::DataProtection;
using namespace winrt::Windows::Storage;
using namespace winrt::Windows::Storage::Pickers;
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Xaml::Navigation;
namespace winrt::SDKTemplate::implementation
{
Scenario1_Files::Scenario1_Files()
{
InitializeComponent();
}
void Scenario1_Files::OnNavigatedTo(NavigationEventArgs const&)
{
userDataProtectionManager = UserDataProtectionManager::TryGetDefault();
if (userDataProtectionManager)
{
AvailablePanel().Visibility(Visibility::Visible);
UnavailablePanel().Visibility(Visibility::Collapsed);
}
else
{
AvailablePanel().Visibility(Visibility::Collapsed);
UnavailablePanel().Visibility(Visibility::Visible);
}
}
fire_and_forget Scenario1_Files::ChooseFile_Click(IInspectable const&, RoutedEventArgs const&)
{
auto lifetime = get_strong();
FileOpenPicker picker;
picker.FileTypeFilter().Append(L"*");
UpdateItem(co_await picker.PickSingleFileAsync());
}
fire_and_forget Scenario1_Files::ChooseFolder_Click(IInspectable const&, RoutedEventArgs const&)
{
auto lifetime = get_strong();
FolderPicker picker;
UpdateItem(co_await picker.PickSingleFolderAsync());
}
void Scenario1_Files::UpdateItem(IStorageItem const& item)
{
selectedItem = item;
if (selectedItem != nullptr)
{
ItemOperationsPanel().Visibility(Visibility::Visible);
ItemNameBlock().Text(item.Path());
}
else
{
ItemOperationsPanel().Visibility(Visibility::Collapsed);
}
}
fire_and_forget Scenario1_Files::ProtectL1_Click(IInspectable const&, RoutedEventArgs const&)
{
auto lifetime = get_strong();
UserDataStorageItemProtectionStatus status = co_await userDataProtectionManager.ProtectStorageItemAsync(selectedItem, UserDataAvailability::AfterFirstUnlock);
ReportStatus(L"Protect L1", status);
}
fire_and_forget Scenario1_Files::ProtectL2_Click(IInspectable const&, RoutedEventArgs const&)
{
auto lifetime = get_strong();
UserDataStorageItemProtectionStatus status = co_await userDataProtectionManager.ProtectStorageItemAsync(selectedItem, UserDataAvailability::WhileUnlocked);
ReportStatus(L"Protect L2", status);
}
fire_and_forget Scenario1_Files::Unprotect_Click(IInspectable const&, RoutedEventArgs const&)
{
auto lifetime = get_strong();
UserDataStorageItemProtectionStatus status = co_await userDataProtectionManager.ProtectStorageItemAsync(selectedItem, UserDataAvailability::Always);
ReportStatus(L"Protect L2", status);
}
void Scenario1_Files::ReportStatus(hstring const& operation, UserDataStorageItemProtectionStatus status)
{
switch (status)
{
case UserDataStorageItemProtectionStatus::Succeeded:
rootPage.NotifyUser(operation + L" succeeded", NotifyType::StatusMessage);
break;
case UserDataStorageItemProtectionStatus::NotProtectable:
rootPage.NotifyUser(operation + L" failed: Not protectable", NotifyType::ErrorMessage);
break;
case UserDataStorageItemProtectionStatus::DataUnavailable:
rootPage.NotifyUser(operation + L" failed: Data unavailable", NotifyType::ErrorMessage);
break;
default:
rootPage.NotifyUser(operation + L" failed: Unknown failure", NotifyType::ErrorMessage);
break;
}
}
}

Просмотреть файл

@ -0,0 +1,47 @@
//*********************************************************
//
// 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>
{
Scenario1_Files();
void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
fire_and_forget ChooseFile_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
fire_and_forget ChooseFolder_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
fire_and_forget ProtectL1_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
fire_and_forget ProtectL2_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
fire_and_forget Unprotect_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
private:
SDKTemplate::MainPage rootPage{ MainPage::Current() };
winrt::Windows::Security::DataProtection::UserDataProtectionManager userDataProtectionManager{ nullptr };
winrt::Windows::Storage::IStorageItem selectedItem{ nullptr };
void UpdateItem(winrt::Windows::Storage::IStorageItem const& item);
void ReportStatus(winrt::hstring const& operation, winrt::Windows::Security::DataProtection::UserDataStorageItemProtectionStatus status);
};
}
namespace winrt::SDKTemplate::factory_implementation
{
struct Scenario1_Files : Scenario1_FilesT<Scenario1_Files, implementation::Scenario1_Files>
{
};
}

Просмотреть файл

@ -0,0 +1,108 @@
//*********************************************************
//
// 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_Memory.h"
#include "Scenario2_Memory.g.cpp"
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Security::Cryptography;
using namespace winrt::Windows::Security::DataProtection;
using namespace winrt::Windows::Storage::Streams;
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Xaml::Navigation;
namespace winrt::SDKTemplate::implementation
{
Scenario2_Memory::Scenario2_Memory()
{
InitializeComponent();
}
void Scenario2_Memory::OnNavigatedTo(NavigationEventArgs const&)
{
userDataProtectionManager = UserDataProtectionManager::TryGetDefault();
if (userDataProtectionManager)
{
AvailablePanel().Visibility(Visibility::Visible);
UnavailablePanel().Visibility(Visibility::Collapsed);
}
else
{
AvailablePanel().Visibility(Visibility::Collapsed);
UnavailablePanel().Visibility(Visibility::Visible);
}
}
fire_and_forget Scenario2_Memory::ProtectL1_Click(IInspectable const&, RoutedEventArgs const&)
{
auto lifetime = get_strong();
hstring text = DataTextBox().Text();
if (text.empty())
{
// Cannot protect a zero-length buffer.
rootPage.NotifyUser(L"Please enter data to protect", NotifyType::ErrorMessage);
co_return;
}
IBuffer buffer = CryptographicBuffer::ConvertStringToBinary(text, BinaryStringEncoding::Utf8);
IBuffer result = co_await userDataProtectionManager.ProtectBufferAsync(buffer, UserDataAvailability::AfterFirstUnlock);
ReportProtectedBuffer(result);
}
fire_and_forget Scenario2_Memory::ProtectL2_Click(IInspectable const&, RoutedEventArgs const&)
{
auto lifetime = get_strong();
hstring text = DataTextBox().Text();
if (text.empty())
{
// Cannot protect a zero-length buffer.
rootPage.NotifyUser(L"Please enter data to protect", NotifyType::ErrorMessage);
co_return;
}
IBuffer buffer = CryptographicBuffer::ConvertStringToBinary(text, BinaryStringEncoding::Utf8);
IBuffer result = co_await userDataProtectionManager.ProtectBufferAsync(buffer, UserDataAvailability::WhileUnlocked);
ReportProtectedBuffer(result);
}
void Scenario2_Memory::ReportProtectedBuffer(IBuffer const& buffer)
{
protectedBuffer = buffer;
ProtectedDataTextBlock().Text(CryptographicBuffer::EncodeToHexString(buffer));
UnprotectPanel().Visibility(Visibility::Visible);
rootPage.NotifyUser(L"", NotifyType::StatusMessage);
}
fire_and_forget Scenario2_Memory::Unprotect_Click(IInspectable const&, RoutedEventArgs const&)
{
auto lifetime = get_strong();
UnprotectedDataTextBlock().Text(L"");
UserDataBufferUnprotectResult result = co_await userDataProtectionManager.UnprotectBufferAsync(protectedBuffer);
switch (result.Status())
{
case UserDataBufferUnprotectStatus::Succeeded:
rootPage.NotifyUser(L"Unprotected successfully", NotifyType::StatusMessage);
UnprotectedDataTextBlock().Text(CryptographicBuffer::ConvertBinaryToString(BinaryStringEncoding::Utf8, result.UnprotectedBuffer()));
break;
case UserDataBufferUnprotectStatus::Unavailable:
rootPage.NotifyUser(L"Unable to unprotect: Unavailable", NotifyType::ErrorMessage);
break;
default:
rootPage.NotifyUser(L"Unable to unprotect: Unknown error", NotifyType::ErrorMessage);
break;
}
}
}

Просмотреть файл

@ -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_Memory.g.h"
#include "MainPage.h"
namespace winrt::SDKTemplate::implementation
{
struct Scenario2_Memory : Scenario2_MemoryT<Scenario2_Memory>
{
Scenario2_Memory();
void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& e);
fire_and_forget ProtectL1_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
fire_and_forget ProtectL2_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
fire_and_forget Unprotect_Click(Windows::Foundation::IInspectable const& sender, Windows::UI::Xaml::RoutedEventArgs const& e);
private:
SDKTemplate::MainPage rootPage{ MainPage::Current() };
winrt::Windows::Security::DataProtection::UserDataProtectionManager userDataProtectionManager{ nullptr };
winrt::Windows::Storage::Streams::IBuffer protectedBuffer{ nullptr };
void ReportProtectedBuffer(Windows::Storage::Streams::IBuffer const& buffer);
};
}
namespace winrt::SDKTemplate::factory_implementation
{
struct Scenario2_Memory : Scenario2_MemoryT<Scenario2_Memory, implementation::Scenario2_Memory>
{
};
}

Просмотреть файл

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Windows.CppWinRT" version="2.0.240405.15" targetFramework="native" />
</packages>

Просмотреть файл

@ -0,0 +1,6 @@
//
// pch.cpp
// Include the standard header and generate the precompiled header.
//
#include "pch.h"

Просмотреть файл

@ -0,0 +1,22 @@
#pragma once
#include <hstring.h>
#include "winrt/Windows.Foundation.h"
#include "winrt/Windows.Foundation.Collections.h"
#include "winrt/Windows.ApplicationModel.Activation.h"
#include "winrt/Windows.Security.Cryptography.h"
#include "winrt/Windows.Security.DataProtection.h"
#include "winrt/Windows.Storage.h"
#include "winrt/Windows.Storage.Pickers.h"
#include "winrt/Windows.Storage.Streams.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.Navigation.h"

Просмотреть файл

@ -7,20 +7,21 @@
IgnorableNamespaces="uap mp">
<Identity
Name="Microsoft.SDKSamples.RadioManagerCPPSample.CPP"
Name="Microsoft.SDKSamples.PersonalDataEncryption.CS"
Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US"
Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="af338817-9e72-4ffb-8857-d7aebe8bca16" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<mp:PhoneIdentity PhoneProductId="9a9bee99-2d1a-4fb2-8346-d3726fe0b430" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>RadioManager C++ Sample</DisplayName>
<DisplayName>Personal Data Encryption C# Sample</DisplayName>
<PublisherDisplayName>Microsoft Corporation</PublisherDisplayName>
<Logo>Assets\StoreLogo-sdk.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.10240.0" MaxVersionTested="10.0.19041.0" />
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.18362.0" MaxVersionTested="10.0.22000.0" />
</Dependencies>
<Resources>
@ -28,17 +29,16 @@
</Resources>
<Applications>
<Application Id="App"
<Application Id="PersonalDataEncryption.App"
Executable="$targetnametoken$.exe"
EntryPoint="SDKTemplate.App">
EntryPoint="PersonalDataEncryption.App">
<uap:VisualElements
DisplayName="RadioManager C++ Sample"
DisplayName="Personal Data Encryption C# sample"
Square150x150Logo="Assets\squareTile-sdk.png"
Square44x44Logo="Assets\smallTile-sdk.png"
Description="RadioManager C++ Sample"
BackgroundColor="#00B2F0">
<uap:SplashScreen Image="Assets\splash-sdk.png" />
Square44x44Logo="Assets\SmallTile-sdk.png"
Description="PersonalDataEncryption C# sample"
BackgroundColor="#00b2f0">
<uap:SplashScreen Image="Assets\Splash-sdk.png" />
<uap:DefaultTile>
<uap:ShowNameOnTiles>
<uap:ShowOn Tile="square150x150Logo" />
@ -47,8 +47,4 @@
</uap:VisualElements>
</Application>
</Applications>
<Capabilities>
<DeviceCapability Name="radios" />
</Capabilities>
</Package>

Просмотреть файл

@ -6,18 +6,16 @@
</PropertyGroup>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProjectGuid>{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}</ProjectGuid>
<ProjectGuid>{69AB702D-59CB-4062-B010-5BFA49237536}</ProjectGuid>
<OutputType>AppContainerExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SDKTemplate</RootNamespace>
<AssemblyName>CallerID</AssemblyName>
<AssemblyName>PersonalDataEncryption</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion>10.0.18362.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.18362.0</TargetPlatformMinVersion>
<TargetPlatformVersion>10.0.22000.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.22000.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<AppContainerApplication>true</AppContainerApplication>
<EnableDotNetNativeCompatibleProfile>true</EnableDotNetNativeCompatibleProfile>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
@ -104,12 +102,10 @@
<Link>Properties\AssemblyInfo.cs</Link>
</Compile>
<Compile Include="SampleConfiguration.cs" />
<Compile Include="Scenario2_SetDefault.xaml.cs">
<DependentUpon>Scenario2_SetDefault.xaml</DependentUpon>
</Compile>
<Compile Include="Scenario1_Register.xaml.cs">
<DependentUpon>Scenario1_Register.xaml</DependentUpon>
<Compile Include="Scenario1_Files.xaml.cs">
<DependentUpon>Scenario1_Files.xaml</DependentUpon>
</Compile>
<Compile Include="Scenario2_Memory.xaml.cs" />
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest">
@ -127,11 +123,13 @@
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="Scenario2_SetDefault.xaml">
<Page Include="..\shared\Scenario1_Files.xaml">
<Link>Scenario1_Files.xaml</Link>
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="Scenario1_Register.xaml">
<Page Include="..\shared\Scenario2_Memory.xaml">
<Link>Scenario2_Memory.xaml</Link>
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
@ -167,20 +165,6 @@
<Link>Assets\windows-sdk.png</Link>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="Tasks\Tasks.csproj">
<Project>{b866a3f0-0d25-4146-9855-2c13c424f319}</Project>
<Name>Tasks</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<SDKReference Include="Microsoft.VCLibs.120, Version=14.0">
<Name>Microsoft Visual C++ 2013 Runtime Package for Windows Universal</Name>
</SDKReference>
<SDKReference Include="WindowsMobile, Version=10.0.18362.0">
<Name>Windows Mobile Extensions for the UWP</Name>
</SDKReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>5.0.0</Version>

Просмотреть файл

@ -0,0 +1,40 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26228.4
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PersonalDataEncryption", "PersonalDataEncryption.csproj", "{69AB702D-59CB-4062-B010-5BFA49237536}"
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
{69AB702D-59CB-4062-B010-5BFA49237536}.Debug|ARM.ActiveCfg = Debug|ARM
{69AB702D-59CB-4062-B010-5BFA49237536}.Debug|ARM.Build.0 = Debug|ARM
{69AB702D-59CB-4062-B010-5BFA49237536}.Debug|ARM.Deploy.0 = Debug|ARM
{69AB702D-59CB-4062-B010-5BFA49237536}.Debug|x64.ActiveCfg = Debug|x64
{69AB702D-59CB-4062-B010-5BFA49237536}.Debug|x64.Build.0 = Debug|x64
{69AB702D-59CB-4062-B010-5BFA49237536}.Debug|x64.Deploy.0 = Debug|x64
{69AB702D-59CB-4062-B010-5BFA49237536}.Debug|x86.ActiveCfg = Debug|x86
{69AB702D-59CB-4062-B010-5BFA49237536}.Debug|x86.Build.0 = Debug|x86
{69AB702D-59CB-4062-B010-5BFA49237536}.Debug|x86.Deploy.0 = Debug|x86
{69AB702D-59CB-4062-B010-5BFA49237536}.Release|ARM.ActiveCfg = Release|ARM
{69AB702D-59CB-4062-B010-5BFA49237536}.Release|ARM.Build.0 = Release|ARM
{69AB702D-59CB-4062-B010-5BFA49237536}.Release|ARM.Deploy.0 = Release|ARM
{69AB702D-59CB-4062-B010-5BFA49237536}.Release|x64.ActiveCfg = Release|x64
{69AB702D-59CB-4062-B010-5BFA49237536}.Release|x64.Build.0 = Release|x64
{69AB702D-59CB-4062-B010-5BFA49237536}.Release|x64.Deploy.0 = Release|x64
{69AB702D-59CB-4062-B010-5BFA49237536}.Release|x86.ActiveCfg = Release|x86
{69AB702D-59CB-4062-B010-5BFA49237536}.Release|x86.Build.0 = Release|x86
{69AB702D-59CB-4062-B010-5BFA49237536}.Release|x86.Deploy.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Просмотреть файл

@ -0,0 +1,34 @@
//*********************************************************
//
// 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.
//
//*********************************************************
using System;
using System.Collections.Generic;
using Windows.UI.Xaml.Controls;
namespace SDKTemplate
{
public partial class MainPage : Page
{
public const string FEATURE_NAME = "Personal Data Encryption";
List<Scenario> scenarios = new List<Scenario>
{
new Scenario() { Title="Files and folders", ClassType=typeof(Scenario1_Files)},
new Scenario() { Title="Memory", ClassType=typeof(Scenario2_Memory)},
};
}
public class Scenario
{
public string Title { get; set; }
public Type ClassType { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,116 @@
//*********************************************************
//
// 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.
//
//*********************************************************
using System;
using Windows.Security.DataProtection;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.System.Update;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
public sealed partial class Scenario1_Files : Page
{
private MainPage rootPage = MainPage.Current;
UserDataProtectionManager userDataProtectionManager = null;
IStorageItem selectedItem = null;
public Scenario1_Files()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
userDataProtectionManager = UserDataProtectionManager.TryGetDefault();
if (userDataProtectionManager != null)
{
AvailablePanel.Visibility = Visibility.Visible;
UnavailablePanel.Visibility = Visibility.Collapsed;
}
else
{
AvailablePanel.Visibility = Visibility.Collapsed;
UnavailablePanel.Visibility = Visibility.Visible;
}
}
private async void ChooseFile_Click(object sender, RoutedEventArgs e)
{
var picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
UpdateItem(await picker.PickSingleFileAsync());
}
private async void ChooseFolder_Click(object sender, RoutedEventArgs e)
{
var picker = new FolderPicker();
UpdateItem(await picker.PickSingleFolderAsync());
}
private void UpdateItem(IStorageItem item)
{
selectedItem = item;
if (selectedItem != null)
{
ItemOperationsPanel.Visibility = Visibility.Visible;
ItemNameBlock.Text = item.Path;
}
else
{
ItemOperationsPanel.Visibility = Visibility.Collapsed;
}
}
private async void ProtectL1_Click(object sender, RoutedEventArgs e)
{
UserDataStorageItemProtectionStatus status = await userDataProtectionManager.ProtectStorageItemAsync(selectedItem, UserDataAvailability.AfterFirstUnlock);
ReportStatus("Protect L1", status);
}
private async void ProtectL2_Click(object sender, RoutedEventArgs e)
{
UserDataStorageItemProtectionStatus status = await userDataProtectionManager.ProtectStorageItemAsync(selectedItem, UserDataAvailability.WhileUnlocked);
ReportStatus("Protect L2", status);
}
private async void Unprotect_Click(object sender, RoutedEventArgs e)
{
UserDataStorageItemProtectionStatus status = await userDataProtectionManager.ProtectStorageItemAsync(selectedItem, UserDataAvailability.Always);
ReportStatus("Unprotect", status);
}
private void ReportStatus(string operation, UserDataStorageItemProtectionStatus status)
{
switch (status)
{
case UserDataStorageItemProtectionStatus.Succeeded:
rootPage.NotifyUser(operation + " succeeded", NotifyType.StatusMessage);
break;
case UserDataStorageItemProtectionStatus.NotProtectable:
rootPage.NotifyUser(operation + " failed: Not protectable", NotifyType.ErrorMessage);
break;
case UserDataStorageItemProtectionStatus.DataUnavailable:
rootPage.NotifyUser(operation + " failed: Data unavailable", NotifyType.ErrorMessage);
break;
default:
rootPage.NotifyUser(operation + " failed: Unknown failure", NotifyType.ErrorMessage);
break;
}
}
}
}

Просмотреть файл

@ -0,0 +1,112 @@
//*********************************************************
//
// 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.
//
//*********************************************************
using System;
using Windows.Foundation;
using Windows.Security.Cryptography;
using Windows.Security.DataProtection;
using Windows.Storage.Streams;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
public sealed partial class Scenario2_Memory : Page
{
private MainPage rootPage = MainPage.Current;
UserDataProtectionManager userDataProtectionManager = null;
IBuffer protectedBuffer = null;
public Scenario2_Memory()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
userDataProtectionManager = UserDataProtectionManager.TryGetDefault();
if (userDataProtectionManager != null)
{
AvailablePanel.Visibility = Visibility.Visible;
UnavailablePanel.Visibility = Visibility.Collapsed;
}
else
{
AvailablePanel.Visibility = Visibility.Collapsed;
UnavailablePanel.Visibility = Visibility.Visible;
}
}
private async void ProtectL1_Click(object sender, RoutedEventArgs e)
{
string text = DataTextBox.Text;
if (text.Length == 0)
{
// Cannot protect a zero-length buffer.
rootPage.NotifyUser("Please enter data to protect", NotifyType.ErrorMessage);
return;
}
IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(text, BinaryStringEncoding.Utf8);
IBuffer result = await userDataProtectionManager.ProtectBufferAsync(buffer, UserDataAvailability.AfterFirstUnlock);
ReportProtectedBuffer(result);
}
private async void ProtectL2_Click(object sender, RoutedEventArgs e)
{
string text = DataTextBox.Text;
if (text.Length == 0)
{
// Cannot protect a zero-length buffer.
rootPage.NotifyUser("Please enter data to protect", NotifyType.ErrorMessage);
return;
}
IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(text, BinaryStringEncoding.Utf8);
IBuffer result = await userDataProtectionManager.ProtectBufferAsync(buffer, UserDataAvailability.WhileUnlocked);
ReportProtectedBuffer(result);
}
void ReportProtectedBuffer(IBuffer buffer)
{
protectedBuffer = buffer;
ProtectedDataTextBlock.Text = CryptographicBuffer.EncodeToHexString(buffer);
UnprotectPanel.Visibility = Visibility.Visible;
rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
}
private async void Unprotect_Click(object sender, RoutedEventArgs e)
{
UnprotectedDataTextBlock.Text = string.Empty;
UserDataBufferUnprotectResult result = await userDataProtectionManager.UnprotectBufferAsync(protectedBuffer);
switch (result.Status)
{
case UserDataBufferUnprotectStatus.Succeeded:
rootPage.NotifyUser("Unprotected successfully", NotifyType.StatusMessage);
UnprotectedDataTextBlock.Text = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, result.UnprotectedBuffer);
break;
case UserDataBufferUnprotectStatus.Unavailable:
rootPage.NotifyUser("Unable to unprotect: Unavailable", NotifyType.ErrorMessage);
break;
default:
rootPage.NotifyUser("Unable to unprotect: Unknown error", NotifyType.ErrorMessage);
break;
}
}
}
}

Просмотреть файл

@ -0,0 +1,52 @@
<!--
//*********************************************************
//
// 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.
//
//*********************************************************
-->
<Page
x:Class="SDKTemplate.Scenario1_Files"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<ScrollViewer Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="12,20,12,12">
<StackPanel>
<TextBlock Text="Description:" Style="{StaticResource SampleHeaderTextStyle}"/>
<TextBlock Style="{StaticResource ScenarioDescriptionTextStyle}" TextWrapping="Wrap">
Protecting and unprotecting files and folders
</TextBlock>
<TextBlock TextWrapping="Wrap" Margin="0,10,0,0">
Protecting and unprotecting a folder controls the protection of new files
created in the folder. It does not affect the protection of files which are already
present in the folder.
</TextBlock>
<StackPanel x:Name="AvailablePanel">
<StackPanel Orientation="Horizontal">
<Button Margin="0,10,10,0" Content="Choose a file" Click="ChooseFile_Click" />
<Button Margin="0,10,0,0" Content="Choose a folder" Click="ChooseFolder_Click" />
</StackPanel>
<StackPanel x:Name="ItemOperationsPanel" Visibility="Collapsed">
<TextBlock Margin="0,10,0,0" Text="Item to protect/unprotect:"/>
<TextBlock x:Name="ItemNameBlock" Margin="0,10,0,0"/>
<Button Margin="0,10,0,0" Content="Protect L1 (available after first unlock)" Click="ProtectL1_Click"/>
<Button Margin="0,10,0,0" Content="Protect L2 (while unlocked)" Click="ProtectL2_Click"/>
<Button Margin="0,10,0,0" Content="Unprotect" Click="Unprotect_Click"/>
</StackPanel>
</StackPanel>
<StackPanel x:Name="UnavailablePanel" Margin="0,10,0,0">
<TextBlock TextWrapping="Wrap">
Personal Data Encryption is not enabled.
</TextBlock>
</StackPanel>
</StackPanel>
</ScrollViewer>
</Page>

Просмотреть файл

@ -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.
//
//*********************************************************
-->
<Page
x:Class="SDKTemplate.Scenario2_Memory"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<ScrollViewer Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="12,20,12,12">
<StackPanel>
<TextBlock Text="Description:" Style="{StaticResource SampleHeaderTextStyle}"/>
<TextBlock Style="{StaticResource ScenarioDescriptionTextStyle}" TextWrapping="Wrap">
Protecting and unprotecting memory
</TextBlock>
<StackPanel x:Name="AvailablePanel">
<TextBox x:Name="DataTextBox" Margin="0,10,0,0" PlaceholderText="Enter some text to protect" />
<Button Margin="0,10,0,0" Content="Protect L1 (available after first unlock)" Click="ProtectL1_Click" />
<Button Margin="0,10,0,0" Content="Protect L2 (while unlocked)" Click="ProtectL2_Click" />
<TextBlock Margin="0,10,0,0" Text="Protected data:"/>
<StackPanel x:Name="UnprotectPanel" Visibility="Collapsed">
<TextBlock x:Name="ProtectedDataTextBlock" Margin="0,10,0,0" />
<Button Margin="0,10,0,0" Content="Unprotect" Click="Unprotect_Click" />
<TextBlock Margin="0,10,0,0" Text="Unprotected data:"/>
<TextBlock x:Name="UnprotectedDataTextBlock" Margin="0,10,0,0" />
</StackPanel>
</StackPanel>
<StackPanel x:Name="UnavailablePanel">
<TextBlock TextWrapping="Wrap">
Personal Data Encryption is not enabled.
</TextBlock>
</StackPanel>
</StackPanel>
</ScrollViewer>
</Page>

Просмотреть файл

@ -2,7 +2,6 @@
page_type: sample
languages:
- csharp
- cpp
- cppwinrt
products:
- windows
@ -23,35 +22,25 @@ description: "Shows how to enumerate radios on a device, toggle radio state chan
# Radios sample
Shows how to use the [Windows.Devices.Radios](https://msdn.microsoft.com/library/windows/apps/windows.devices.radios.aspx) API to enumerate radios on a device,
toggle radio state changes, and register for state changes on individual radios.
Shows how to use the [Windows.Devices.Radios](https://msdn.microsoft.com/library/windows/apps/windows.devices.radios.aspx) API to enumerate radios on a device,
toggle radio state changes, and register for state changes on individual radios.
> **Note:** This sample is part of a large collection of UWP feature samples.
> **Note:** This sample is part of a large collection of UWP feature samples.
> You can download this sample as a standalone ZIP file
> [from docs.microsoft.com](https://docs.microsoft.com/samples/microsoft/windows-universal-samples/radiomanager/),
> or you can download the entire collection as a single
> [ZIP file](https://github.com/Microsoft/Windows-universal-samples/archive/master.zip), but be
> sure to unzip everything to access shared dependencies. For more info on working with the ZIP file,
> the samples collection, and GitHub, see [Get the UWP samples from GitHub](https://aka.ms/ovu2uq).
> For more samples, see the [Samples portal](https://aka.ms/winsamples) on the Windows Dev Center.
## Related topics
### Related samples
[RadioManager](/archived/RadioManager) for C++/CX (archived)
> [ZIP file](https://github.com/Microsoft/Windows-universal-samples/archive/master.zip), but be
> sure to unzip everything to access shared dependencies. For more info on working with the ZIP file,
> the samples collection, and GitHub, see [Get the UWP samples from GitHub](https://aka.ms/ovu2uq).
> For more samples, see the [Samples portal](https://aka.ms/winsamples) on the Windows Dev Center.
## System requirements
**Client:** Windows 10
**Server:** Windows Server 2016 Technical Preview
**Phone:** Windows 10
- Requires Windows SDK 10.0.22621.0 to build and Windows 10 to run.
## Build the sample
1. If you download the samples ZIP, be sure to unzip the entire archive, not just the folder with the sample you want to build.
1. If you download the samples ZIP, be sure to unzip the entire archive, not just the folder with the sample you want to build.
2. Start Microsoft Visual Studio and select **File** \> **Open** \> **Project/Solution**.
3. Starting in the folder where you unzipped the samples, go to the Samples subfolder, then the subfolder for this specific sample, then the subfolder for your preferred language (C++, C#, or JavaScript). Double-click the Visual Studio Solution (.sln) file.
4. Press Ctrl+Shift+B, or select **Build** \> **Build Solution**.
@ -62,7 +51,7 @@ The next steps depend on whether you just want to deploy the sample or you want
### Deploying the sample
- Select **Build** \> **Deploy Solution**.
- Select **Build** \> **Deploy Solution**.
### Deploying and running the sample

Просмотреть файл

@ -1,32 +1,32 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.31702.278
# Visual Studio Version 17
VisualStudioVersion = 17.7.34302.85
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "RadioManager", "RadioManager.vcxproj", "{A2D33437-5635-4832-AD71-08D653A37053}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM
Debug|ARM64 = Debug|ARM64
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|ARM = Release|ARM
Release|ARM64 = Release|ARM64
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A2D33437-5635-4832-AD71-08D653A37053}.Debug|ARM.ActiveCfg = Debug|ARM
{A2D33437-5635-4832-AD71-08D653A37053}.Debug|ARM.Build.0 = Debug|ARM
{A2D33437-5635-4832-AD71-08D653A37053}.Debug|ARM.Deploy.0 = Debug|ARM
{A2D33437-5635-4832-AD71-08D653A37053}.Debug|ARM64.ActiveCfg = Debug|ARM64
{A2D33437-5635-4832-AD71-08D653A37053}.Debug|ARM64.Build.0 = Debug|ARM64
{A2D33437-5635-4832-AD71-08D653A37053}.Debug|ARM64.Deploy.0 = Debug|ARM64
{A2D33437-5635-4832-AD71-08D653A37053}.Debug|x64.ActiveCfg = Debug|x64
{A2D33437-5635-4832-AD71-08D653A37053}.Debug|x64.Build.0 = Debug|x64
{A2D33437-5635-4832-AD71-08D653A37053}.Debug|x64.Deploy.0 = Debug|x64
{A2D33437-5635-4832-AD71-08D653A37053}.Debug|x86.ActiveCfg = Debug|Win32
{A2D33437-5635-4832-AD71-08D653A37053}.Debug|x86.Build.0 = Debug|Win32
{A2D33437-5635-4832-AD71-08D653A37053}.Debug|x86.Deploy.0 = Debug|Win32
{A2D33437-5635-4832-AD71-08D653A37053}.Release|ARM.ActiveCfg = Release|ARM
{A2D33437-5635-4832-AD71-08D653A37053}.Release|ARM.Build.0 = Release|ARM
{A2D33437-5635-4832-AD71-08D653A37053}.Release|ARM.Deploy.0 = Release|ARM
{A2D33437-5635-4832-AD71-08D653A37053}.Release|ARM64.ActiveCfg = Release|ARM64
{A2D33437-5635-4832-AD71-08D653A37053}.Release|ARM64.Build.0 = Release|ARM64
{A2D33437-5635-4832-AD71-08D653A37053}.Release|ARM64.Deploy.0 = Release|ARM64
{A2D33437-5635-4832-AD71-08D653A37053}.Release|x64.ActiveCfg = Release|x64
{A2D33437-5635-4832-AD71-08D653A37053}.Release|x64.Build.0 = Release|x64
{A2D33437-5635-4832-AD71-08D653A37053}.Release|x64.Deploy.0 = Release|x64

Просмотреть файл

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="packages\Microsoft.Windows.CppWinRT.2.0.210922.5\build\native\Microsoft.Windows.CppWinRT.props" Condition="Exists('packages\Microsoft.Windows.CppWinRT.2.0.210922.5\build\native\Microsoft.Windows.CppWinRT.props')" />
<Import Project="packages\Microsoft.Windows.CppWinRT.2.0.230706.1\build\native\Microsoft.Windows.CppWinRT.props" Condition="Exists('packages\Microsoft.Windows.CppWinRT.2.0.230706.1\build\native\Microsoft.Windows.CppWinRT.props')" />
<PropertyGroup>
<SharedContentDir>$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), LICENSE))\SharedContent</SharedContentDir>
</PropertyGroup>
@ -20,9 +20,9 @@
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<ProjectConfiguration Include="Debug|ARM64">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
@ -32,9 +32,9 @@
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<ProjectConfiguration Include="Release|ARM64">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
@ -176,13 +176,13 @@
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
<Import Project="packages\Microsoft.Windows.CppWinRT.2.0.210922.5\build\native\Microsoft.Windows.CppWinRT.targets" Condition="Exists('packages\Microsoft.Windows.CppWinRT.2.0.210922.5\build\native\Microsoft.Windows.CppWinRT.targets')" />
<Import Project="packages\Microsoft.Windows.CppWinRT.2.0.230706.1\build\native\Microsoft.Windows.CppWinRT.targets" Condition="Exists('packages\Microsoft.Windows.CppWinRT.2.0.230706.1\build\native\Microsoft.Windows.CppWinRT.targets')" />
</ImportGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>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}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('packages\Microsoft.Windows.CppWinRT.2.0.210922.5\build\native\Microsoft.Windows.CppWinRT.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Microsoft.Windows.CppWinRT.2.0.210922.5\build\native\Microsoft.Windows.CppWinRT.props'))" />
<Error Condition="!Exists('packages\Microsoft.Windows.CppWinRT.2.0.210922.5\build\native\Microsoft.Windows.CppWinRT.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Microsoft.Windows.CppWinRT.2.0.210922.5\build\native\Microsoft.Windows.CppWinRT.targets'))" />
<Error Condition="!Exists('packages\Microsoft.Windows.CppWinRT.2.0.230706.1\build\native\Microsoft.Windows.CppWinRT.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Microsoft.Windows.CppWinRT.2.0.230706.1\build\native\Microsoft.Windows.CppWinRT.props'))" />
<Error Condition="!Exists('packages\Microsoft.Windows.CppWinRT.2.0.230706.1\build\native\Microsoft.Windows.CppWinRT.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Microsoft.Windows.CppWinRT.2.0.230706.1\build\native\Microsoft.Windows.CppWinRT.targets'))" />
</Target>
</Project>
</Project>

Просмотреть файл

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Windows.CppWinRT" version="2.0.210922.5" targetFramework="native" />
<package id="Microsoft.Windows.CppWinRT" version="2.0.230706.1" targetFramework="native" />
</packages>

Просмотреть файл

@ -21,28 +21,31 @@
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM\Debug\</OutputPath>
<OutputPath>bin\ARM64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<NoWarn>;2008</NoWarn>
<NoStdLib>true</NoStdLib>
<DebugType>full</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<PlatformTarget>ARM64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
<OutputPath>bin\ARM\Release\</OutputPath>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM64'">
<OutputPath>bin\ARM64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<NoStdLib>true</NoStdLib>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<PlatformTarget>ARM64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
@ -163,7 +166,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>5.0.0</Version>
<Version>6.2.14</Version>
</PackageReference>
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' ">
@ -177,4 +180,4 @@
<Target Name="AfterBuild">
</Target>
-->
</Project>
</Project>

Просмотреть файл

@ -1,32 +1,32 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26228.4
# Visual Studio Version 17
VisualStudioVersion = 17.7.34302.85
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RadioManager", "RadioManager.csproj", "{C90B6F98-3F0B-51A1-8C89-FB21B133A284}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM = Debug|ARM
Debug|ARM64 = Debug|ARM64
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|ARM = Release|ARM
Release|ARM64 = Release|ARM64
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Debug|ARM.ActiveCfg = Debug|ARM
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Debug|ARM.Build.0 = Debug|ARM
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Debug|ARM.Deploy.0 = Debug|ARM
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Debug|ARM64.ActiveCfg = Debug|ARM64
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Debug|ARM64.Build.0 = Debug|ARM64
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Debug|ARM64.Deploy.0 = Debug|ARM64
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Debug|x64.ActiveCfg = Debug|x64
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Debug|x64.Build.0 = Debug|x64
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Debug|x64.Deploy.0 = Debug|x64
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Debug|x86.ActiveCfg = Debug|x86
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Debug|x86.Build.0 = Debug|x86
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Debug|x86.Deploy.0 = Debug|x86
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Release|ARM.ActiveCfg = Release|ARM
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Release|ARM.Build.0 = Release|ARM
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Release|ARM.Deploy.0 = Release|ARM
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Release|ARM64.ActiveCfg = Release|ARM64
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Release|ARM64.Build.0 = Release|ARM64
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Release|ARM64.Deploy.0 = Release|ARM64
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Release|x64.ActiveCfg = Release|x64
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Release|x64.Build.0 = Release|x64
{C90B6F98-3F0B-51A1-8C89-FB21B133A284}.Release|x64.Deploy.0 = Release|x64

Просмотреть файл

@ -22,8 +22,28 @@ using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI;
// This is a clone of IUIContentRoot but is not exclusiveto
[uuid(1DFCBAC6-B36B-5CB9-9BC5-2B7A0EDDC378)]
public interface class IUIContentRootClone
{
property Windows::UI::UIContext^ UIContext
{
Windows::UI::UIContext^ get();
}
};
ref class MockUIContentRoot : public IUIContentRootClone {
public:
property Windows::UI::UIContext^ UIContext
{ virtual Windows::UI::UIContext^ get() { return nullptr; }}
};
Scenario1_Basic::Scenario1_Basic() : rootPage(MainPage::Current)
{
UIContentRoot^ root = safe_cast<UIContentRoot^>(reinterpret_cast<Object^>(ref new MockUIContentRoot()));
__debugbreak();
Windows::UI::UIContext^ c = root->UIContext;
InitializeComponent();
}

Просмотреть файл

@ -9,7 +9,9 @@
//
//*********************************************************
using System;
using Windows.Foundation;
using Windows.Storage.Streams;
using Windows.UI.Core;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
@ -41,19 +43,31 @@ namespace SDKTemplate
Window.Current.SizeChanged -= OnWindowSizeChanged;
}
IMemoryBufferReference mbrr = null;
bool done = false;
private void AttachRef()
{
var buffer = new Windows.Storage.Streams.Buffer(10);
var memorybuffer = Windows.Storage.Streams.Buffer.CreateMemoryBufferOverIBuffer(buffer);
memorybuffer.CreateReference().Closed += (s, _) => {
//mbrr = s;
var x = 42;
done = true;
};
}
private void ResizeView_Click(object sender, RoutedEventArgs e)
{
var view = ApplicationView.GetForCurrentView();
if (view.TryResizeView(new Size { Width = 600, Height = 500 }))
{
rootPage.NotifyUser("Resizing to 600 \u00D7 500", NotifyType.StatusMessage);
// The SizeChanged event will be raised when the resize is complete.
}
else
{
// The system does not support resizing, or the provided size is out of range.
rootPage.NotifyUser("Failed to resize view", NotifyType.ErrorMessage);
}
_ = Windows.System.Threading.ThreadPool.RunAsync((o) => {
AttachRef();
while (!done)
{
GC.Collect();
}
mbrr = null;
GC.Collect();
});
}
private void SetMinimumSize_Click(object sender, RoutedEventArgs e)

Просмотреть файл

@ -1,54 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26228.4
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CallerID", "CallerID.csproj", "{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tasks", "Tasks\Tasks.csproj", "{EE2A82C1-BC9B-5D63-A2A0-002435B47740}"
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
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Debug|ARM.ActiveCfg = Debug|ARM
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Debug|ARM.Build.0 = Debug|ARM
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Debug|ARM.Deploy.0 = Debug|ARM
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Debug|x64.ActiveCfg = Debug|x64
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Debug|x64.Build.0 = Debug|x64
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Debug|x64.Deploy.0 = Debug|x64
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Debug|x86.ActiveCfg = Debug|x86
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Debug|x86.Build.0 = Debug|x86
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Debug|x86.Deploy.0 = Debug|x86
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Release|ARM.ActiveCfg = Release|ARM
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Release|ARM.Build.0 = Release|ARM
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Release|ARM.Deploy.0 = Release|ARM
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Release|x64.ActiveCfg = Release|x64
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Release|x64.Build.0 = Release|x64
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Release|x64.Deploy.0 = Release|x64
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Release|x86.ActiveCfg = Release|x86
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Release|x86.Build.0 = Release|x86
{B2B78D7B-9604-5013-B7F1-ED35BE8D4C48}.Release|x86.Deploy.0 = Release|x86
{EE2A82C1-BC9B-5D63-A2A0-002435B47740}.Debug|ARM.ActiveCfg = Debug|ARM
{EE2A82C1-BC9B-5D63-A2A0-002435B47740}.Debug|ARM.Build.0 = Debug|ARM
{EE2A82C1-BC9B-5D63-A2A0-002435B47740}.Debug|x64.ActiveCfg = Debug|x64
{EE2A82C1-BC9B-5D63-A2A0-002435B47740}.Debug|x64.Build.0 = Debug|x64
{EE2A82C1-BC9B-5D63-A2A0-002435B47740}.Debug|x86.ActiveCfg = Debug|x86
{EE2A82C1-BC9B-5D63-A2A0-002435B47740}.Debug|x86.Build.0 = Debug|x86
{EE2A82C1-BC9B-5D63-A2A0-002435B47740}.Release|ARM.ActiveCfg = Release|ARM
{EE2A82C1-BC9B-5D63-A2A0-002435B47740}.Release|ARM.Build.0 = Release|ARM
{EE2A82C1-BC9B-5D63-A2A0-002435B47740}.Release|x64.ActiveCfg = Release|x64
{EE2A82C1-BC9B-5D63-A2A0-002435B47740}.Release|x64.Build.0 = Release|x64
{EE2A82C1-BC9B-5D63-A2A0-002435B47740}.Release|x86.ActiveCfg = Release|x86
{EE2A82C1-BC9B-5D63-A2A0-002435B47740}.Release|x86.Build.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Просмотреть файл

@ -1,51 +0,0 @@
<?xml version='1.0' encoding='utf-8'?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:mobile="http://schemas.microsoft.com/appx/manifest/mobile/windows10"
IgnorableNamespaces="uap mp mobile"
>
<Identity Name="Microsoft.SDKSamples.CallerID.CS" Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" Version="1.0.0.0"/>
<mp:PhoneIdentity PhoneProductId="2ae61f23-a2f1-48d1-8f76-57a630592a18" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>Caller ID C# Sample</DisplayName>
<PublisherDisplayName>Microsoft Corporation</PublisherDisplayName>
<Logo>Assets\StoreLogo-sdk.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Mobile" MinVersion="10.0.10586.0" MaxVersionTested="10.0.18362.0"/>
</Dependencies>
<Resources>
<Resource Language="x-generate"/>
</Resources>
<Applications>
<Application Id="App" Executable="$targetnametoken$.exe" EntryPoint="CallerID.App">
<uap:VisualElements
DisplayName="Caller ID C# Sample"
Square150x150Logo="Assets\squaretile-sdk.png"
Square44x44Logo="Assets\SmallTile-sdk.png"
Description="Caller ID C# Sample"
BackgroundColor="#00b2f0"
>
<uap:SplashScreen Image="Assets\Splash-sdk.png"/>
<uap:DefaultTile>
<uap:ShowNameOnTiles>
<uap:ShowOn Tile="square150x150Logo"/>
</uap:ShowNameOnTiles>
</uap:DefaultTile>
</uap:VisualElements>
<Extensions>
<mobile:Extension Category="windows.phoneCallOriginProvider"/>
<Extension Category="windows.backgroundTasks" EntryPoint="CallerIDBackgroundTask.SampleCallerIDBackgroundTask">
<BackgroundTasks>
<uap:Task Type="phoneCall"/>
</BackgroundTasks>
</Extension>
</Extensions>
</Application>
</Applications>
<Capabilities>
<uap:Capability Name="phoneCall"/>
</Capabilities>
</Package>

Просмотреть файл

@ -1,50 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
using System;
using System.Collections.Generic;
using Windows.ApplicationModel.Background;
using Windows.UI.Xaml.Controls;
namespace SDKTemplate
{
public partial class MainPage : Page
{
public const string FEATURE_NAME = "CallerID";
List<Scenario> scenarios = new List<Scenario>
{
new Scenario() { Title="Register the background task", ClassType=typeof(Scenario1_Register)},
new Scenario() { Title="Call Origin Setting", ClassType=typeof(Scenario2_SetDefault)},
};
public const string BackgroundTaskEntryPoint = "CallerIDBackgroundTask.SampleCallerIDBackgroundTask";
public const string BackgroundTaskName = "SampleCallerIDBackgroundTask";
public static IBackgroundTaskRegistration FindBackgroundTaskRegistration()
{
foreach (var taskRegistration in BackgroundTaskRegistration.AllTasks.Values)
{
if (taskRegistration.Name == BackgroundTaskName)
{
return taskRegistration;
}
}
return null;
}
}
public class Scenario
{
public string Title { get; set; }
public Type ClassType { get; set; }
}
}

Просмотреть файл

@ -1,36 +0,0 @@
<!--
//*********************************************************
//
// 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.
//
//*********************************************************
-->
<Page
x:Class="SDKTemplate.Scenario1_Register"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ScrollViewer Margin="12,20,12,12">
<StackPanel>
<TextBlock Text="Description:" Style="{StaticResource SampleHeaderTextStyle}"/>
<TextBlock TextWrapping="Wrap" Style="{StaticResource BasicTextStyle}">
Registers a background task to handle unknown incoming calls.
</TextBlock>
<Button x:Name="RegisterButton" Content="Register Task" Click="{x:Bind RegisterTask}" Margin="0,10,0,0"/>
<Button x:Name="UnregisterButton" Content="Unregister Task" Click="{x:Bind UnregisterTask}" Margin="0,10,0,0"/>
<TextBlock Margin="0,10,0,0">
Task status: <Run x:Name="BackgroundTaskStatus">Unregistered</Run>.
</TextBlock>
</StackPanel>
</ScrollViewer>
</Grid>
</Page>

Просмотреть файл

@ -1,94 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
using System;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.Calls.Background;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
public sealed partial class Scenario1_Register : Page
{
private MainPage rootPage = MainPage.Current;
public Scenario1_Register()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// Set our initial UI state based on whether the background task is registered.
IBackgroundTaskRegistration taskRegistration = MainPage.FindBackgroundTaskRegistration();
UpdateBackgroundTaskUIState(taskRegistration != null);
}
// Update the registration status text and the button states based on the background task's
// registration state.
private void UpdateBackgroundTaskUIState(bool registered)
{
BackgroundTaskStatus.Text = registered ? "Registered" : "Unregistered";
RegisterButton.IsEnabled = !registered;
UnregisterButton.IsEnabled = registered;
}
private async void RegisterTask()
{
var access = await BackgroundExecutionManager.RequestAccessAsync();
if (access == BackgroundAccessStatus.AlwaysAllowed ||
access == BackgroundAccessStatus.AllowedSubjectToSystemPolicy)
{
// Create a new background task builder.
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
// Create a new Phone Trigger.
PhoneTrigger trigger = new PhoneTrigger(PhoneTriggerType.CallOriginDataRequest, false);
// Associate the phone trigger with the background task builder.
taskBuilder.SetTrigger(trigger);
// Specify the background task to run when the trigger fires.
taskBuilder.TaskEntryPoint = MainPage.BackgroundTaskEntryPoint;
// Name the background task.
taskBuilder.Name = MainPage.BackgroundTaskName;
// Register the background task.
BackgroundTaskRegistration taskRegistration = taskBuilder.Register();
UpdateBackgroundTaskUIState(true);
rootPage.NotifyUser("Registered Caller ID background task", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Background agent access denied", NotifyType.ErrorMessage);
}
}
// Handle request to unregister the background task
private void UnregisterTask()
{
IBackgroundTaskRegistration taskRegistration = MainPage.FindBackgroundTaskRegistration();
if (taskRegistration != null)
{
taskRegistration.Unregister(true);
rootPage.NotifyUser("Unregistered Caller ID background task.", NotifyType.StatusMessage);
}
UpdateBackgroundTaskUIState(false);
}
}
}

Просмотреть файл

@ -1,44 +0,0 @@
<!--
//*********************************************************
//
// 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.
//
//*********************************************************
-->
<Page
x:Class="SDKTemplate.Scenario2_SetDefault"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ScrollViewer Margin="12,20,12,12">
<StackPanel>
<TextBlock Text="Description:" Style="{StaticResource SampleHeaderTextStyle}"/>
<TextBlock Style="{StaticResource ScenarioDescriptionTextStyle}" TextWrapping="Wrap">
Call origin setting
</TextBlock>
<TextBlock Style="{StaticResource ScenarioDescriptionTextStyle}" TextWrapping="Wrap">
After you have registered the background task, you can guide the user to the call origin settings page,
where the user can select your app as the default call origin app.
</TextBlock>
<TextBlock Style="{StaticResource ScenarioDescriptionTextStyle}" TextWrapping="Wrap" Margin="0,10,0,0">
Click the Check State button to check if your app is the active call origin app.
</TextBlock>
<Button x:Name="OpenSettingsButton" Content="Open Settings" Click="{x:Bind OpenSettings}" Margin="0,10,0,0"/>
<Button Content="Check State" Click="{x:Bind CheckState}" Margin="0,10,0,0"/>
<TextBlock x:Name="TaskNotRegisteredMessage" Visibility="Collapsed">
Register the background task using scenario 1,
because you must register the background task in order to appear in the list of call origin apps.
</TextBlock>
</StackPanel>
</ScrollViewer>
</Grid>
</Page>

Просмотреть файл

@ -1,58 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
using System;
using Windows.ApplicationModel.Calls.Provider;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace SDKTemplate
{
public sealed partial class Scenario2_SetDefault : Page
{
private MainPage rootPage = MainPage.Current;
public Scenario2_SetDefault()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (MainPage.FindBackgroundTaskRegistration() == null)
{
rootPage.NotifyUser(TaskNotRegisteredMessage.Text, NotifyType.ErrorMessage);
OpenSettingsButton.IsEnabled = false;
}
}
private void OpenSettings()
{
// Open the call origin settings page.
PhoneCallOriginManager.ShowPhoneCallOriginSettingsUI();
}
private void CheckState()
{
bool isActive = PhoneCallOriginManager.IsCurrentAppActiveCallOriginApp;
if (isActive)
{
rootPage.NotifyUser("This app is the active call origin app.", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("This app is not the active call origin app.", NotifyType.StatusMessage);
}
}
}
}

Просмотреть файл

@ -1,63 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
using System;
using System.Diagnostics;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.Calls.Background;
using Windows.ApplicationModel.Calls.Provider;
namespace CallerIDBackgroundTask
{
public sealed class SampleCallerIDBackgroundTask : IBackgroundTask
{
//
// The Run method is the entry point of a background task.
//
public void Run(IBackgroundTaskInstance taskInstance)
{
// Associate a cancellation handler with the background task.
// Even though this task isn't performing much work, it can still be cancelled.
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
// Do the background task activity.
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
PhoneCallOriginDataRequestTriggerDetails callDetails = (PhoneCallOriginDataRequestTriggerDetails)taskInstance.TriggerDetails;
PhoneCallOrigin phoneCallOrigin = LocalLookupForCallerData(callDetails.PhoneNumber);
PhoneCallOriginManager.SetCallOrigin(callDetails.RequestId, phoneCallOrigin);
_deferral.Complete();
}
private PhoneCallOrigin LocalLookupForCallerData(String phoneNumber)
{
// Fake origin data for each incoming call.
PhoneCallOrigin phoneCallOrigin = new PhoneCallOrigin();
phoneCallOrigin.DisplayName = "Contoso";
phoneCallOrigin.Location = "Redmond, Washington, USA";
phoneCallOrigin.Category = "IT Services";
phoneCallOrigin.CategoryDescription = "Information technology services";
return phoneCallOrigin;
}
//
// Handles background task cancellation.
//
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
// Normally, we would signal the task to exit.
// However, our sample task has no async operations and is so short that
// we'll just let it run to completion instead of trying to cancel it.
}
}
}

Просмотреть файл

@ -1,126 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<SharedContentDir>$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), LICENSE))\SharedContent</SharedContentDir>
</PropertyGroup>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProjectGuid>{EE2A82C1-BC9B-5D63-A2A0-002435B47740}</ProjectGuid>
<OutputType>winmdobj</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CallerIDBackgroundTask</RootNamespace>
<AssemblyName>CallerIDBackgroundTask</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion>10.0.18362.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.18362.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<EnableDotNetNativeCompatibleProfile>true</EnableDotNetNativeCompatibleProfile>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
<PlatformTarget>ARM</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
<PlatformTarget>ARM</PlatformTarget>
<OutputPath>bin\ARM\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<PlatformTarget>x64</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<PlatformTarget>x64</PlatformTarget>
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<PlatformTarget>x86</PlatformTarget>
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UAP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<ItemGroup>
<Compile Include="CallerIDBackgroundTask.cs" />
<Compile Include="$(SharedContentDir)\cs\AssemblyInfo.cs">
<Link>Properties\AssemblyInfo.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<SDKReference Include="WindowsMobile, Version=10.0.18362.0">
<Name>Windows Mobile Extensions for the UWP %28WindowsMobile, Version=10.0.18362.0%29</Name>
</SDKReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>5.0.0</Version>
</PackageReference>
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' ">
<VisualStudioVersion>14.0</VisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

Просмотреть файл

@ -1,91 +0,0 @@
---
topic: sample
languages:
- cpp
- cppcx
- js
products:
- windows
- windows-uwp
---
# Geolocation sample
Shows how to use the Windows.Devices.Geolocation namespace to get the geographic location of the user's device
and track when the location changes in various ways.
After obtaining access to the user's location, an app can
* Retrieve the current location.
* Receiving events when the location changes.
* Receiving events when the device has entered or exited locations of interest.
* Receiving events when the device has spent significant time in a location (a "visit").
> **Note:** This sample is part of a large collection of UWP feature samples.
> If you are unfamiliar with Git and GitHub, you can download the entire collection as a
> [ZIP file](https://github.com/Microsoft/Windows-universal-samples/archive/master.zip), but be
> sure to unzip everything to access shared dependencies. For more info on working with the ZIP file,
> the samples collection, and GitHub, see [Get the UWP samples from GitHub](https://aka.ms/ovu2uq).
> For more samples, see the [Samples portal](https://aka.ms/winsamples) on the Windows Dev Center.
This sample also shows how to:
- **Use a [geofence](http://msdn.microsoft.com/library/windows/apps/dn263744):** Receive notifications when the user's device has entered or left an area of interest.
- **Handle changes in location permissions**: Register for the Geolocator's StatusChanged event and use the [StatusChangedEventArgs](http://msdn.microsoft.com/library/windows/apps/br225600) to determine the current position status.
- **Get location from a background task**
- **Handle geofencing events from a background task**
- **Handle geovisit events from a background task**
- **Obtain satellite data:** When available, use the [GeocoordinateSatelliteData](http://msdn.microsoft.com/library/windows/apps/jj635260) class to obtain additional information on the quality of the satellite based location data.
- **Display a toast:** Notify the user when a geofencing event has occurred in the background.
- **Refresh geofence binding:** Refresh the binding on resume and after removal of a geofence. Note that removal requires subscribing to removal events if a geofence is set as single use or a duration is set.
- **Request access to the user's location:** Request access to the user's location using the RequestAccessAsync method. Important: call the RequestAccessAsync before accessing the user's location. At that time, your app must be in the foreground and RequestAccessAsync must be called from the UI thread. Until the user grants your app permission to their location, your app can't access location data.
- **Track when the user visits a location:** Poll for or receive notifications when the user spends significant time in a location.
- **Help the user change location settings:** Link to location privacy settings from your app if the user revokes access to location while your app is in the foreground. Call the LaunchUriAsync method with the URI "ms-settings://privacy/location".
Geofences need to be created in the Foreground Geofencing scenario (Scenario 4) and then you can go to Background Geofencing scenario (Scenario 5) to register for background geofencing events.
The Geolocation sample formats and parses time and dates in the en-US locale using the Gregorian calendar and 24-hour clock. To help other locales in entering data the edit fields have a format example shown below the control. For example, Start Time would be entered mm/dd/yyyy hh:mm:ss format. February 2, 2014 at 10:34 pm would be written 2/2/2014 22:34:00. For the Dwell Time and Duration the format is dd:hh:mm:ss so a time span of 7 days, 23 hours, 45 minutes and 55 seconds would be written as 7:23:45:55.
### Declaring the Location capability
This sample requires that location capability be set in the *Package.appxmanifest* file to allow the app to access location at runtime. The capability can be set in the app manifest using Microsoft Visual Studio.
## Related topics
[Get current location](https://msdn.microsoft.com/library/windows/apps/mt219698)
[Windows.Devices.Geolocation](http://msdn.microsoft.com/library/windows/apps/br225603)
[Windows.Devices.Geolocation.Geofencing](https://msdn.microsoft.com/library/windows/apps/dn263744)
[Guidelines for location-aware apps](https://msdn.microsoft.com/library/windows/apps/hh465148)
## Related samples
[Traffic App sample](https://github.com/microsoft/windows-appsample-trafficapp/)
[Lunch Scheduler app sample](https://github.com/Microsoft/Windows-appsample-lunch-scheduler)
## System requirements
**Client:** Windows 10
**Server:** Windows Server 2016 Technical Preview
**Phone:** Windows 10
## Build the sample
1. If you download the samples ZIP, be sure to unzip the entire archive, not just the folder with the sample you want to build.
2. Start Microsoft Visual Studio 2017 and select **File** \> **Open** \> **Project/Solution**.
3. Starting in the folder where you unzipped the samples, go to the Samples subfolder, then the subfolder for this specific sample, then the subfolder for your preferred language (C++, C#, or JavaScript). Double-click the Visual Studio Solution (.sln) file.
4. Press Ctrl+Shift+B, or select **Build** \> **Build Solution**.
## Run the sample
The next steps depend on whether you just want to deploy the sample or you want to both deploy and run it.
### Deploying the sample
- Select Build > Deploy Solution.
### Deploying and running the sample
- To debug the sample and then run it, press F5 or select Debug > Start Debugging. To run the sample without debugging, press Ctrl+F5 or selectDebug > Start Without Debugging.

Просмотреть файл

@ -1,232 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup>
<SharedContentDir>$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), LICENSE))\SharedContent</SharedContentDir>
</PropertyGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{f7101922-3c9c-59df-9cdc-93973d37d0d8}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<ProjectName>BackgroundTask</ProjectName>
<RootNamespace>BackgroundTask</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
<AppContainerApplication>true</AppContainerApplication>
<ApplicationType>Windows Store</ApplicationType>
<ApplicationTypeRevision>10.0</ApplicationTypeRevision>
<WindowsTargetPlatformVersion>10.0.18362.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>10.0.18362.0</WindowsTargetPlatformMinVersion>
<EnableDotNetNativeCompatibleProfile>true</EnableDotNetNativeCompatibleProfile>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<GenerateManifest>false</GenerateManifest>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PreprocessorDefinitions>_WINRT_DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>28204</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PreprocessorDefinitions>_WINRT_DLL;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>28204</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PreprocessorDefinitions>_WINRT_DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>28204</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PreprocessorDefinitions>_WINRT_DLL;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>28204</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PreprocessorDefinitions>_WINRT_DLL;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>28204</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>Use</PrecompiledHeader>
<PreprocessorDefinitions>_WINRT_DLL;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeaderFile>pch.h</PrecompiledHeaderFile>
<PrecompiledHeaderOutputFile>$(IntDir)pch.pch</PrecompiledHeaderOutputFile>
<AdditionalUsingDirectories>$(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories)</AdditionalUsingDirectories>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>28204</DisableSpecificWarnings>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<AdditionalDependencies>runtimeobject.lib;%(AdditionalDependencies)</AdditionalDependencies>
<IgnoreAllDefaultLibraries>false</IgnoreAllDefaultLibraries>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="LocationBackgroundTask.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="VisitBackgroundTask.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="LocationBackgroundTask.cpp" />
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="VisitBackgroundTask.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

Просмотреть файл

@ -1,371 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
// LocationBackgroundTask.cpp
#include "pch.h"
#include "LocationBackgroundTask.h"
using namespace BackgroundTask;
using namespace Concurrency;
using namespace Platform;
using namespace Windows::ApplicationModel::Background;
using namespace Windows::Data::Json;
using namespace Windows::Data::Xml::Dom;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Devices::Geolocation::Geofencing;
using namespace Windows::Foundation;
using namespace Windows::Globalization::DateTimeFormatting;
using namespace Windows::Storage;
using namespace Windows::UI::Notifications;
const int oneHundredNanosecondsPerSecond = 10000000; // conversion from 100 nano-second resolution to seconds
const unsigned int maxEventDescriptors = 42; // Value determined by how many max length event descriptors (91 chars)
// stored as a JSON string can fit in 8K (max allowed for local settings)
LocationBackgroundTask::LocationBackgroundTask()
{
}
LocationBackgroundTask::~LocationBackgroundTask()
{
}
void LocationBackgroundTask::Run(IBackgroundTaskInstance^ taskInstance)
{
// Get the deferral object from the task instance
Platform::Agile<BackgroundTaskDeferral> deferral(taskInstance->GetDeferral());
// Associate a cancellation handler with the background task
taskInstance->Canceled += ref new BackgroundTaskCanceledEventHandler(this, &LocationBackgroundTask::OnCanceled);
Geolocator^ geolocator = ref new Geolocator();
task<Geoposition^> geopositionTask(geolocator->GetGeopositionAsync(), geopositionTaskTokenSource.get_token());
geopositionTask.then([this, deferral, geolocator](task<Geoposition^> getPosTask)
{
DateTimeFormatter^ dateFormatter = ref new DateTimeFormatter("longtime");
auto settings = ApplicationData::Current->LocalSettings;
try
{
// Get will throw an exception if the task was canceled or failed with an error
Geoposition^ pos = getPosTask.get();
// Write to LocalSettings to indicate that this background task ran
settings->Values->Insert("Status", "Time: " + dateFormatter->Format(pos->Coordinate->Timestamp));
settings->Values->Insert("Latitude", pos->Coordinate->Point->Position.Latitude.ToString());
settings->Values->Insert("Longitude", pos->Coordinate->Point->Position.Longitude.ToString());
settings->Values->Insert("Accuracy", pos->Coordinate->Accuracy.ToString());
}
catch (Platform::AccessDeniedException^)
{
// Write to LocalSettings to indicate that this background task ran
settings->Values->Insert("Status", "Disabled");
settings->Values->Insert("Latitude", "No data");
settings->Values->Insert("Longitude", "No data");
settings->Values->Insert("Accuracy", "No data");
}
catch (task_canceled&)
{
}
catch (Exception^ ex)
{
settings->Values->Insert("Latitude", "No data");
settings->Values->Insert("Longitude", "No data");
settings->Values->Insert("Accuracy", "No data");
#if (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP)
// If there are no location sensors GetGeopositionAsync()
// will timeout -- that is acceptable.
if (ex->HResult == HRESULT_FROM_WIN32(WAIT_TIMEOUT))
{
settings->Values->Insert("Status", "Operation accessing location sensors timed out. Possibly there are no location sensors.");
}
else
#endif
{
settings->Values->Insert("Status", ex->ToString());
}
}
// Indicate that the background task has completed
deferral->Complete();
});
}
// Handles background task cancellation
void LocationBackgroundTask::OnCanceled(IBackgroundTaskInstance^ taskInstance, BackgroundTaskCancellationReason reason)
{
// Cancel the async operation
geopositionTaskTokenSource.cancel();
}
GeofenceBackgroundTask::GeofenceBackgroundTask()
{
geofenceBackgroundEvents = ref new Platform::Collections::Vector<Platform::String^>();
}
GeofenceBackgroundTask::~GeofenceBackgroundTask()
{
}
void GeofenceBackgroundTask::Invoke(Windows::Foundation::IAsyncAction^ asyncInfo, Windows::Foundation::AsyncStatus asyncStatus)
{
}
void GeofenceBackgroundTask::Run(IBackgroundTaskInstance^ taskInstance)
{
// Get the deferral object from the task instance
Platform::Agile<BackgroundTaskDeferral> deferral(taskInstance->GetDeferral());
// Associate a cancellation handler with the background task
taskInstance->Canceled += ref new BackgroundTaskCanceledEventHandler(this, &GeofenceBackgroundTask::OnCanceled);
Geolocator^ geolocator = ref new Geolocator();
task<Geoposition^> geopositionTask(geolocator->GetGeopositionAsync(), geopositionTaskTokenSource.get_token());
geopositionTask.then([this, deferral, geolocator](task<Geoposition^> getPosTask)
{
auto settings = ApplicationData::Current->LocalSettings;
try
{
// Get will throw an exception if the task was canceled or failed with an error
Geoposition^ pos = getPosTask.get();
GetGeofenceStateChangedReports(pos);
}
catch (Platform::AccessDeniedException^)
{
// Write to LocalSettings to indicate that this background task ran
settings->Values->Insert("Status", "Disabled");
}
catch (task_canceled&)
{
}
catch (Exception^ ex)
{
#if (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP)
// If there are no location sensors GetGeopositionAsync()
// will timeout -- that is acceptable.
if (ex->HResult == HRESULT_FROM_WIN32(WAIT_TIMEOUT))
{
settings->Values->Insert("Status", "Operation accessing location sensors timed out. Possibly there are no location sensors.");
}
else
#endif
{
settings->Values->Insert("Status", ex->ToString());
}
}
// Indicate that the background task has completed
deferral->Complete();
});
}
// Handles background task cancellation
void GeofenceBackgroundTask::OnCanceled(IBackgroundTaskInstance^ taskInstance, BackgroundTaskCancellationReason reason)
{
// Cancel the async operation
geopositionTaskTokenSource.cancel();
}
// Stores geofence events into local settings
void GeofenceBackgroundTask::GetGeofenceStateChangedReports(Geoposition^ pos)
{
FillEventCollectionWithExistingEvents();
GeofenceMonitor^ monitor = GeofenceMonitor::Current;
Geoposition^ posLastKnown = monitor->LastKnownGeoposition;
DateTime eventDateTime = posLastKnown->Coordinate->Timestamp;
auto calendar = ref new Windows::Globalization::Calendar();
auto us = ref new Platform::Collections::Vector<String^>();
us->Append("en-US");
auto formatterLongTime = ref new Windows::Globalization::DateTimeFormatting::DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", us, "US", Windows::Globalization::CalendarIdentifiers::Gregorian, Windows::Globalization::ClockIdentifiers::TwentyFourHour);
bool eventOfInterest = true;
// NOTE TO DEVELOPER:
// These events can be filtered out if the
// geofence event time is stale.
calendar->SetToNow();
DateTime nowDateTime = calendar->GetDateTime();
DateTime diffDateTime;
diffDateTime.UniversalTime = nowDateTime.UniversalTime - eventDateTime.UniversalTime;
long long deltaInSeconds = diffDateTime.UniversalTime / oneHundredNanosecondsPerSecond;
// NOTE TO DEVELOPER:
// If the time difference between the geofence event and now is too large
// the eventOfInterest should be set to false.
if (true == eventOfInterest)
{
// NOTE TO DEVELOPER:
// This event can be filtered out if the
// geofence event location is too far away.
if ((posLastKnown->Coordinate->Point->Position.Latitude != pos->Coordinate->Point->Position.Latitude) ||
(posLastKnown->Coordinate->Point->Position.Longitude != pos->Coordinate->Point->Position.Longitude))
{
// NOTE TO DEVELOPER:
// Use an algorithm like the Haversine formula or Vincenty's formulae to determine
// the distance between the current location (pos->Coordinate)
// and the location of the geofence event (latitudeEvent/longitudeEvent).
// If too far apart set eventOfInterest to false to
// filter the event out.
}
if (true == eventOfInterest)
{
// Retreive a vector of geofence state changed reports
auto reports = monitor->ReadReports();
unsigned int count = reports->Size;
String^ geofenceItemEvent = nullptr;
int numEventsOfInterest = count;
for (unsigned int loop = 0; loop < count; loop++)
{
auto report = reports->GetAt(loop);
GeofenceState state = report->NewState;
geofenceItemEvent = report->Geofence->Id + " " + formatterLongTime->Format(eventDateTime);
if (state == GeofenceState::Removed)
{
GeofenceRemovalReason reason = report->RemovalReason;
if (reason == GeofenceRemovalReason::Expired)
{
geofenceItemEvent += " (Removed/Expired)";
}
else if (reason == GeofenceRemovalReason::Used)
{
geofenceItemEvent += " (Removed/Used)";
}
}
else if (state == GeofenceState::Entered)
{
geofenceItemEvent += " (Entered)";
}
else if (state == GeofenceState::Exited)
{
geofenceItemEvent += " (Exited)";
}
AddEventDescription(geofenceItemEvent);
}
if (true == eventOfInterest && 0 != numEventsOfInterest)
{
SaveExistingEvents();
// NOTE: Other notification mechanisms can be used here, such as Badge and/or Tile updates.
DoToast(numEventsOfInterest, geofenceItemEvent);
}
}
}
}
// Helper method to pop a toast
void GeofenceBackgroundTask::DoToast(int numEventsOfInterest, Platform::String^ eventName)
{
// pop a toast for each geofence event
ToastNotifier^ ToastNotifier = ToastNotificationManager::CreateToastNotifier();
// Create a two line toast and add audio reminder
// Here the xml that will be passed to the
// ToastNotification for the toast is retrieved
XmlDocument^ toastXml = ToastNotificationManager::GetTemplateContent(ToastTemplateType::ToastText02);
// Set both lines of text
XmlNodeList^ nodeList = toastXml->GetElementsByTagName("text");
nodeList->Item(0)->AppendChild(toastXml->CreateTextNode("Geolocation Sample"));
if (1 == numEventsOfInterest)
{
nodeList->Item(1)->AppendChild(toastXml->CreateTextNode(eventName));
}
else
{
auto secondLine = "There are " + numEventsOfInterest + " new geofence events";
nodeList->Item(1)->AppendChild(toastXml->CreateTextNode(secondLine));
}
// now create a xml node for the audio source
IXmlNode^ toastNode = toastXml->SelectSingleNode("/toast");
XmlElement^ audio = toastXml->CreateElement("audio");
audio->SetAttribute("src", "ms-winsoundevent:Notification.SMS");
ToastNotification^ toast = ref new ToastNotification(toastXml);
ToastNotifier->Show(toast);
}
void GeofenceBackgroundTask::FillEventCollectionWithExistingEvents()
{
auto settings = ApplicationData::Current->LocalSettings->Values;
if (settings->HasKey("BackgroundGeofenceEventCollection"))
{
String^ geofenceEvent = safe_cast<String^>(settings->Lookup("BackgroundGeofenceEventCollection"));
if (0 != geofenceEvent->Length())
{
auto events = JsonValue::Parse(geofenceEvent)->GetArray();
// NOTE: the events are accessed in reverse order
// because the events were added to JSON from
// newer to older. AddEventDescription() adds
// each new entry to the beginning of the collection.
for (int pos = events->Size - 1; pos >= 0; pos--)
{
auto element = events->GetAt(pos);
AddEventDescription(element->GetString());
}
}
}
}
void GeofenceBackgroundTask::SaveExistingEvents()
{
auto jsonArray = ref new JsonArray();
for (auto eventDescriptor : geofenceBackgroundEvents)
{
jsonArray->Append(JsonValue::CreateStringValue(eventDescriptor->ToString()));
}
String^ jsonString = jsonArray->Stringify();
auto settings = ApplicationData::Current->LocalSettings->Values;
settings->Insert("BackgroundGeofenceEventCollection", jsonString);
}
void GeofenceBackgroundTask::AddEventDescription(Platform::String^ eventDescription)
{
if (geofenceBackgroundEvents->Size == maxEventDescriptors)
{
geofenceBackgroundEvents->RemoveAtEnd();
}
geofenceBackgroundEvents->InsertAt(0, eventDescription);
}

Просмотреть файл

@ -1,54 +0,0 @@
//*********************************************************
//
// 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 BackgroundTask
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class LocationBackgroundTask sealed : public Windows::ApplicationModel::Background::IBackgroundTask
{
public:
LocationBackgroundTask();
virtual void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance);
private:
void OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason);
~LocationBackgroundTask();
Concurrency::cancellation_token_source geopositionTaskTokenSource;
};
[Windows::Foundation::Metadata::WebHostHidden]
public ref class GeofenceBackgroundTask sealed : public Windows::ApplicationModel::Background::IBackgroundTask
{
public:
GeofenceBackgroundTask();
virtual void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance);
void Invoke(Windows::Foundation::IAsyncAction^ asyncInfo, Windows::Foundation::AsyncStatus asyncStatus);
private:
void OnCanceled(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance, Windows::ApplicationModel::Background::BackgroundTaskCancellationReason reason);
void GetGeofenceStateChangedReports(Windows::Devices::Geolocation::Geoposition^ pos);
void DoToast(int numEventsOfInterest, Platform::String^ eventName);
void FillEventCollectionWithExistingEvents();
void SaveExistingEvents();
void AddEventDescription(Platform::String^ eventDescription);
~GeofenceBackgroundTask();
Concurrency::cancellation_token_source geopositionTaskTokenSource;
Platform::Collections::Vector<Platform::String^>^ geofenceBackgroundEvents;
};
}

Просмотреть файл

@ -1,192 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
// VisitBackgroundTask.cpp
#include "pch.h"
#include "VisitBackgroundTask.h"
using namespace BackgroundTask;
using namespace Concurrency;
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::ApplicationModel::Background;
using namespace Windows::Data::Json;
using namespace Windows::Data::Xml::Dom;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Globalization;
using namespace Windows::Globalization::DateTimeFormatting;
using namespace Windows::Storage;
using namespace Windows::UI::Notifications;
const unsigned int maxEventDescriptors = 42; // Value determined by how many max length event descriptors (91 chars)
// stored as a JSON string can fit in 8K (max allowed for local settings)
VisitBackgroundTask::VisitBackgroundTask()
: _visitBackgroundEvents(ref new Vector<String^>())
{
}
VisitBackgroundTask::~VisitBackgroundTask()
{
}
void VisitBackgroundTask::Run(IBackgroundTaskInstance^ taskInstance)
{
// Get the deferral object from the task instance
BackgroundTaskDeferral^ deferral = taskInstance->GetDeferral();
GeovisitTriggerDetails^ triggerDetails = safe_cast<GeovisitTriggerDetails^>(taskInstance->TriggerDetails);
GetVisitReports(triggerDetails);
// Indicate that the background task has completed
deferral->Complete();
}
// Gets the new visits reports and saves them into local settings
void VisitBackgroundTask::GetVisitReports(GeovisitTriggerDetails^ triggerDetails)
{
// First fill the _visitBackgroundEvents with previous existing reports saved in local settings.
_visitBackgroundEvents->Clear();
FillReportCollectionWithExistingReports();
// Read reports from the triggerDetails.
// If the user revoked location access, ReadReports returns 0 reports.
IVectorView<Geovisit^>^ reports = triggerDetails->ReadReports();
auto us = ref new Vector<String^>({ "en-US" });
auto formatterLongTime = ref new DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", us, "US", CalendarIdentifiers::Gregorian, ClockIdentifiers::TwentyFourHour);
unsigned int count = reports->Size;
String^ visitItemEvent = nullptr;
for (unsigned int index = 0; index < count; index++)
{
Geovisit^ report = reports->GetAt(index);
visitItemEvent = formatterLongTime->Format(report->Timestamp);
visitItemEvent += " " + report->StateChange.ToString();
// Check if the report has a valid position.
if (report->Position != nullptr)
{
Geoposition^ pos = report->Position;
visitItemEvent += " (" +
pos->Coordinate->Point->Position.Latitude.ToString() + "," +
pos->Coordinate->Point->Position.Longitude.ToString() +
")";
}
// Now add each new visit report to _VisitBackgroundEvents.
AddVisitReport(visitItemEvent);
}
if (0 != count)
{
// Save all the reports back to the local settings.
SaveExistingEvents();
// NOTE: Other notification mechanisms can be used here, such as Badge and/or Tile updates.
DoToast(count, visitItemEvent);
}
}
// Helper method to pop a toast
void VisitBackgroundTask::DoToast(int numEventsOfInterest, String^ eventName)
{
// pop a toast for each geofence event
ToastNotifier^ ToastNotifier = ToastNotificationManager::CreateToastNotifier();
// Create a two line toast and add audio reminder
// Here the xml that will be passed to the
// ToastNotification for the toast is retrieved
XmlDocument^ toastXml = ToastNotificationManager::GetTemplateContent(ToastTemplateType::ToastText02);
// Set both lines of text
XmlNodeList^ nodeList = toastXml->GetElementsByTagName("text");
nodeList->Item(0)->AppendChild(toastXml->CreateTextNode("Geolocation Sample"));
if (1 == numEventsOfInterest)
{
nodeList->Item(1)->AppendChild(toastXml->CreateTextNode(eventName));
}
else
{
auto secondLine = "There are " + numEventsOfInterest + " new visit events";
nodeList->Item(1)->AppendChild(toastXml->CreateTextNode(secondLine));
}
// now create a xml node for the audio source
IXmlNode^ toastNode = toastXml->SelectSingleNode("/toast");
XmlElement^ audio = toastXml->CreateElement("audio");
audio->SetAttribute("src", "ms-winsoundevent:Notification.SMS");
ToastNotification^ toast = ref new ToastNotification(toastXml);
ToastNotifier->Show(toast);
}
void VisitBackgroundTask::FillReportCollectionWithExistingReports()
{
auto settings = ApplicationData::Current->LocalSettings->Values;
if (settings->HasKey("BackgroundVisitEventCollection"))
{
String^ visitEvent = safe_cast<String^>(settings->Lookup("BackgroundVisitEventCollection"));
if (0 != visitEvent->Length())
{
auto events = JsonValue::Parse(visitEvent)->GetArray();
// NOTE: the events are accessed in reverse order
// because the events were added to JSON from
// newer to older. AddVisitReport() adds
// each new entry to the beginning of the collection
// and throws away the last entry if the collection gets too large.
for (int pos = events->Size - 1; pos >= 0; pos--)
{
auto element = events->GetAt(pos);
AddVisitReport(element->GetString());
}
}
}
}
void VisitBackgroundTask::SaveExistingEvents()
{
auto jsonArray = ref new JsonArray();
for (auto eventDescriptor : _visitBackgroundEvents)
{
jsonArray->Append(JsonValue::CreateStringValue(eventDescriptor->ToString()));
}
String^ jsonString = jsonArray->Stringify();
auto settings = ApplicationData::Current->LocalSettings->Values;
settings->Insert("BackgroundVisitEventCollection", jsonString);
}
void VisitBackgroundTask::AddVisitReport(String^ eventDescription)
{
if (_visitBackgroundEvents->Size == maxEventDescriptors)
{
_visitBackgroundEvents->RemoveAtEnd();
}
_visitBackgroundEvents->InsertAt(0, eventDescription);
}

Просмотреть файл

@ -1,36 +0,0 @@
//*********************************************************
//
// 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 BackgroundTask
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class VisitBackgroundTask sealed : public Windows::ApplicationModel::Background::IBackgroundTask
{
public:
VisitBackgroundTask();
virtual void Run(Windows::ApplicationModel::Background::IBackgroundTaskInstance^ taskInstance);
private:
void GetVisitReports(Windows::Devices::Geolocation::GeovisitTriggerDetails^ triggerDetails);
void DoToast(int numEventsOfInterest, Platform::String^ eventName);
void FillReportCollectionWithExistingReports();
void SaveExistingEvents();
void AddVisitReport(Platform::String^ eventDescription);
~VisitBackgroundTask();
Platform::Collections::Vector<Platform::String^>^ _visitBackgroundEvents;
};
}

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 1.1 KiB

Просмотреть файл

@ -1,12 +0,0 @@
//*********************************************************
//
// 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"

Просмотреть файл

@ -1,15 +0,0 @@
//*********************************************************
//
// 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 <collection.h>
#include <ppltasks.h>

Просмотреть файл

@ -1,57 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26228.4
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Geolocation", "GeolocationCPP\Geolocation.vcxproj", "{C65D85B2-1E0C-5351-8281-71DF477D6B4C}"
ProjectSection(ProjectDependencies) = postProject
{F7101922-3C9C-59DF-9CDC-93973D37D0D8} = {F7101922-3C9C-59DF-9CDC-93973D37D0D8}
EndProjectSection
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BackgroundTask", "BackgroundTask\BackgroundTask.vcxproj", "{F7101922-3C9C-59DF-9CDC-93973D37D0D8}"
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
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Debug|ARM.ActiveCfg = Debug|ARM
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Debug|ARM.Build.0 = Debug|ARM
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Debug|ARM.Deploy.0 = Debug|ARM
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Debug|x64.ActiveCfg = Debug|x64
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Debug|x64.Build.0 = Debug|x64
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Debug|x64.Deploy.0 = Debug|x64
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Debug|x86.ActiveCfg = Debug|Win32
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Debug|x86.Build.0 = Debug|Win32
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Debug|x86.Deploy.0 = Debug|Win32
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Release|ARM.ActiveCfg = Release|ARM
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Release|ARM.Build.0 = Release|ARM
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Release|ARM.Deploy.0 = Release|ARM
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Release|x64.ActiveCfg = Release|x64
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Release|x64.Build.0 = Release|x64
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Release|x64.Deploy.0 = Release|x64
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Release|x86.ActiveCfg = Release|Win32
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Release|x86.Build.0 = Release|Win32
{C65D85B2-1E0C-5351-8281-71DF477D6B4C}.Release|x86.Deploy.0 = Release|Win32
{F7101922-3C9C-59DF-9CDC-93973D37D0D8}.Debug|ARM.ActiveCfg = Debug|ARM
{F7101922-3C9C-59DF-9CDC-93973D37D0D8}.Debug|ARM.Build.0 = Debug|ARM
{F7101922-3C9C-59DF-9CDC-93973D37D0D8}.Debug|x64.ActiveCfg = Debug|x64
{F7101922-3C9C-59DF-9CDC-93973D37D0D8}.Debug|x64.Build.0 = Debug|x64
{F7101922-3C9C-59DF-9CDC-93973D37D0D8}.Debug|x86.ActiveCfg = Debug|Win32
{F7101922-3C9C-59DF-9CDC-93973D37D0D8}.Debug|x86.Build.0 = Debug|Win32
{F7101922-3C9C-59DF-9CDC-93973D37D0D8}.Release|ARM.ActiveCfg = Release|ARM
{F7101922-3C9C-59DF-9CDC-93973D37D0D8}.Release|ARM.Build.0 = Release|ARM
{F7101922-3C9C-59DF-9CDC-93973D37D0D8}.Release|x64.ActiveCfg = Release|x64
{F7101922-3C9C-59DF-9CDC-93973D37D0D8}.Release|x64.Build.0 = Release|x64
{F7101922-3C9C-59DF-9CDC-93973D37D0D8}.Release|x86.ActiveCfg = Release|Win32
{F7101922-3C9C-59DF-9CDC-93973D37D0D8}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Просмотреть файл

@ -1,77 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// GeofenceItem.cpp
// Implementation of the GeofenceItem class
//
#include "pch.h"
#include "GeofenceItem.h"
using namespace SDKTemplate;
using namespace SDKTemplate::GeolocationCPP;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Devices::Geolocation::Geofencing;
Windows::Devices::Geolocation::Geofencing::Geofence^ GeofenceItem::Geofence::get()
{
return geofence;
}
Platform::String^ GeofenceItem::Id::get()
{
return geofence->Id;
}
double GeofenceItem::Latitude::get()
{
Geocircle^ circle = safe_cast<Geocircle^> (geofence->Geoshape);
return circle->Center.Latitude;
}
double GeofenceItem::Longitude::get()
{
Geocircle^ circle = safe_cast<Geocircle^> (geofence->Geoshape);
return circle->Center.Longitude;
}
double GeofenceItem::Radius::get()
{
Geocircle^ circle = safe_cast<Geocircle^> (geofence->Geoshape);
return circle->Radius;
}
long long GeofenceItem::DwellTime::get()
{
return geofence->DwellTime.Duration;
}
bool GeofenceItem::SingleUse::get()
{
return geofence->SingleUse;
}
unsigned int GeofenceItem::MonitoredStates::get()
{
return safe_cast<int>(geofence->MonitoredStates);
}
long long GeofenceItem::Duration::get()
{
return geofence->Duration.Duration;
}
long long GeofenceItem::StartTime::get()
{
return geofence->StartTime.UniversalTime;
}

Просмотреть файл

@ -1,100 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// GeofenceItem.h
// Declaration of the GeofenceItem class
//
#pragma once
namespace SDKTemplate
{
namespace GeolocationCPP
{
// Since data binding uses Platform::Collections::Vector<Object^>^
// the GeofenceItem must be implemented as a WinRT object.
// This means that native data types cannot be used in
// the interface.
// Note that this is different than the
// implementation in C# where native types
// are allowed because the collection uses
// System.Collections.ObjectModel.ObservableCollection<GeofenceItem>
// but System isn't available in C++ Windows Runtime apps.
// Also note the metadata that allows this class
// to be used in data binding.
// Also note that since System isn't available
// GeofenceItem does not implement IEquatable to allow
// removal of objects in the collection
[Windows::UI::Xaml::Data::Bindable]
public ref class GeofenceItem sealed
{
private:
Windows::Devices::Geolocation::Geofencing::Geofence^ geofence;
public:
GeofenceItem(Windows::Devices::Geolocation::Geofencing::Geofence^ geofence)
{
this->geofence = geofence;
}
property Windows::Devices::Geolocation::Geofencing::Geofence^ Geofence
{
Windows::Devices::Geolocation::Geofencing::Geofence^ get();
}
property Platform::String^ Id
{
Platform::String^ get();
}
property double Latitude
{
double get();
}
property double Longitude
{
double get();
}
property double Radius
{
double get();
}
property long long DwellTime
{
long long get();
}
property bool SingleUse
{
bool get();
}
property unsigned int MonitoredStates
{
unsigned int get();
}
property long long Duration
{
long long get();
}
property long long StartTime
{
long long get();
}
};
}
}

Просмотреть файл

@ -1,284 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<SharedContentDir>$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), LICENSE))\SharedContent</SharedContentDir>
</PropertyGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{c65d85b2-1e0c-5351-8281-71df477d6b4c}</ProjectGuid>
<RootNamespace>SDKTemplate</RootNamespace>
<DefaultLanguage>en-US</DefaultLanguage>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
<AppContainerApplication>true</AppContainerApplication>
<ApplicationType>Windows Store</ApplicationType>
<ApplicationTypeRevision>10.0</ApplicationTypeRevision>
<WindowsTargetPlatformVersion>10.0.18362.0</WindowsTargetPlatformVersion>
<WindowsTargetPlatformMinVersion>10.0.18362.0</WindowsTargetPlatformMinVersion>
<EnableDotNetNativeCompatibleProfile>true</EnableDotNetNativeCompatibleProfile>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
</PropertyGroup>
<PropertyGroup>
<IncludePath>$(VC_IncludePath);$(UniversalCRT_IncludePath);$(WindowsSDK_IncludePath);$(SharedContentDir)\cpp</IncludePath>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
<ClCompile>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
<ClCompile>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<AdditionalOptions>/bigobj %(AdditionalOptions)</AdditionalOptions>
<DisableSpecificWarnings>4453;28204</DisableSpecificWarnings>
</ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="GeofenceItem.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="$(SharedContentDir)\cpp\App.xaml.h">
<DependentUpon>$(SharedContentDir)\xaml\App.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="$(SharedContentDir)\cpp\MainPage.xaml.h">
<DependentUpon>$(SharedContentDir)\cpp\MainPage.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="SampleConfiguration.h" />
<ClInclude Include="Scenario1_TrackPosition.xaml.h">
<DependentUpon>Scenario1_TrackPosition.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="Scenario2_GetPosition.xaml.h">
<DependentUpon>Scenario2_GetPosition.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="Scenario3_BackgroundTask.xaml.h">
<DependentUpon>Scenario3_BackgroundTask.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="Scenario4_ForegroundGeofence.xaml.h">
<DependentUpon>Scenario4_ForegroundGeofence.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="Scenario5_GeofenceBackgroundTask.xaml.h">
<DependentUpon>Scenario5_GeofenceBackgroundTask.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="Scenario6_GetLastVisit.xaml.h">
<DependentUpon>Scenario6_GetLastVisit.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="Scenario7_ForegroundVisits.xaml.h">
<DependentUpon>Scenario7_ForegroundVisits.xaml</DependentUpon>
</ClInclude>
<ClInclude Include="Scenario8_VisitsBackgroundTask.xaml.h">
<DependentUpon>Scenario8_VisitsBackgroundTask.xaml</DependentUpon>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="$(SharedContentDir)\xaml\App.xaml">
<SubType>Designer</SubType>
</ApplicationDefinition>
<Page Include="$(SharedContentDir)\cpp\MainPage.xaml">
<SubType>Designer</SubType>
</Page>
<Page Include="Scenario1_TrackPosition.xaml" />
<Page Include="Scenario2_GetPosition.xaml" />
<Page Include="Scenario3_BackgroundTask.xaml" />
<Page Include="Scenario4_ForegroundGeofence.xaml" />
<Page Include="Scenario5_GeofenceBackgroundTask.xaml" />
<Page Include="$(SharedContentDir)\xaml\Styles.xaml">
<Link>Styles\Styles.xaml</Link>
</Page>
<Page Include="Scenario6_GetLastVisit.xaml">
<SubType>Designer</SubType>
</Page>
<Page Include="Scenario7_ForegroundVisits.xaml">
<SubType>Designer</SubType>
</Page>
<Page Include="Scenario8_VisitsBackgroundTask.xaml">
<SubType>Designer</SubType>
</Page>
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest">
<SubType>Designer</SubType>
</AppxManifest>
</ItemGroup>
<ItemGroup>
<ClCompile Include="$(SharedContentDir)\cpp\App.xaml.cpp">
<DependentUpon>$(SharedContentDir)\xaml\App.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="GeofenceItem.cpp" />
<ClCompile Include="$(SharedContentDir)\cpp\MainPage.xaml.cpp">
<DependentUpon>$(SharedContentDir)\cpp\MainPage.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="pch.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Create</PrecompiledHeader>
</ClCompile>
<ClCompile Include="SampleConfiguration.cpp" />
<ClCompile Include="Scenario1_TrackPosition.xaml.cpp">
<DependentUpon>Scenario1_TrackPosition.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="Scenario2_GetPosition.xaml.cpp">
<DependentUpon>Scenario2_GetPosition.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="Scenario3_BackgroundTask.xaml.cpp">
<DependentUpon>Scenario3_BackgroundTask.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="Scenario4_ForegroundGeofence.xaml.cpp">
<DependentUpon>Scenario4_ForegroundGeofence.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="Scenario4_ForegroundGeofenceHelpers.cpp" />
<ClCompile Include="Scenario5_GeofenceBackgroundTask.xaml.cpp">
<DependentUpon>Scenario5_GeofenceBackgroundTask.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="Scenario6_GetLastVisit.xaml.cpp">
<DependentUpon>Scenario6_GetLastVisit.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="Scenario7_ForegroundVisits.xaml.cpp">
<DependentUpon>Scenario7_ForegroundVisits.xaml</DependentUpon>
</ClCompile>
<ClCompile Include="Scenario8_VisitsBackgroundTask.xaml.cpp">
<DependentUpon>Scenario8_VisitsBackgroundTask.xaml</DependentUpon>
</ClCompile>
</ItemGroup>
<ItemGroup>
<Image Include="$(SharedContentDir)\media\microsoft-sdk.png">
<Link>Assets\microsoft-sdk.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\smalltile-sdk.png">
<Link>Assets\smalltile-sdk.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\badge-logo.png">
<Link>Assets\badge-logo.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\splash-sdk.png">
<Link>Assets\splash-sdk.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\squaretile-sdk.png">
<Link>Assets\squaretile-sdk.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\storelogo-sdk.png">
<Link>Assets\storelogo-sdk.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\tile-sdk.png">
<Link>Assets\tile-sdk.png</Link>
</Image>
<Image Include="$(SharedContentDir)\media\windows-sdk.png">
<Link>Assets\windows-sdk.png</Link>
</Image>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BackgroundTask\BackgroundTask.vcxproj">
<Project>{a4072f75-ff35-4895-8559-8b67d00ff210}</Project>
<Private>true</Private>
<ReferenceOutputAssembly>true</ReferenceOutputAssembly>
<LinkLibraryDependencies>true</LinkLibraryDependencies>
<UseLibraryDependencyInputs>false</UseLibraryDependencyInputs>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

Просмотреть файл

@ -1,85 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ApplicationDefinition Include="$(SharedContentDir)\xaml\App.xaml" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="$(SharedContentDir)\cpp\App.xaml.cpp" />
<ClCompile Include="GeofenceItem.cpp" />
<ClCompile Include="$(SharedContentDir)\cpp\MainPage.xaml.cpp" />
<ClCompile Include="pch.cpp" />
<ClCompile Include="SampleConfiguration.cpp" />
<ClCompile Include="Scenario1_TrackPosition.xaml.cpp" />
<ClCompile Include="Scenario2_GetPosition.xaml.cpp" />
<ClCompile Include="Scenario3_BackgroundTask.xaml.cpp" />
<ClCompile Include="Scenario4_ForegroundGeofence.xaml.cpp" />
<ClCompile Include="Scenario4_ForegroundGeofenceHelpers.cpp" />
<ClCompile Include="Scenario5_GeofenceBackgroundTask.xaml.cpp" />
<ClCompile Include="Scenario6_GetLastVisit.xaml.cpp" />
<ClCompile Include="Scenario7_ForegroundVisits.xaml.cpp" />
<ClCompile Include="Scenario8_VisitsBackgroundTask.xaml.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="GeofenceItem.h" />
<ClInclude Include="pch.h" />
<ClInclude Include="$(SharedContentDir)\cpp\App.xaml.h" />
<ClInclude Include="$(SharedContentDir)\cpp\MainPage.xaml.h" />
<ClInclude Include="SampleConfiguration.h" />
<ClInclude Include="Scenario1_TrackPosition.xaml.h" />
<ClInclude Include="Scenario2_GetPosition.xaml.h" />
<ClInclude Include="Scenario3_BackgroundTask.xaml.h" />
<ClInclude Include="Scenario4_ForegroundGeofence.xaml.h" />
<ClInclude Include="Scenario5_GeofenceBackgroundTask.xaml.h" />
<ClInclude Include="Scenario6_GetLastVisit.xaml.h" />
<ClInclude Include="Scenario7_ForegroundVisits.xaml.h" />
<ClInclude Include="Scenario8_VisitsBackgroundTask.xaml.h" />
</ItemGroup>
<ItemGroup>
<Image Include="$(SharedContentDir)\media\microsoft-sdk.png">
<Filter>Assets</Filter>
</Image>
<Image Include="$(SharedContentDir)\media\smalltile-sdk.png">
<Filter>Assets</Filter>
</Image>
<Image Include="$(SharedContentDir)\media\splash-sdk.png">
<Filter>Assets</Filter>
</Image>
<Image Include="$(SharedContentDir)\media\squaretile-sdk.png">
<Filter>Assets</Filter>
</Image>
<Image Include="$(SharedContentDir)\media\storelogo-sdk.png">
<Filter>Assets</Filter>
</Image>
<Image Include="$(SharedContentDir)\media\tile-sdk.png">
<Filter>Assets</Filter>
</Image>
<Image Include="$(SharedContentDir)\media\windows-sdk.png">
<Filter>Assets</Filter>
</Image>
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest" />
</ItemGroup>
<ItemGroup>
<Page Include="$(SharedContentDir)\cpp\MainPage.xaml" />
<Page Include="Scenario1_TrackPosition.xaml" />
<Page Include="Scenario2_GetPosition.xaml" />
<Page Include="Scenario3_BackgroundTask.xaml" />
<Page Include="Scenario4_ForegroundGeofence.xaml" />
<Page Include="Scenario5_GeofenceBackgroundTask.xaml" />
<Page Include="$(SharedContentDir)\xaml\Styles.xaml">
<Filter>Styles</Filter>
</Page>
<Page Include="Scenario6_GetLastVisit.xaml" />
<Page Include="Scenario7_ForegroundVisits.xaml" />
<Page Include="Scenario8_VisitsBackgroundTask.xaml" />
</ItemGroup>
<ItemGroup>
<Filter Include="Assets">
<UniqueIdentifier>{119187f1-6e63-4fad-b176-d51dedff9d05}</UniqueIdentifier>
</Filter>
<Filter Include="Styles">
<UniqueIdentifier>{90ddf119-2d47-4176-b08f-d9217b81efec}</UniqueIdentifier>
</Filter>
</ItemGroup>
</Project>

Просмотреть файл

@ -1,67 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
IgnorableNamespaces="uap mp">
<Identity
Name="Microsoft.SDKSamples.GeolocationCPP.CPP"
Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US"
Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="6a4011e8-a8d4-4312-9668-2a665f802291" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>GeolocationCPP</DisplayName>
<PublisherDisplayName>Microsoft Corporation</PublisherDisplayName>
<Logo>Assets\StoreLogo-sdk.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.16299.0" MaxVersionTested="10.0.18362.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate"/>
</Resources>
<Applications>
<Application Id="App"
Executable="$targetnametoken$.exe"
EntryPoint="GeolocationCPP.App">
<uap:VisualElements
DisplayName="GeolocationCPP"
Square150x150Logo="Assets\squareTile-sdk.png"
Square44x44Logo="Assets\smallTile-sdk.png"
Description="GeolocationCPP"
BackgroundColor="#00B2F0">
<uap:SplashScreen Image="Assets\Splash-sdk.png" />
<uap:LockScreen Notification="badge" BadgeLogo="Assets\badge-logo.png" />
</uap:VisualElements>
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTask.LocationBackgroundTask" >
<BackgroundTasks>
<Task Type="timer" />
</BackgroundTasks>
</Extension>
<Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTask.GeofenceBackgroundTask">
<BackgroundTasks>
<Task Type="location" />
</BackgroundTasks>
</Extension>
<Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTask.VisitBackgroundTask">
<BackgroundTasks>
<Task Type="location" />
</BackgroundTasks>
</Extension>
</Extensions>
</Application>
</Applications>
<Capabilities>
<DeviceCapability Name="location"/>
</Capabilities>
</Package>

Просмотреть файл

@ -1,20 +0,0 @@
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
#include "pch.h"
#include "MainPage.xaml.h"
#include "SampleConfiguration.h"
using namespace SDKTemplate;
Platform::Array<Scenario>^ MainPage::scenariosInner = ref new Platform::Array<Scenario>
{
{ "Track position", "SDKTemplate.GeolocationCPP.Scenario1" },
{ "Get position", "SDKTemplate.GeolocationCPP.Scenario2" },
{ "Background position", "SDKTemplate.GeolocationCPP.Scenario3" },
{ "Foreground geofencing", "SDKTemplate.GeolocationCPP.Scenario4" },
{ "Background geofencing", "SDKTemplate.GeolocationCPP.Scenario5" },
{ "Get last visit", "SDKTemplate.GeolocationCPP.Scenario6" },
{ "Foreground visit monitoring", "SDKTemplate.GeolocationCPP.Scenario7" },
{ "Background visit monitoring", "SDKTemplate.GeolocationCPP.Scenario8" },
};

Просмотреть файл

@ -1,39 +0,0 @@
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
#pragma once
#include "pch.h"
namespace SDKTemplate
{
value struct Scenario;
partial ref class MainPage
{
internal:
static property Platform::String^ FEATURE_NAME
{
Platform::String^ get()
{
return "GeolocationCPP";
}
}
static property Platform::Array<Scenario>^ scenarios
{
Platform::Array<Scenario>^ get()
{
return scenariosInner;
}
}
private:
static Platform::Array<Scenario>^ scenariosInner;
};
public value struct Scenario
{
Platform::String^ Title;
Platform::String^ ClassName;
};
}

Просмотреть файл

@ -1,50 +0,0 @@
<!--
//*********************************************************
//
// 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.
//
//*********************************************************
-->
<Page x:Class="SDKTemplate.GeolocationCPP.Scenario1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:SDKTemplate.GeolocationCPP" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid x:Name="LayoutRoot" HorizontalAlignment="Left" VerticalAlignment="Top">
<StackPanel Orientation="Vertical">
<TextBlock x:Name="InputTextBlock" TextWrapping="Wrap" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Geolocation API allows application to continuously track the position of the device either distance-based or periodic-based." Margin="1,0,-1,10" />
<StackPanel Orientation="Horizontal" Margin="0,10,0,10">
<Button x:Name="StartTrackingButton" Content="Start Tracking" Margin="0,0,10,0" Click="StartTracking"/>
<Button x:Name="StopTrackingButton" Content="Stop Tracking" Margin="0,0,10,0" Click="StopTracking"/>
</StackPanel>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="0" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Status: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="1" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Latitude: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="2" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Longitude: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="3" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Accuracy: " />
<TextBlock x:Name="ScenarioOutput_Status" TextWrapping="Wrap" Grid.Row="0" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Unknown" />
<TextBlock x:Name="ScenarioOutput_Latitude" TextWrapping="Wrap" Grid.Row="1" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Longitude" TextWrapping="Wrap" Grid.Row="2" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Accuracy" TextWrapping="Wrap" Grid.Row="3" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
</Grid>
<TextBlock TextWrapping="Wrap" x:Name="LocationDisabledMessage" Margin="0,10,0,0" FontStyle="Italic" Visibility="Collapsed">
<Run Text="Application is not able to get location data. Go to " />
<Hyperlink NavigateUri="ms-settings:privacy-location">
<Run Text="Settings" />
</Hyperlink>
<Run Text=" to check the location permissions."/>
</TextBlock>
</StackPanel>
</Grid>
</Page>

Просмотреть файл

@ -1,205 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// Scenario1_TrackPosition.xaml.cpp
// Implementation of the Scenario1 class
//
#include "pch.h"
#include "Scenario1_TrackPosition.xaml.h"
using namespace SDKTemplate;
using namespace SDKTemplate::GeolocationCPP;
using namespace Concurrency;
using namespace Platform;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Foundation;
using namespace Windows::UI::Core;
Scenario1::Scenario1() : rootPage(MainPage::Current)
{
InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void Scenario1::OnNavigatedTo(NavigationEventArgs^ e)
{
StartTrackingButton->IsEnabled = true;
StopTrackingButton->IsEnabled = false;
}
/// <summary>
/// Invoked when this page is no longer displayed.
/// </summary>
/// <param name="e"></param>
void Scenario1::OnNavigatedFrom(NavigationEventArgs^ e)
{
// If the navigation is external to the app do not clean up.
// This can occur on Phone when suspending the app.
if (e->NavigationMode == NavigationMode::Forward && e->Uri == nullptr)
{
return;
}
if (StopTrackingButton->IsEnabled)
{
geolocator->PositionChanged::remove(positionToken);
geolocator->StatusChanged::remove(statusToken);
}
}
void Scenario1::StartTracking(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
task<GeolocationAccessStatus> geolocationAccessRequestTask(Windows::Devices::Geolocation::Geolocator::RequestAccessAsync());
geolocationAccessRequestTask.then([this](task<GeolocationAccessStatus> accessStatusTask)
{
// Get will throw an exception if the task was canceled or failed with an error
auto accessStatus = accessStatusTask.get();
switch (accessStatus)
{
case GeolocationAccessStatus::Allowed:
// You should set MovementThreshold for distance-based tracking
// or ReportInterval for periodic-based tracking before adding event
// handlers. If none is set, a ReportInterval of 1 second is used
// as a default and a position will be returned every 1 second.
//
// Value of 2000 milliseconds (2 seconds)
// isn't a requirement, it is just an example.
if (geolocator == nullptr)
{
geolocator = ref new Geolocator();
geolocator->ReportInterval = 2000;
}
// Subscribe to PositionChanged event to get updated tracking positions
positionToken = geolocator->PositionChanged::add(ref new TypedEventHandler<Geolocator^, PositionChangedEventArgs^>(this, &Scenario1::OnPositionChanged));
// Subscribe to StatusChanged event to get updates of location status change
statusToken = geolocator->StatusChanged::add(ref new TypedEventHandler<Geolocator^, StatusChangedEventArgs^>(this, &Scenario1::OnStatusChanged));
LocationDisabledMessage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
StartTrackingButton->IsEnabled = false;
StopTrackingButton->IsEnabled = true;
break;
case GeolocationAccessStatus::Denied:
rootPage->NotifyUser("Access to location is denied.", NotifyType::ErrorMessage);
LocationDisabledMessage->Visibility = Windows::UI::Xaml::Visibility::Visible;
break;
case GeolocationAccessStatus::Unspecified:
rootPage->NotifyUser("Unspecified error!", NotifyType::ErrorMessage);
}
});
}
void Scenario1::StopTracking(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
geolocator->PositionChanged::remove(positionToken);
geolocator->StatusChanged::remove(statusToken);
StartTrackingButton->IsEnabled = true;
StopTrackingButton->IsEnabled = false;
}
void Scenario1::OnPositionChanged(Geolocator^ sender, PositionChangedEventArgs^ e)
{
// We need to dispatch to the UI thread to display the output
Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new DispatchedHandler(
[this, e]()
{
rootPage->NotifyUser("Location updated", NotifyType::StatusMessage);
auto coordinate = e->Position->Coordinate;
ScenarioOutput_Latitude->Text = coordinate->Point->Position.Latitude.ToString();
ScenarioOutput_Longitude->Text = coordinate->Point->Position.Longitude.ToString();
ScenarioOutput_Accuracy->Text = coordinate->Accuracy.ToString();
},
CallbackContext::Any
)
);
}
void Scenario1::OnStatusChanged(Geolocator^ sender, StatusChangedEventArgs^ e)
{
// We need to dispatch to the UI thread to display the output
Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new DispatchedHandler(
[this, e]()
{
switch (e->Status)
{
case Windows::Devices::Geolocation::PositionStatus::Ready:
// Location platform is providing valid data.
ScenarioOutput_Status->Text = "Ready";
rootPage->NotifyUser("Location platform is ready.", NotifyType::StatusMessage);
break;
case Windows::Devices::Geolocation::PositionStatus::Initializing:
// Location platform is attempting to acquire a fix.
ScenarioOutput_Status->Text = "Initializing";
rootPage->NotifyUser("Location platform is attempting to obtain a position.", NotifyType::StatusMessage);
break;
case Windows::Devices::Geolocation::PositionStatus::NoData:
// Location platform could not obtain location data.
ScenarioOutput_Status->Text = "No data";
rootPage->NotifyUser("Not able to determine a location.", NotifyType::ErrorMessage);
break;
case Windows::Devices::Geolocation::PositionStatus::Disabled:
// The permission to access location data is denied by the user or other policies.
ScenarioOutput_Status->Text = "Disabled";
rootPage->NotifyUser("Access to location is denied.", NotifyType::ErrorMessage);
// Clear cached location data if any
ScenarioOutput_Latitude->Text = "No data";
ScenarioOutput_Longitude->Text = "No data";
ScenarioOutput_Accuracy->Text = "No data";
break;
case Windows::Devices::Geolocation::PositionStatus::NotInitialized:
// The location platform is not initialized. This indicates that the application
// has not made a request for location data.
ScenarioOutput_Status->Text = "Not initialized";
rootPage->NotifyUser("No request for location is made yet.", NotifyType::StatusMessage);
break;
case Windows::Devices::Geolocation::PositionStatus::NotAvailable:
// The location platform is not available on this version of the OS.
ScenarioOutput_Status->Text = "Not available";
rootPage->NotifyUser("Location is not available on this version of the OS.", NotifyType::ErrorMessage);
break;
default:
ScenarioOutput_Status->Text = "Unknown";
rootPage->NotifyUser("", NotifyType::StatusMessage);
break;
}
},
CallbackContext::Any
)
);
}

Просмотреть файл

@ -1,52 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// Scenario1_TrackPosition.xaml.h
// Declaration of the Scenario1 class
//
#pragma once
#include "pch.h"
#include "Scenario1_TrackPosition.g.h"
#include "MainPage.xaml.h"
namespace SDKTemplate
{
namespace GeolocationCPP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Scenario1 sealed
{
public:
Scenario1();
protected:
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
private:
MainPage^ rootPage;
Windows::Devices::Geolocation::Geolocator^ geolocator = nullptr;
Windows::Foundation::EventRegistrationToken positionToken;
Windows::Foundation::EventRegistrationToken statusToken;
void OnPositionChanged(Windows::Devices::Geolocation::Geolocator^ sender, Windows::Devices::Geolocation::PositionChangedEventArgs^ e);
void OnStatusChanged(Windows::Devices::Geolocation::Geolocator^ sender, Windows::Devices::Geolocation::StatusChangedEventArgs^ e);
void StartTracking(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void StopTracking(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
};
}
}

Просмотреть файл

@ -1,75 +0,0 @@
<!--
//*********************************************************
//
// 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.
//
//*********************************************************
-->
<Page x:Class="SDKTemplate.GeolocationCPP.Scenario2" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:SDKTemplate.GeolocationCPP" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid x:Name="LayoutRoot" HorizontalAlignment="Left" VerticalAlignment="Top">
<StackPanel Orientation="Vertical">
<TextBlock x:Name="InputTextBlock" TextWrapping="Wrap" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Geolocation API allows application to take a one-shot reading of the current position." />
<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,10,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="0" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" VerticalAlignment="Center" Text="DesiredAccuracy (meters): " />
<TextBox x:Name="DesiredAccuracyInMeters" Width="80" Margin="0,0,0,0" InputScope="Number" Grid.Row="0" Grid.Column="1" HorizontalAlignment="Left" TextChanged="DesiredAccuracyInMeters_TextChanged"/>
</Grid>
<StackPanel Orientation="Horizontal" Margin="0,10,0,10">
<Button x:Name="GetGeolocationButton" Content="Get Geolocation" Margin="0,0,10,0" Click="GetGeolocationButtonClicked"/>
<Button x:Name="CancelGetGeolocationButton" Content="Cancel" Margin="0,0,10,0" Click="CancelGetGeolocationButtonClicked"/>
</StackPanel>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="0" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Latitude: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="1" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Longitude: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="2" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Accuracy: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="3" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Source: " />
<TextBlock x:Name="Label_DilutionOfPrecision" Margin="0,0,10,0" Visibility="{Binding Visibility, ElementName=ScenarioOutput_PosPrecision}" TextWrapping="Wrap" Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="2" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Dilution Of Precision (DOP): " />
<TextBlock x:Name="Label_PosPrecision" Margin="20,0,10,0" Visibility="{Binding Visibility, ElementName=ScenarioOutput_PosPrecision}" TextWrapping="Wrap" Grid.Row="6" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Position DOP: " />
<TextBlock x:Name="Label_HorzPrecision" Margin="20,0,10,0" Visibility="{Binding Visibility, ElementName=ScenarioOutput_HorzPrecision}" TextWrapping="Wrap" Grid.Row="7" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Horizontal DOP: " />
<TextBlock x:Name="Label_VertPrecision" Margin="20,0,10,0" Visibility="{Binding Visibility, ElementName=ScenarioOutput_VertPrecision}" TextWrapping="Wrap" Grid.Row="8" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Vertical DOP: " />
<TextBlock x:Name="ScenarioOutput_Latitude" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="0" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Longitude" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="1" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Accuracy" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="2" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Source" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="3" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_PosPrecision" Margin="0,0,10,0" Visibility="Collapsed" TextWrapping="Wrap" Grid.Row="6" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_HorzPrecision" Margin="0,0,10,0" Visibility="Collapsed" TextWrapping="Wrap" Grid.Row="7" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_VertPrecision" Margin="0,0,10,0" Visibility="Collapsed" TextWrapping="Wrap" Grid.Row="8" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
</Grid>
<TextBlock TextWrapping="Wrap" x:Name="LocationDisabledMessage" Margin="0,10,0,0" FontStyle="Italic" Visibility="Collapsed">
<Run Text="Application is not able to get location data. Go to " />
<Hyperlink NavigateUri="ms-settings:privacy-location">
<Run Text="Settings" />
</Hyperlink>
<Run Text=" to check the location permissions."/>
</TextBlock>
</StackPanel>
</Grid>
</Page>

Просмотреть файл

@ -1,188 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// Scenario2_GetPosition.xaml.cpp
// Implementation of the Scenario2 class
//
#include "pch.h"
#include "Scenario2_GetPosition.xaml.h"
using namespace SDKTemplate;
using namespace SDKTemplate::GeolocationCPP;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Foundation;
using namespace Windows::UI::Core;
using namespace Platform;
using namespace concurrency;
Scenario2::Scenario2() : rootPage(MainPage::Current)
{
InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void Scenario2::OnNavigatedTo(NavigationEventArgs^ e)
{
GetGeolocationButton->IsEnabled = true;
CancelGetGeolocationButton->IsEnabled = false;
DesiredAccuracyInMeters->IsEnabled = true;
}
/// <summary>
/// Invoked when this page is no longer displayed.
/// </summary>
/// <param name="e"></param>
void Scenario2::OnNavigatedFrom(NavigationEventArgs^ e)
{
if (CancelGetGeolocationButton->IsEnabled)
{
geopositionTaskTokenSource.cancel();
}
}
void Scenario2::GetGeolocationButtonClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
GetGeolocationButton->IsEnabled = false;
CancelGetGeolocationButton->IsEnabled = true;
LocationDisabledMessage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
try
{
task<GeolocationAccessStatus> geolocationAccessRequestTask(Windows::Devices::Geolocation::Geolocator::RequestAccessAsync());
geolocationAccessRequestTask.then([this](task<GeolocationAccessStatus> accessStatusTask)
{
// Get will throw an exception if the task was canceled or failed with an error
auto accessStatus = accessStatusTask.get();
if (accessStatus == GeolocationAccessStatus::Allowed)
{
rootPage->NotifyUser("Waiting for update...", NotifyType::StatusMessage);
auto geolocator = ref new Windows::Devices::Geolocation::Geolocator();
geolocator->DesiredAccuracyInMeters = desiredAccuracyInMetersValue;
task<Geoposition^> geopositionTask(geolocator->GetGeopositionAsync(), geopositionTaskTokenSource.get_token());
geopositionTask.then([this](task<Geoposition^> getPosTask)
{
rootPage->NotifyUser("Location updated.", NotifyType::StatusMessage);
// Get will throw an exception if the task was canceled or failed with an error
UpdateLocationData(getPosTask.get());
GetGeolocationButton->IsEnabled = true;
CancelGetGeolocationButton->IsEnabled = false;
});
}
else if (accessStatus == GeolocationAccessStatus::Denied)
{
rootPage->NotifyUser("Access to location is denied.", NotifyType::ErrorMessage);
LocationDisabledMessage->Visibility = Windows::UI::Xaml::Visibility::Visible;
UpdateLocationData(nullptr);
}
else //GeolocationAccessStatus::Unspecified:
{
rootPage->NotifyUser("Unspecified error!", NotifyType::ErrorMessage);
UpdateLocationData(nullptr);
}
});
}
catch (task_canceled&)
{
rootPage->NotifyUser("Canceled", NotifyType::StatusMessage);
}
catch (Exception^ ex)
{
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
}
}
void Scenario2::CancelGetGeolocationButtonClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
geopositionTaskTokenSource.cancel();
GetGeolocationButton->IsEnabled = true;
CancelGetGeolocationButton->IsEnabled = false;
}
void Scenario2::DesiredAccuracyInMeters_TextChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
bool goodValue = true;
unsigned int value = FromStringTo<unsigned int>(DesiredAccuracyInMeters->Text);
if (0 == value)
{
// make sure string was '0'
if ("0" != DesiredAccuracyInMeters->Text)
{
rootPage->NotifyUser("Desired Accuracy must be a number", NotifyType::StatusMessage);
goodValue = false;
}
}
if (true == goodValue)
{
// clear out status message
rootPage->NotifyUser("", NotifyType::StatusMessage);
}
}
void Scenario2::UpdateLocationData(Windows::Devices::Geolocation::Geoposition^ position)
{
if (position == nullptr)
{
ScenarioOutput_Latitude->Text = "No data";
ScenarioOutput_Longitude->Text = "No data";
ScenarioOutput_Accuracy->Text = "No data";
}
else
{
ScenarioOutput_Latitude->Text = position->Coordinate->Point->Position.Latitude.ToString();
ScenarioOutput_Longitude->Text = position->Coordinate->Point->Position.Longitude.ToString();
ScenarioOutput_Accuracy->Text = position->Coordinate->Accuracy.ToString();
ScenarioOutput_Source->Text = position->Coordinate->PositionSource.ToString();
if (position->Coordinate->PositionSource == PositionSource::Satellite)
{
// show labels and satellite data
Label_PosPrecision->Opacity = 1;
ScenarioOutput_PosPrecision->Opacity = 1;
ScenarioOutput_PosPrecision->Text = position->Coordinate->SatelliteData->PositionDilutionOfPrecision->ToString();
Label_HorzPrecision->Opacity = 1;
ScenarioOutput_HorzPrecision->Opacity = 1;
ScenarioOutput_HorzPrecision->Text = position->Coordinate->SatelliteData->HorizontalDilutionOfPrecision->ToString();
Label_VertPrecision->Opacity = 1;
ScenarioOutput_VertPrecision->Opacity = 1;
ScenarioOutput_VertPrecision->Text = position->Coordinate->SatelliteData->VerticalDilutionOfPrecision->ToString();
}
else
{
// hide labels and satellite data
Label_PosPrecision->Opacity = 0;
ScenarioOutput_PosPrecision->Opacity = 0;
Label_HorzPrecision->Opacity = 0;
ScenarioOutput_HorzPrecision->Opacity = 0;
Label_VertPrecision->Opacity = 0;
ScenarioOutput_VertPrecision->Opacity = 0;
}
}
}

Просмотреть файл

@ -1,51 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// Scenario2_GetPosition.xaml.h
// Declaration of the Scenario2 class
//
#pragma once
#include "pch.h"
#include "Scenario2_GetPosition.g.h"
#include "MainPage.xaml.h"
namespace SDKTemplate
{
namespace GeolocationCPP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Scenario2 sealed
{
public:
Scenario2();
protected:
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
private:
MainPage^ rootPage;
unsigned int desiredAccuracyInMetersValue = 0;
concurrency::cancellation_token_source geopositionTaskTokenSource;
void GetGeolocationButtonClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void CancelGetGeolocationButtonClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void DesiredAccuracyInMeters_TextChanged(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void UpdateLocationData(Windows::Devices::Geolocation::Geoposition^ position);
};
}
}

Просмотреть файл

@ -1,40 +0,0 @@
<!--
//*********************************************************
//
// 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.
//
//*********************************************************
-->
<Page x:Class="SDKTemplate.GeolocationCPP.Scenario3" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:SDKTemplate.GeolocationCPP" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid x:Name="LayoutRoot" HorizontalAlignment="Left" VerticalAlignment="Top">
<StackPanel Orientation="Vertical">
<TextBlock x:Name="InputTextBlock" TextWrapping="Wrap" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Registers a background task to read geolocation on a periodic timer. Displayed position will be updated periodically when the background task runs (Set in the sample to every 15 minutes)." />
<StackPanel Orientation="Horizontal" Margin="0,10,0,10">
<Button x:Name="RegisterBackgroundTaskButton" Content="Register" Margin="0,0,10,0" Click="RegisterBackgroundTask"/>
<Button x:Name="UnregisterBackgroundTaskButton" Content="Unregister" Margin="0,0,10,0" Click="UnregisterBackgroundTask"/>
</StackPanel>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="0" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Latitude: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="1" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Longitude: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="2" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Accuracy: " />
<TextBlock x:Name="ScenarioOutput_Latitude" TextWrapping="Wrap" Grid.Row="0" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Longitude" TextWrapping="Wrap" Grid.Row="1" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Accuracy" TextWrapping="Wrap" Grid.Row="2" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
</Grid>
</StackPanel>
</Grid>
</Page>

Просмотреть файл

@ -1,275 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// Scenario3_BackgroundTask.xaml.cpp
// Implementation of the Scenario3 class
//
#include "pch.h"
#include "Scenario3_BackgroundTask.xaml.h"
using namespace SDKTemplate;
using namespace SDKTemplate::GeolocationCPP;
using namespace concurrency;
using namespace Platform;
using namespace Windows::ApplicationModel::Background;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Foundation;
using namespace Windows::Storage;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
Scenario3::Scenario3() : rootPage(MainPage::Current), sampleBackgroundTaskName("SampleLocationBackgroundTask"), sampleBackgroundTaskEntryPoint("BackgroundTask.LocationBackgroundTask")
{
InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void Scenario3::OnNavigatedTo(NavigationEventArgs^ e)
{
// Look for an already registered background task
geolocTask = nullptr;
auto iter = BackgroundTaskRegistration::AllTasks->First();
while (iter->HasCurrent)
{
auto task = iter->Current;
if (task->Value->Name == sampleBackgroundTaskName)
{
geolocTask = safe_cast<BackgroundTaskRegistration^>(task->Value);
break;
}
iter->MoveNext();
}
if (geolocTask != nullptr)
{
// Register for background task completion notifications
taskCompletedToken = geolocTask->Completed::add(ref new BackgroundTaskCompletedEventHandler(this, &Scenario3::OnCompleted));
try
{
// Check the background access status of the application and display the appropriate status message
switch (BackgroundExecutionManager::GetAccessStatus())
{
case BackgroundAccessStatus::AlwaysAllowed:
case BackgroundAccessStatus::AllowedSubjectToSystemPolicy:
rootPage->NotifyUser("Background task is already registered. Waiting for next update...", NotifyType::StatusMessage);
break;
default:
rootPage->NotifyUser("Background tasks may be disabled for this app", NotifyType::ErrorMessage);
break;
}
}
catch (Exception^ ex)
{
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
}
UpdateButtonStates(/*registered:*/ true);
}
else
{
UpdateButtonStates(/*registered:*/ false);
}
}
/// <summary>
/// Invoked when this page is no longer displayed.
/// </summary>
/// <param name="e"></param>
void Scenario3::OnNavigatedFrom(NavigationEventArgs^ e)
{
if (geolocTask != nullptr)
{
// remove the event handler
geolocTask->Completed::remove(taskCompletedToken);
}
}
void Scenario3::RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
try
{
// Get permission for a background task from the user. If the user has already answered once,
// this does nothing and the user must manually update their preference via PC Settings.
task<BackgroundAccessStatus> requestAccessTask(BackgroundExecutionManager::RequestAccessAsync());
requestAccessTask.then([this](BackgroundAccessStatus backgroundAccessStatus)
{
// Create a new background task builder
BackgroundTaskBuilder^ geolocTaskBuilder = ref new BackgroundTaskBuilder();
geolocTaskBuilder->Name = sampleBackgroundTaskName;
geolocTaskBuilder->TaskEntryPoint = sampleBackgroundTaskEntryPoint;
// Create a new timer triggering at a 15 minute interval
auto trigger = ref new TimeTrigger(15, false);
// Associate the timer trigger with the background task builder
geolocTaskBuilder->SetTrigger(trigger);
// Register the background task
geolocTask = geolocTaskBuilder->Register();
// Register for background task completion notifications
taskCompletedToken = geolocTask->Completed::add(ref new BackgroundTaskCompletedEventHandler(this, &Scenario3::OnCompleted));
UpdateButtonStates(/*registered:*/ true);
// Check the background access status of the application and display the appropriate status message
switch (backgroundAccessStatus)
{
case BackgroundAccessStatus::AlwaysAllowed:
case BackgroundAccessStatus::AllowedSubjectToSystemPolicy:
rootPage->NotifyUser("Background task registered.", NotifyType::StatusMessage);
// Need to request access to location
// This must be done with background task registration
// because the background task cannot display UI
RequestLocationAccess();
break;
default:
rootPage->NotifyUser("Background tasks may be disabled for this app", NotifyType::ErrorMessage);
break;
}
});
}
catch (Exception^ ex)
{
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
UpdateButtonStates(/*registered:*/ false);
}
}
void Scenario3::UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
// Unregister the background task
if (geolocTask != nullptr)
{
geolocTask->Unregister(true);
geolocTask = nullptr;
}
ScenarioOutput_Latitude->Text = "No data";
ScenarioOutput_Longitude->Text = "No data";
ScenarioOutput_Accuracy->Text = "No data";
UpdateButtonStates(/*registered:*/ false);
rootPage->NotifyUser("Background task unregistered.", NotifyType::StatusMessage);
}
void Scenario3::OnCompleted(BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ args)
{
// Update the UI with progress reported by the background task
// We need to dispatch to the UI thread to display the output
Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new DispatchedHandler(
[this, args]()
{
try
{
// Throw an exception if the background task had an unrecoverable error
args->CheckResult();
// Update the UI with the completion status of the background task
auto settings = ApplicationData::Current->LocalSettings->Values;
if (settings->HasKey("Status"))
{
rootPage->NotifyUser(safe_cast<String^>(settings->Lookup("Status")), NotifyType::StatusMessage);
}
// Extract and display Latitude
if (settings->HasKey("Latitude"))
{
ScenarioOutput_Latitude->Text = safe_cast<String^>(settings->Lookup("Latitude"));
}
else
{
ScenarioOutput_Latitude->Text = "No data";
}
// Extract and display Longitude
if (settings->HasKey("Longitude"))
{
ScenarioOutput_Longitude->Text = safe_cast<String^>(settings->Lookup("Longitude"));
}
else
{
ScenarioOutput_Longitude->Text = "No data";
}
// Extract and display Accuracy
if (settings->HasKey("Accuracy"))
{
ScenarioOutput_Accuracy->Text = safe_cast<String^>(settings->Lookup("Accuracy"));
}
else
{
ScenarioOutput_Accuracy->Text = "No data";
}
}
catch (Exception^ ex)
{
// The background task had an error
rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
}
},
CallbackContext::Any
)
);
}
/// <summary>
/// Update the enable state of the register/unregister buttons.
/// </summary>
void Scenario3::UpdateButtonStates(bool registered)
{
auto uiDelegate = [this, registered]()
{
RegisterBackgroundTaskButton->IsEnabled = !registered;
UnregisterBackgroundTaskButton->IsEnabled = registered;
};
auto handler = ref new Windows::UI::Core::DispatchedHandler(uiDelegate, Platform::CallbackContext::Any);
Dispatcher->RunAsync(CoreDispatcherPriority::Normal, handler);
}
void Scenario3::RequestLocationAccess()
{
task<GeolocationAccessStatus> geolocationAccessRequestTask(Windows::Devices::Geolocation::Geolocator::RequestAccessAsync());
geolocationAccessRequestTask.then([this](task<GeolocationAccessStatus> accessStatusTask)
{
auto accessStatus = accessStatusTask.get();
switch (accessStatus)
{
case GeolocationAccessStatus::Allowed:
break;
case GeolocationAccessStatus::Denied:
rootPage->NotifyUser("Access to location is denied.", NotifyType::ErrorMessage);
break;
case GeolocationAccessStatus::Unspecified:
rootPage->NotifyUser("Unspecified error!", NotifyType::ErrorMessage);
break;
}
});
}

Просмотреть файл

@ -1,54 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// Scenario3_BackgroundTask.xaml.h
// Declaration of the Scenario3 class
//
#pragma once
#include "pch.h"
#include "Scenario3_BackgroundTask.g.h"
#include "MainPage.xaml.h"
namespace SDKTemplate
{
namespace GeolocationCPP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Scenario3 sealed
{
public:
Scenario3();
protected:
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
private:
MainPage^ rootPage;
Platform::String^ sampleBackgroundTaskName;
Platform::String^ sampleBackgroundTaskEntryPoint;
Windows::ApplicationModel::Background::BackgroundTaskRegistration^ geolocTask;
Windows::Foundation::EventRegistrationToken taskCompletedToken;
void RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void RequestLocationAccess();
void OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ sender, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ e);
void UpdateButtonStates(bool registered);
};
}
}

Просмотреть файл

@ -1,204 +0,0 @@
<!--
//*********************************************************
//
// 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.
//
//*********************************************************
-->
<Page x:Class="SDKTemplate.GeolocationCPP.Scenario4" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:SDKTemplate.GeolocationCPP" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Page.Resources>
<SolidColorBrush x:Key="RequiredFieldBrush" Color="Red" />
<Style x:Key="AsteriskTextStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource RequiredFieldBrush}"/>
<Setter Property="FontSize" Value="{StaticResource ControlContentThemeFontSize}"/>
<Setter Property="FontFamily" Value="{StaticResource ContentControlThemeFontFamily}"/>
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="IsColorFontEnabled" Value="True"/>
<Setter Property="TextTrimming" Value="WordEllipsis"/>
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="Typography.StylisticSet20" Value="True"/>
<Setter Property="Typography.DiscretionaryLigatures" Value="True"/>
</Style>
</Page.Resources>
<ScrollViewer VerticalScrollMode="Enabled">
<Grid x:Name="LayoutRoot" HorizontalAlignment="Left" VerticalAlignment="Top">
<StackPanel Orientation="Vertical">
<StackPanel Margin="0,0,0,0" Orientation="Vertical">
<TextBlock x:Name="InputTextBlock" TextWrapping="Wrap" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Geofence API allows applications to add, list and remove geofences that will be monitored by the system." />
<StackPanel Orientation="Horizontal" Margin="5,10,0,0">
<TextBlock Style="{StaticResource AsteriskTextStyle}" VerticalAlignment="Center" Text="*" />
<TextBlock Style="{StaticResource BasicTextStyle}" VerticalAlignment="Center" Text="Indicates Required Fields" />
</StackPanel>
</StackPanel>
<StackPanel Name="StackPanel_Main" Orientation="Vertical" >
<StackPanel Name="StackPanel_InputControls" Orientation="Vertical">
<Grid HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid Name="Grid_InputControls" Grid.Row="0" Grid.Column="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Name="StackPanel_NameLabel" Orientation="Horizontal" Grid.Row="0" Grid.Column="0" Margin="5,0,0,0">
<TextBlock Name="TextBlock_Name" Style="{StaticResource BasicTextStyle}" VerticalAlignment="Center" Text="Name" />
<TextBlock Name="TextBlock_NameAsterisk" Style="{StaticResource AsteriskTextStyle}" VerticalAlignment="Center" Text="*" />
</StackPanel>
<StackPanel Name="StackPanel_Id" Orientation="Horizontal" Margin="0,5,0,0" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2">
<TextBox Width="150" Name="Id" HorizontalAlignment="Left" Text="" TextChanged="OnIdTextChanged"/>
<TextBlock Style="{StaticResource BasicTextStyle}" Name="CharCount" HorizontalAlignment="Left" Margin="10,0,0,0" Text="0 characters" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Orientation="Vertical" Margin="0,5,0,0" Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2">
<Button x:Name="SetPositionToHereButton" Width="160" HorizontalAlignment="Left" VerticalAlignment="Top" Content="Set to Here" Click="OnSetPositionToHere"/>
<ProgressBar x:Name="SetPositionProgressBar" Visibility="Collapsed" Height="10" IsEnabled="True" IsIndeterminate="True"/>
</StackPanel>
<StackPanel Name="StackPanel_LatitudeLabel" Orientation="Horizontal" Grid.Row="2" Grid.Column="0" Margin="5,5">
<TextBlock Name="TextBlock_Latitude" Style="{StaticResource BasicTextStyle}" VerticalAlignment="Center" Text="Latitude" />
<TextBlock Name="TextBlock_LatitudeAsterisk" Style="{StaticResource AsteriskTextStyle}" VerticalAlignment="Center" Text="*" />
</StackPanel>
<StackPanel Name="StackPanel_Latitude" Orientation="Horizontal" Margin="0,5,0,0" Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2">
<TextBox Width="150" Name="Latitude" InputScope="Number" HorizontalAlignment="Left" MaxLength="11" TextChanged="OnLatitudeTextChanged"/>
<TextBlock Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Margin="10,0,0,0" Text="-90 to 90 degrees" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Name="StackPanel_LongitudeLabel" Orientation="Horizontal" Grid.Row="3" Grid.Column="0" Margin="5,5">
<TextBlock Name="TextBlock_Longitude" Style="{StaticResource BasicTextStyle}" VerticalAlignment="Center" Text="Longitude" />
<TextBlock Name="TextBlock_LongitudeAsterisk" Style="{StaticResource AsteriskTextStyle}" VerticalAlignment="Center" Text="*" />
</StackPanel>
<StackPanel Name="StackPanel_Longitude" Orientation="Horizontal" Margin="0,5,0,0" Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="2">
<TextBox Width="150" Name="Longitude" InputScope="Number" HorizontalAlignment="Left" MaxLength="12" TextChanged="OnLongitudeTextChanged"/>
<TextBlock Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Margin="10,0,0,0" Text="-180 to 180 degrees" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Name="StackPanel_RadiusLabel" Orientation="Horizontal" Grid.Row="4" Grid.Column="0" Margin="5,5">
<TextBlock Name="TextBlock_Radius" Style="{StaticResource BasicTextStyle}" VerticalAlignment="Center" Text="Radius" />
<TextBlock Name="TextBlock_RadiusAsterisk" Style="{StaticResource AsteriskTextStyle}" VerticalAlignment="Center" Text="*" />
</StackPanel>
<StackPanel Name="StackPanel_Radius" Orientation="Horizontal" Margin="0,5" Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2">
<TextBox Width="150" Name="Radius" InputScope="Number" HorizontalAlignment="Left" MaxLength="12" TextChanged="OnRadiusTextChanged"/>
<TextBlock Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Margin="10,6,0,6" Text=".1 to 10018754.3 m" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Name="StackPanel_DwellTimeLabel" Grid.Row="5" Grid.Column="0" Margin="5,5">
<TextBlock Name="TextBlock_DwellTime" Style="{StaticResource BasicTextStyle}" VerticalAlignment="Center" Text="Dwell Time"/>
</StackPanel>
<StackPanel Orientation="Vertical" Margin="0,5" Grid.Row="5" Grid.Column="1" Grid.ColumnSpan="2">
<TextBox Width="200" Name="DwellTime" InputScope="Number" HorizontalAlignment="Left"/>
<TextBlock Width="150" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Margin="10,0,0,0" Text="Format: d:hh:mm:ss" VerticalAlignment="Center"/>
<TextBlock Width="200" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Margin="10,0,0,0" Text="Examples:" VerticalAlignment="Center"/>
<TextBlock Width="250" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Margin="10,0,0,0" Text="7:22:45:55 for 7 days, 22 hours, 45 minutes, 55 seconds" VerticalAlignment="Center"/>
<TextBlock Width="250" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Margin="10,0,0,0" Text="1:35 for 1 minute, 35 seconds" VerticalAlignment="Center"/>
<TextBlock Width="250" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Margin="10,0,0,0" Text="30 for 30 seconds" VerticalAlignment="Center"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,5" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="2">
<Button x:Name="SetStartTimeToNowButton" HorizontalAlignment="Left" VerticalAlignment="Top" Content="Set to Now" Click="OnSetStartTimeToNow"/>
</StackPanel>
<StackPanel Name="StackPanel_StartTimeLabel" Grid.Row="7" Grid.Column="0" Margin="5,5">
<TextBlock Name="TextBlock_StartTime" Style="{StaticResource BasicTextStyle}" VerticalAlignment="Center" Text="Start Time" />
</StackPanel>
<StackPanel Orientation="Vertical" Margin="0,5" Grid.Row="7" Grid.Column="1" Grid.ColumnSpan="2">
<TextBox Width="200" Name="StartTime" InputScope="Number" HorizontalAlignment="Left"/>
<TextBlock Width="250" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Margin="10,0,0,0" Text="Format: mm/dd/yyyy hh:mm:ss" VerticalAlignment="Center" />
<TextBlock Width="250" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Margin="10,0,0,0" Text="Example: 2/10/2014 22:45:07" VerticalAlignment="Center" />
<TextBlock Width="250" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Margin="10,0,0,0" Text=" for Feb 10, 2014 at 10:45:07 PM" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Name="StackPanel_DurationLabel" Grid.Row="8" Grid.Column="0" Margin="5,5">
<TextBlock Name="TextBlock_Duration" Style="{StaticResource BasicTextStyle}" VerticalAlignment="Center" Text="Duration" />
</StackPanel>
<StackPanel Orientation="Vertical" Margin="0,5,0,0" Grid.Row="8" Grid.Column="1" Grid.ColumnSpan="2">
<TextBox Width="200" Name="Duration" InputScope="Number" HorizontalAlignment="Left"/>
<TextBlock Width="250" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Margin="10,0,0,0" Text="See Dwell Time for format information" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="5" Grid.Row="9" Grid.Column="1" Grid.ColumnSpan="2">
<CheckBox Name="SingleUse" Content="Single Use"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0,10,0,10" Grid.Row="10" Grid.Column="0" Grid.ColumnSpan="2">
<Button x:Name="CreateGeofenceButton" HorizontalAlignment="Left" VerticalAlignment="Top" Content="Create Geofence" Margin="10,0,10,0" Click="OnCreateGeofence" IsEnabled="False"/>
</StackPanel>
</Grid>
</Grid>
</StackPanel>
<StackPanel Name="StackPanel_ListBoxes" Orientation="Vertical">
<Grid Name="Grid_ListBox">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Grid.Column="0" Margin="5,5">
<StackPanel Orientation="Vertical">
<TextBlock Style="{StaticResource BasicTextStyle}" Text="Registered" />
<TextBlock Style="{StaticResource BasicTextStyle}" Text="Geofences" />
</StackPanel>
</StackPanel>
<StackPanel Orientation="Vertical" Margin="5,5,0,0" Grid.Row="0" Grid.Column="1">
<ListBox Name="RegisteredGeofenceListBox" Width="250" Height="120"
ItemsSource="{Binding}"
SelectionChanged="OnRegisteredGeofenceListBoxSelectionChanged"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollMode="Enabled">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Left">
<StackPanel Orientation="Horizontal" Margin="5,0,0,0">
<TextBlock Text="{Binding Id}"/>
<TextBlock Text=" ("/>
<TextBlock Text="{Binding Latitude}"/>
<TextBlock Text=", "/>
<TextBlock Text="{Binding Longitude}"/>
<TextBlock Text=", "/>
<TextBlock Text="{Binding Radius}"/>
<TextBlock Text=")"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button x:Name="RemoveGeofenceItem" HorizontalAlignment="Left" VerticalAlignment="Top" Content="Remove Geofence" Margin="10,5,10,5" Click="OnRemoveGeofenceItem" IsEnabled="False"/>
</StackPanel>
<StackPanel Grid.Row="1" Grid.Column="0" Margin="10">
<TextBlock Style="{StaticResource BasicTextStyle}" Text="Events" />
</StackPanel>
<StackPanel Orientation="Vertical" Margin="10" Grid.Row="1" Grid.Column="1">
<ListBox Name="GeofenceEventsListBox" Width="250" Height="120"
ItemsSource="{Binding}"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollMode="Enabled"/>
</StackPanel>
</Grid>
</StackPanel>
</StackPanel>
</StackPanel>
</Grid>
</ScrollViewer>
</Page>

Просмотреть файл

@ -1,442 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// Scenario4_ForegroundGeofence.xaml.cpp
// Implementation of the Scenario4 class
//
#include "pch.h"
#include "Scenario4_ForegroundGeofence.xaml.h"
using namespace SDKTemplate;
using namespace SDKTemplate::GeolocationCPP;
using namespace Platform;
using namespace Windows::Devices::Enumeration;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Devices::Geolocation::Geofencing;
using namespace Windows::Foundation;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml::Navigation;
const unsigned int oneHundredNanosecondsPerSecond = 10000000;
const unsigned int defaultDwellTimeSeconds = 10;
Scenario4::Scenario4()
: rootPage(MainPage::Current),
nameSet(false),
latitudeSet(false),
longitudeSet(false),
radiusSet(false),
permissionsChecked(false),
inGetPositionAsync(false)
{
InitializeComponent();
try
{
auto us = ref new Platform::Collections::Vector<String^>();
us->Append("en-US");
formatterShortDateLongTime = ref new Windows::Globalization::DateTimeFormatting::DateTimeFormatter("{month.integer}/{day.integer}/{year.full} {hour.integer}:{minute.integer(2)}:{second.integer(2)}", us, "US", Windows::Globalization::CalendarIdentifiers::Gregorian, Windows::Globalization::ClockIdentifiers::TwentyFourHour);
formatterLongTime = ref new Windows::Globalization::DateTimeFormatting::DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", us, "US", Windows::Globalization::CalendarIdentifiers::Gregorian, Windows::Globalization::ClockIdentifiers::TwentyFourHour);
calendar = ref new Windows::Globalization::Calendar();
geofenceCollection = ref new Platform::Collections::Vector<GeofenceItem^>();
eventCollection = ref new Platform::Collections::Vector<Platform::String^>();
geolocator = ref new Geolocator();
geofences = GeofenceMonitor::Current->Geofences;
// using data binding to the root page collection of GeofenceItems
RegisteredGeofenceListBox->DataContext = geofenceCollection;
// using data binding to the root page collection of GeofenceItems associated with events
GeofenceEventsListBox->DataContext = eventCollection;
FillRegisteredGeofenceListBoxWithExistingGeofences();
FillEventListBoxWithExistingEvents();
coreWindow = CoreWindow::GetForCurrentThread(); // this needs to be set before InitializeComponent sets up event registration for app visibility
coreWindow->VisibilityChanged += ref new TypedEventHandler<CoreWindow ^, VisibilityChangedEventArgs ^>(this, &Scenario4::OnVisibilityChanged);
// register for state change events
geofenceStateChangeToken = GeofenceMonitor::Current->GeofenceStateChanged += ref new TypedEventHandler<GeofenceMonitor^, Platform::Object^>(this, &Scenario4::OnGeofenceStateChanged);
geofenceStatusChangeToken = GeofenceMonitor::Current->StatusChanged += ref new TypedEventHandler<GeofenceMonitor^, Platform::Object^>(this, &Scenario4::OnGeofenceStatusChanged);
}
catch (Platform::Exception^ ex)
{
// GeofenceMonitor failed in adding a geofence
// exceptions could be from out of memory, lat/long out of range,
// too long a name, not a unique name, specifying a start
// time + duration that is still in the past
// If ex->HResult is RPC_E_DISCONNECTED (0x80010108):
// The Location Framework service event state is out of synchronization
// with the Windows::Devices::Geolocation::Geofencing::GeofenceMonitor.
// To recover remove all event handlers on the GeofenceMonitor or restart the application.
// Once all event handlers are removed you may add back any event handlers and retry the operation.
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
}
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void Scenario4::OnNavigatedTo(NavigationEventArgs^ e)
{
}
/// <summary>
/// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
/// </summary>
/// <param name="e">
/// 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 e.Cancel to true.
/// </param>
void Scenario4::OnNavigatedFrom(NavigationEventArgs^ e)
{
// If the navigation is external to the app do not clean up.
// This can occur on Phone when suspending the app.
if (e->NavigationMode == NavigationMode::Forward && e->Uri == nullptr)
{
return;
}
if (true == inGetPositionAsync)
{
geopositionTaskTokenSource.cancel();
}
GeofenceMonitor::Current->GeofenceStateChanged::remove(geofenceStateChangeToken);
GeofenceMonitor::Current->StatusChanged::remove(geofenceStatusChangeToken);
// save off the contents of the event collection
SaveExistingEvents();
}
void Scenario4::OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args)
{
// NOTE: After the app is no longer visible on the screen and before the app is suspended
// you might want your app to use toast notification for any geofence activity.
// By registering for VisibiltyChanged the app is notified when the app is no longer visible on the foreground.
if (args->Visible)
{
// register for foreground events
geofenceStateChangeToken = GeofenceMonitor::Current->GeofenceStateChanged += ref new TypedEventHandler<GeofenceMonitor^, Platform::Object^>(this, &Scenario4::OnGeofenceStateChanged);
geofenceStatusChangeToken = GeofenceMonitor::Current->StatusChanged += ref new TypedEventHandler<GeofenceMonitor^, Platform::Object^>(this, &Scenario4::OnGeofenceStatusChanged);
}
else
{
// unregister foreground events (let background capture events)
GeofenceMonitor::Current->GeofenceStateChanged::remove(geofenceStateChangeToken);
GeofenceMonitor::Current->StatusChanged::remove(geofenceStatusChangeToken);
}
}
void Scenario4::OnGeofenceStatusChanged(GeofenceMonitor^ sender, Platform::Object^ args)
{
auto status = sender->Status;
// We need to dispatch to the UI thread to display the output
Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new DispatchedHandler(
[this, status]()
{
Platform::String^ eventDescription = GetTimeStampedMessage("Geofence Status");
if (GeofenceMonitorStatus::Ready == status)
{
eventDescription += " (Ready)";
}
else if (GeofenceMonitorStatus::Initializing == status)
{
eventDescription += " (Initializing)";
}
else if (GeofenceMonitorStatus::NoData == status)
{
eventDescription += " (NoData)";
}
else if (GeofenceMonitorStatus::Disabled == status)
{
eventDescription += " (Disabled)";
}
else if (GeofenceMonitorStatus::NotInitialized == status)
{
eventDescription += " (NotInitialized)";
}
else if (GeofenceMonitorStatus::NotAvailable == status)
{
eventDescription += " (NotAvailable)";
}
else
{
eventDescription += " (Unknown)";
}
AddEventDescription(eventDescription);
},
CallbackContext::Any
)
);
}
void Scenario4::OnGeofenceStateChanged(GeofenceMonitor^ sender, Platform::Object^ args)
{
auto reports = sender->ReadReports();
// We need to dispatch to the UI thread to display the output
Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new DispatchedHandler(
[this, reports]()
{
for (auto report : reports)
{
GeofenceState state = report->NewState;
auto geofence = report->Geofence;
Platform::String^ eventDescription = GetTimeStampedMessage(geofence->Id);
if (state == GeofenceState::Removed)
{
GeofenceRemovalReason reason = report->RemovalReason;
if (reason == GeofenceRemovalReason::Expired)
{
eventDescription += " (Removed/Expired)";
}
else if (reason == GeofenceRemovalReason::Used)
{
eventDescription += " (Removed/Used)";
}
else
{
eventDescription += " (Removed/Unknown)";
}
AddEventDescription(eventDescription);
// remove the geofence from the client side geofences collection
Remove(geofence);
// empty the registered geofence listbox and repopulate
geofenceCollection->Clear();
FillRegisteredGeofenceListBoxWithExistingGeofences();
}
else if (state == GeofenceState::Entered || state == GeofenceState::Exited)
{
// NOTE: You might want to write your app to take particular
// action based on whether the app has internet connectivity.
if (state == GeofenceState::Entered)
{
eventDescription += " (Entered)";
}
else if (state == GeofenceState::Exited)
{
eventDescription += " (Exited)";
}
AddEventDescription(eventDescription);
}
}
},
CallbackContext::Any
)
);
}
/// <summary>
/// This method removes the geofence from the client side geofences collection
/// </summary>
/// <param name="geofence"></param>
void Scenario4::Remove(Windows::Devices::Geolocation::Geofencing::Geofence^ geofence)
{
try
{
unsigned int index = 0;
if (geofences->IndexOf(geofence, &index))
{
geofences->RemoveAt(index);
}
else
{
auto strMsg = "Could not find Geofence " + geofence->Id + " in the geofences collection";
rootPage->NotifyUser(strMsg, NotifyType::StatusMessage);
}
}
catch (Platform::Exception^ ex)
{
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
}
}
/// <summary>
/// This is the click handler for the 'Remove Geofence Item' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Scenario4::OnRemoveGeofenceItem(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
if (nullptr != RegisteredGeofenceListBox->SelectedItem)
{
// get selected item
GeofenceItem^ itemToRemove = safe_cast<GeofenceItem^>(RegisteredGeofenceListBox->SelectedItem);
auto geofence = itemToRemove->Geofence;
// remove the geofence from the client side geofences collection
Remove(geofence);
// empty the registered geofence listbox and repopulate
geofenceCollection->Clear();
FillRegisteredGeofenceListBoxWithExistingGeofences();
}
}
Windows::Devices::Geolocation::Geofencing::Geofence^ Scenario4::GenerateGeofence()
{
Geofence^ geofence = nullptr;
try
{
String^ fenceKey = Id->Text;
BasicGeoposition position;
position.Latitude = FromStringTo<double>(Latitude->Text);
position.Longitude = FromStringTo<double>(Longitude->Text);
position.Altitude = 0.0;
double radius = FromStringTo<double>(Radius->Text);
// the geofence is a circular region
Geocircle^ geocircle = ref new Geocircle(position, radius);
bool singleUse = false;
if (true == SingleUse->IsChecked->Value)
{
singleUse = true;
}
// want to listen for enter geofence, exit geofence and remove geofence events
// you can select a subset of these event states
MonitoredGeofenceStates mask = static_cast<MonitoredGeofenceStates>(0);
mask = mask | MonitoredGeofenceStates::Entered;
mask = mask | MonitoredGeofenceStates::Exited;
mask = mask | MonitoredGeofenceStates::Removed;
// setting up how long you need to be in geofence for enter event to fire
TimeSpan dwellTime;
bool useDwellTime = false;
// use dwell if the textbox has text
if (nullptr != DwellTime->Text)
{
dwellTime.Duration = GetDurationFromString(DwellTime->Text);
if (0 != dwellTime.Duration)
{
useDwellTime = true;
}
}
if (!useDwellTime)
{
dwellTime.Duration = defaultDwellTimeSeconds * oneHundredNanosecondsPerSecond;
useDwellTime = true;
}
// setting up how long the geofence should be active
TimeSpan duration;
bool useDuration = false;
// use duration if the textbox has text
if (nullptr != Duration->Text)
{
duration.Duration = GetDurationFromString(Duration->Text);
if (0 != duration.Duration)
{
useDuration = true;
}
}
// setting up the start time of the geofence
DateTime startTime;
bool useStartTime = false;
if (nullptr != StartTime->Text)
{
startTime.UniversalTime = GetUniversalTimeFromString(StartTime->Text);
if (0 != startTime.UniversalTime)
{
useStartTime = true;
}
if (!useStartTime)
{
rootPage->NotifyUser("Could not determine Start Time", NotifyType::ErrorMessage);
}
}
if (false == useStartTime && false == useDuration)
{
if (true == useDwellTime)
{
geofence = ref new Geofence(fenceKey, geocircle, mask, singleUse, dwellTime);
}
}
else
{
if (!useStartTime)
{
calendar->SetToNow();
startTime = calendar->GetDateTime();
}
if (!useDuration)
{
duration.Duration = 0;
}
geofence = ref new Geofence(fenceKey, geocircle, mask, singleUse, dwellTime, startTime, duration);
}
}
catch (Platform::Exception^ ex)
{
// GeofenceMonitor failed in adding a geofence
// exceptions could be from out of memory, lat/long out of range,
// too long a name, not a unique name, specifying an activation
// time + duration that is still in the past
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
}
return geofence;
}

Просмотреть файл

@ -1,100 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// Scenario4_ForegroundGeofence.xaml.h
// Declaration of the Scenario4 class
//
#pragma once
#include "pch.h"
#include "geofenceitem.h"
#include "Scenario4_ForegroundGeofence.g.h"
#include "MainPage.xaml.h"
namespace SDKTemplate
{
namespace GeolocationCPP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Scenario4 sealed
{
public:
Scenario4();
protected:
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
private:
void RefreshControlsFromGeofenceItem(GeofenceItem^ item);
bool TextChangedHandlerDouble(bool nullAllowed, Platform::String^ name, Windows::UI::Xaml::Controls::TextBox^ e);
bool TextChangedHandlerInt(bool nullAllowed, Platform::String^ name, Windows::UI::Xaml::Controls::TextBox^ e);
bool SettingsAvailable();
void AddGeofenceToRegisteredGeofenceListBox(Windows::Devices::Geolocation::Geofencing::Geofence^ geoFence);
void GetGeopositionAsync();
Windows::Devices::Geolocation::Geofencing::Geofence^ GenerateGeofence();
void FillRegisteredGeofenceListBoxWithExistingGeofences();
void FillEventListBoxWithExistingEvents();
void SaveExistingEvents();
void AddEventDescription(Platform::String^ eventDescription);
Platform::String^ GetTimeStampedMessage(Platform::String^ EventCalled);
void SetStartTimeToNowFunction();
long long GetDurationFromString(Platform::String^ str);
long long GetUniversalTimeFromString(Platform::String^ str);
void GetTimeComponentAsString(Platform::String^& str, int timecomponent, bool appenddelimiter);
Platform::String^ GetDurationString(long long duration);
void Remove(Windows::Devices::Geolocation::Geofencing::Geofence^ geofence);
void OnGeofenceStateChanged(Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ sender, Platform::Object^ args);
void OnGeofenceStatusChanged(Windows::Devices::Geolocation::Geofencing::GeofenceMonitor^ sender, Platform::Object^ args);
void OnVisibilityChanged(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::VisibilityChangedEventArgs^ args);
#if (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP)
void OnAccessChanged(Windows::Devices::Enumeration::DeviceAccessInformation^ sender, Windows::Devices::Enumeration::DeviceAccessChangedEventArgs^ args);
#endif
void OnIdTextChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::TextChangedEventArgs^ e);
void OnLatitudeTextChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::TextChangedEventArgs^ e);
void OnLongitudeTextChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::TextChangedEventArgs^ e);
void OnRadiusTextChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::TextChangedEventArgs^ e);
void OnRegisteredGeofenceListBoxSelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e);
void OnRemoveGeofenceItem(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void OnSetStartTimeToNow(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void OnSetPositionToHere(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void OnCreateGeofence(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
MainPage^ rootPage;
bool nameSet;
bool latitudeSet;
bool longitudeSet;
bool radiusSet;
bool permissionsChecked;
bool inGetPositionAsync;
Windows::Devices::Geolocation::Geolocator^ geolocator;
Windows::Foundation::Collections::IVector<Windows::Devices::Geolocation::Geofencing::Geofence^>^ geofences;
#if (WINAPI_FAMILY == WINAPI_FAMILY_PC_APP)
Windows::Devices::Enumeration::DeviceAccessInformation^ accessInfo;
#endif
Windows::Foundation::EventRegistrationToken geofenceStateChangeToken;
Windows::Foundation::EventRegistrationToken geofenceStatusChangeToken;
concurrency::cancellation_token_source geopositionTaskTokenSource;
Windows::Globalization::DateTimeFormatting::DateTimeFormatter^ formatterShortDateLongTime;
Windows::Globalization::DateTimeFormatting::DateTimeFormatter^ formatterLongTime;
Windows::Globalization::Calendar^ calendar;
Platform::Collections::Vector<GeofenceItem^>^ geofenceCollection;
Platform::Collections::Vector<Platform::String^>^ eventCollection;
Platform::Agile<Windows::UI::Core::CoreWindow> coreWindow;
};
}
}

Просмотреть файл

@ -1,637 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// Scenario4_ForegroundGeofenceHelpers.cpp
// Implementation of the Scenario4 class
//
#include "pch.h"
#include "Scenario4_ForegroundGeofence.xaml.h"
using namespace SDKTemplate;
using namespace SDKTemplate::GeolocationCPP;
using namespace concurrency;
using namespace Platform;
using namespace Windows::Data::Json;
using namespace Windows::Devices::Enumeration;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Devices::Geolocation::Geofencing;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Storage;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
const unsigned int secondsPerMinute = 60;
const unsigned int secondsPerHour = 60 * secondsPerMinute;
const unsigned int secondsPerDay = 24 * secondsPerHour;
const unsigned int oneHundredNanosecondsPerSecond = 10000000;
const unsigned int timeComponentBufferSize = 10;
const unsigned int maxEventDescriptors = 42; // Value determined by how many max length event descriptors (91 chars)
// stored as a JSON string can fit in 8K (max allowed for local settings)
void Scenario4::OnSetStartTimeToNow(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
SetStartTimeToNowFunction();
}
void Scenario4::SetStartTimeToNowFunction()
{
try
{
calendar->SetToNow();
DateTime dt = calendar->GetDateTime();
StartTime->Text = formatterShortDateLongTime->Format(dt);
}
catch (Platform::Exception^ ex)
{
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
}
}
void Scenario4::OnSetPositionToHere(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
SetPositionProgressBar->Visibility = Windows::UI::Xaml::Visibility::Visible;
SetPositionToHereButton->IsEnabled = false;
Latitude->IsEnabled = false;
Longitude->IsEnabled = false;
// Request a high accuracy position for better accuracy locating the geofence
geolocator->DesiredAccuracy = PositionAccuracy::High;
task<Geoposition^> geopositionTask(geolocator->GetGeopositionAsync(), geopositionTaskTokenSource.get_token());
geopositionTask.then([this](task<Geoposition^> getPosTask)
{
try
{
// Get will throw an exception if the task was canceled or failed with an error
Geoposition^ pos = getPosTask.get();
Latitude->Text = pos->Coordinate->Point->Position.Latitude.ToString();
Longitude->Text = pos->Coordinate->Point->Position.Longitude.ToString();
// clear status
rootPage->NotifyUser("", NotifyType::StatusMessage);
}
catch (task_canceled&)
{
rootPage->NotifyUser("Operation canceled", NotifyType::StatusMessage);
}
catch (Exception^ ex)
{
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
}
});
// restore cursor and re-enable button
SetPositionProgressBar->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
SetPositionToHereButton->IsEnabled = true;
Latitude->IsEnabled = true;
Longitude->IsEnabled = true;
}
Platform::String^ Scenario4::GetTimeStampedMessage(Platform::String^ EventCalled)
{
Platform::String^ message;
calendar->SetToNow();
message = EventCalled + " " + formatterLongTime->Format(calendar->GetDateTime());
return message;
}
void Scenario4::OnLatitudeTextChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::TextChangedEventArgs^ e)
{
latitudeSet = TextChangedHandlerDouble(false, "Latitude", Latitude);
CreateGeofenceButton->IsEnabled = SettingsAvailable();
}
void Scenario4::OnLongitudeTextChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::TextChangedEventArgs^ e)
{
longitudeSet = TextChangedHandlerDouble(false, "Longitude", Longitude);
CreateGeofenceButton->IsEnabled = SettingsAvailable();
}
void Scenario4::OnRadiusTextChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::TextChangedEventArgs^ e)
{
radiusSet = TextChangedHandlerDouble(false, "Radius", Radius);
CreateGeofenceButton->IsEnabled = SettingsAvailable();
}
void Scenario4::OnIdTextChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::TextChangedEventArgs^ e)
{
// get number of characters
unsigned int charCount = Id->Text->Length();
nameSet = (0 != charCount);
CharCount->Text = charCount.ToString() + " characters";
CreateGeofenceButton->IsEnabled = SettingsAvailable();
}
void Scenario4::OnRegisteredGeofenceListBoxSelectionChanged(Platform::Object^ sender, Windows::UI::Xaml::Controls::SelectionChangedEventArgs^ e)
{
IVector<Object^>^ list = e->AddedItems;
if (0 == list->Size)
{
// disable the remove button
RemoveGeofenceItem->IsEnabled = false;
}
else
{
// enable the remove button
RemoveGeofenceItem->IsEnabled = true;
// update controls with the values from this geofence item
// get selected item
GeofenceItem^ item = safe_cast<GeofenceItem^>(RegisteredGeofenceListBox->SelectedItem);
RefreshControlsFromGeofenceItem(item);
CreateGeofenceButton->IsEnabled = SettingsAvailable();
}
}
void Scenario4::GetTimeComponentAsString(Platform::String^& str, int timecomponent, bool appenddelimiter)
{
if (0 != timecomponent)
{
if (timecomponent < 10 && str->Length())
{
str += L"0";
}
str += timecomponent.ToString();
}
else if (str->Length())
{
str += L"00";
}
if (appenddelimiter && str->Length())
{
str += L":";
}
}
Platform::String^ Scenario4::GetDurationString(long long duration)
{
long long totalSeconds = duration / oneHundredNanosecondsPerSecond;
int days = safe_cast<int>(totalSeconds / secondsPerDay);
totalSeconds -= days * secondsPerDay;
int hours = safe_cast<int>(totalSeconds / secondsPerHour);
totalSeconds -= hours * secondsPerHour;
int minutes = safe_cast<int>(totalSeconds / secondsPerMinute);
totalSeconds -= minutes * secondsPerMinute;
int seconds = safe_cast<int>(totalSeconds);
Platform::String^ str;
GetTimeComponentAsString(str, days, true);
GetTimeComponentAsString(str, hours, true);
GetTimeComponentAsString(str, minutes, true);
GetTimeComponentAsString(str, seconds, false);
return str;
}
void Scenario4::RefreshControlsFromGeofenceItem(GeofenceItem^ item)
{
if (nullptr != item)
{
Id->Text = item->Id;
Latitude->Text = item->Latitude.ToString();
Longitude->Text = item->Longitude.ToString();
Radius->Text = item->Radius.ToString();
SingleUse->IsChecked = item->SingleUse;
if (0 != item->StartTime)
{
DateTime dt;
dt.UniversalTime = item->StartTime;
StartTime->Text = formatterShortDateLongTime->Format(dt);
}
else
{
StartTime->Text = "";
}
if (0 != item->DwellTime)
{
DwellTime->Text = GetDurationString(item->DwellTime);
}
else
{
DwellTime->Text = "";
}
if (0 != item->Duration)
{
Duration->Text = GetDurationString(item->Duration);
}
else
{
Duration->Text = "";
}
// Update flags used to enable Create Geofence button
OnIdTextChanged(nullptr, nullptr);
OnLongitudeTextChanged(nullptr, nullptr);
OnLatitudeTextChanged(nullptr, nullptr);
OnRadiusTextChanged(nullptr, nullptr);
}
}
bool Scenario4::TextChangedHandlerDouble(bool nullAllowed, Platform::String^ name, Windows::UI::Xaml::Controls::TextBox^ e)
{
bool valueSet = false;
if (e->Text->IsEmpty())
{
if (false == nullAllowed)
{
if (nullptr != name)
{
auto strMsg = name + " needs a value";
rootPage->NotifyUser(strMsg, NotifyType::StatusMessage);
}
}
else
{
valueSet = true;
}
}
else
{
valueSet = true;
double value = FromStringTo<double>(e->Text);
if (0 == value)
{
// make sure string was '0'
if ("0" != e->Text)
{
auto strMsg = name + " must be a number";
rootPage->NotifyUser(strMsg, NotifyType::StatusMessage);
valueSet = false;
}
}
if (true == valueSet)
{
// clear out status message
rootPage->NotifyUser("", NotifyType::StatusMessage);
}
}
return valueSet;
}
bool Scenario4::TextChangedHandlerInt(bool nullAllowed, Platform::String^ name, Windows::UI::Xaml::Controls::TextBox^ e)
{
bool valueSet = false;
if (e->Text->IsEmpty())
{
if (false == nullAllowed)
{
if (nullptr != name)
{
auto strMsg = name + " needs a value";
rootPage->NotifyUser(strMsg, NotifyType::StatusMessage);
}
}
else
{
valueSet = true;
}
}
else
{
valueSet = true;
int value = FromStringTo<int>(e->Text);
if (0 == value)
{
// make sure string was '0'
if ("0" != e->Text)
{
auto strMsg = name + " must be a number";
rootPage->NotifyUser(strMsg, NotifyType::StatusMessage);
valueSet = false;
}
}
if (true == valueSet)
{
// clear out status message
rootPage->NotifyUser("", NotifyType::StatusMessage);
}
}
return valueSet;
}
// are settings available so a geofence can be created?
bool Scenario4::SettingsAvailable()
{
bool fSettingsAvailable = false;
if (true == nameSet &&
true == latitudeSet &&
true == longitudeSet &&
true == radiusSet)
{
// also need to test if data is good
fSettingsAvailable = true;
}
return fSettingsAvailable;
}
// add geofence to listbox
void Scenario4::AddGeofenceToRegisteredGeofenceListBox(Windows::Devices::Geolocation::Geofencing::Geofence^ geofence)
{
GeofenceItem^ item = ref new GeofenceItem(geofence);
// The registered geofence listbox is data bound
// to a collection
// so once the GeofenceItem is added to the
// collection it will appear in the
// registered geofence listbox.
geofenceCollection->InsertAt(0, item);
}
long long Scenario4::GetDurationFromString(Platform::String^ str)
{
long long result = 0;
long tally = 0;
std::wistringstream ss(str->Data());
// create an array of strings to hold time information
// (days/hours/minutes/seconds)
std::vector<std::array<wchar_t, timeComponentBufferSize>> v;
// parse string using the : delimiter
for (std::array<wchar_t, timeComponentBufferSize> a; ss.getline(&a[0], timeComponentBufferSize, ':');)
{
v.push_back(a);
}
auto start = 4 - v.size();
if (start >= 0)
{
// convert string to a number
enum { day = 0, hour, minute, second };
auto component = start;
bool stayinloop = true;
for (auto& a : v)
{
int timeComponentResult = _wtoi(&a[0]);
switch (component)
{
case day:
timeComponentResult *= secondsPerDay;
break;
case hour:
timeComponentResult *= secondsPerHour;
break;
case minute:
timeComponentResult *= secondsPerMinute;
break;
case second:
break;
default:
stayinloop = false;
break;
}
if (!stayinloop)
{
break;
}
tally += timeComponentResult;
++component;
}
}
result = tally;
result *= oneHundredNanosecondsPerSecond;
return result;
}
long long Scenario4::GetUniversalTimeFromString(Platform::String^ str)
{
long long result = 0;
std::tm t;
std::wistringstream ss(str->Data());
ss >> std::get_time(&t, L"%m/%d/%Y %H:%M:%S");
SYSTEMTIME st = { 0 };
st.wYear = t.tm_year + 1900;
st.wMonth = t.tm_mon + 1;
st.wDay = t.tm_mday;
st.wHour = t.tm_hour;
st.wMinute = t.tm_min;
st.wSecond = t.tm_sec;
// now convert to UTC
SYSTEMTIME stUTC = { 0 };
TIME_ZONE_INFORMATION tzi = { 0 };
if (0 != ::GetTimeZoneInformation(&tzi))
{
if (TRUE == ::TzSpecificLocalTimeToSystemTime(&tzi, &st, &stUTC))
{
FILETIME ft;
if (TRUE == ::SystemTimeToFileTime(&stUTC, &ft))
{
_ULARGE_INTEGER ulint = { ft.dwLowDateTime, ft.dwHighDateTime };
result = ulint.QuadPart;
}
}
}
return result;
}
/// <summary>
/// This is the click handler for the 'Create Geofence' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Scenario4::OnCreateGeofence(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
try
{
// This must be done here because there is no guarantee of
// getting the location consent from a geofence call.
if (false == permissionsChecked)
{
GetGeopositionAsync();
permissionsChecked = true;
}
// get lat/long/radius, the fence name (fenceKey),
// and other properties from controls,
// depending on data in controls for activation time
// and duration the appropriate
// constructor will be used.
Geofence^ geofence = GenerateGeofence();
// Add the geofence to the GeofenceMonitor's
// collection of fences
geofences->InsertAt(0, geofence);
// add geofence to listbox
AddGeofenceToRegisteredGeofenceListBox(geofence);
}
catch (task_canceled&)
{
rootPage->NotifyUser("Canceled", NotifyType::StatusMessage);
}
catch (Platform::Exception^ ex)
{
// GeofenceMonitor failed in adding a geofence
// exceptions could be from out of memory, lat/long out of range,
// too long a name, not a unique name, specifying an activation
// time + duration that is still in the past
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
}
}
void Scenario4::GetGeopositionAsync()
{
rootPage->NotifyUser("Checking permissions...", NotifyType::StatusMessage);
inGetPositionAsync = true;
task<Geoposition^> geopositionTask(geolocator->GetGeopositionAsync(), geopositionTaskTokenSource.get_token());
geopositionTask.then([this](task<Geoposition^> getPosTask)
{
try
{
// Get will throw an exception if the task was canceled or failed with an error
Geoposition^ pos = getPosTask.get();
// clear status
rootPage->NotifyUser("", NotifyType::StatusMessage);
}
catch (task_canceled&)
{
rootPage->NotifyUser("Operation canceled", NotifyType::StatusMessage);
}
catch (Exception^ ex)
{
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
}
});
inGetPositionAsync = false;
}
void Scenario4::FillRegisteredGeofenceListBoxWithExistingGeofences()
{
for (auto geofence : geofences)
{
AddGeofenceToRegisteredGeofenceListBox(geofence);
}
}
void Scenario4::FillEventListBoxWithExistingEvents()
{
auto settings = ApplicationData::Current->LocalSettings->Values;
if (settings->HasKey("ForegroundGeofenceEventCollection"))
{
String^ geofenceEvent = safe_cast<String^>(settings->Lookup("ForegroundGeofenceEventCollection"));
if (0 != geofenceEvent->Length())
{
auto events = JsonValue::Parse(geofenceEvent)->GetArray();
// NOTE: the events are accessed in reverse order
// because the events were added to JSON from
// newer to older. AddEventDescription() adds
// each new entry to the beginning of the collection.
for (int pos = events->Size - 1; pos >= 0; pos--)
{
auto element = events->GetAt(pos);
AddEventDescription(element->GetString());
}
}
settings->Remove("ForegroundGeofenceEventCollection");
}
}
void Scenario4::SaveExistingEvents()
{
auto jsonArray = ref new JsonArray();
for (auto eventDescriptor : eventCollection)
{
jsonArray->Append(JsonValue::CreateStringValue(eventDescriptor->ToString()));
}
String^ jsonString = jsonArray->Stringify();
auto settings = ApplicationData::Current->LocalSettings->Values;
settings->Insert("ForegroundGeofenceEventCollection", jsonString);
}
void Scenario4::AddEventDescription(Platform::String^ eventDescription)
{
if (eventCollection->Size == maxEventDescriptors)
{
eventCollection->RemoveAtEnd();
}
eventCollection->InsertAt(0, eventDescription);
}

Просмотреть файл

@ -1,40 +0,0 @@
<!--
//*********************************************************
//
// 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.
//
//*********************************************************
-->
<Page x:Class="SDKTemplate.GeolocationCPP.Scenario5" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:SDKTemplate.GeolocationCPP" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid x:Name="LayoutRoot" HorizontalAlignment="Left" VerticalAlignment="Top">
<StackPanel Orientation="Vertical">
<TextBlock x:Name="InputTextBlock" TextWrapping="Wrap" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Control registration of a background task to receive geofencing events. Geofences need to be created using the Foreground Geofencing scenario before background geofence events can occur." />
<StackPanel Orientation="Horizontal" Margin="0,10,0,10">
<Button x:Name="RegisterBackgroundTaskButton" Content="Register" Margin="0,0,10,0" Click="RegisterBackgroundTask"/>
<Button x:Name="UnregisterBackgroundTaskButton" Content="Unregister" Margin="0,0,10,0" Click="UnregisterBackgroundTask"/>
</StackPanel>
<Grid Name="Grid_GeofenceEvents" HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Grid.Column="0" Margin="10" Orientation="Vertical">
<TextBlock Style="{StaticResource BasicTextStyle}" Text="Geofence"/>
<TextBlock Style="{StaticResource BasicTextStyle}" Text="Events" />
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="10" Grid.Row="1" Grid.Column="1">
<ListBox Name="GeofenceBackgroundEventsListBox" Width="260" Height="240" ItemsSource="{Binding}"/>
</StackPanel>
</Grid>
</StackPanel>
</Grid>
</Page>

Просмотреть файл

@ -1,285 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// Scenario5_BackgroundTask.xaml.cpp
// Implementation of the Scenario5 class
//
#include "pch.h"
#include "Scenario5_GeofenceBackgroundTask.xaml.h"
using namespace SDKTemplate;
using namespace SDKTemplate::GeolocationCPP;
using namespace concurrency;
using namespace Platform;
using namespace Windows::ApplicationModel::Background;
using namespace Windows::Data::Json;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Storage;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml::Navigation;
const int oneHundredNanosecondsPerSecond = 10000000; // conversion from 100 nano-second resolution to seconds
Scenario5::Scenario5() : rootPage(MainPage::Current), sampleBackgroundTaskName("SampleGeofenceBackgroundTask"), sampleBackgroundTaskEntryPoint("BackgroundTask.GeofenceBackgroundTask")
{
InitializeComponent();
// using data binding to the root page collection of GeofenceItems associated with events
geofenceBackgroundEvents = ref new Platform::Collections::Vector<Platform::String^>();
GeofenceBackgroundEventsListBox->DataContext = geofenceBackgroundEvents;
FillEventListBoxWithExistingEvents();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void Scenario5::OnNavigatedTo(NavigationEventArgs^ e)
{
// Look for an already registered background task
geofenceTask = nullptr;
auto iter = BackgroundTaskRegistration::AllTasks->First();
while (iter->HasCurrent)
{
auto task = iter->Current;
if (task->Value->Name == sampleBackgroundTaskName)
{
geofenceTask = safe_cast<BackgroundTaskRegistration^>(task->Value);
break;
}
iter->MoveNext();
}
if (geofenceTask != nullptr)
{
FillEventListBoxWithExistingEvents();
// Register for background task completion notifications
taskCompletedToken = geofenceTask->Completed::add(ref new BackgroundTaskCompletedEventHandler(this, &Scenario5::OnCompleted));
try
{
// Check the background access status of the application and display the appropriate status message
switch (BackgroundExecutionManager::GetAccessStatus())
{
case BackgroundAccessStatus::AlwaysAllowed:
case BackgroundAccessStatus::AllowedSubjectToSystemPolicy:
rootPage->NotifyUser("Background task is already registered. Waiting for next update...", NotifyType::StatusMessage);
break;
default:
rootPage->NotifyUser("Not able to run in background.", NotifyType::ErrorMessage);
break;
}
}
catch (Exception^ ex)
{
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
}
UpdateButtonStates(/*registered:*/ true);
}
else
{
UpdateButtonStates(/*registered:*/ false);
}
}
/// <summary>
/// Invoked when this page is no longer displayed.
/// </summary>
/// <param name="e"></param>
void Scenario5::OnNavigatedFrom(NavigationEventArgs^ e)
{
}
void Scenario5::RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
try
{
// Get permission for a background task from the user. If the user has already answered once,
// this does nothing and the user must manually update their preference via PC Settings.
task<BackgroundAccessStatus> requestAccessTask(BackgroundExecutionManager::RequestAccessAsync());
requestAccessTask.then([this](BackgroundAccessStatus backgroundAccessStatus)
{
// Regardless of the answer, register the background task. If the user later adds this application
// to the lock screen, the background task will be ready to run.
// Create a new background task builder
BackgroundTaskBuilder^ geofenceTaskBuilder = ref new BackgroundTaskBuilder();
geofenceTaskBuilder->Name = sampleBackgroundTaskName;
geofenceTaskBuilder->TaskEntryPoint = sampleBackgroundTaskEntryPoint;
// Create a new location trigger
auto trigger = ref new LocationTrigger(LocationTriggerType::Geofence);
// Associate the location trigger with the background task builder
geofenceTaskBuilder->SetTrigger(trigger);
// If it is important that there is user presence and/or
// internet connection when OnCompleted is called
// the following could be called before calling Register()
// SystemCondition^ condition = ref new SystemCondition(SystemConditionType::UserPresent | SystemConditionType::InternetAvailable);
// geofenceTaskBuilder->AddCondition(condition);
// Register the background task
geofenceTask = geofenceTaskBuilder->Register();
// Register for background task completion notifications
taskCompletedToken = geofenceTask->Completed::add(ref new BackgroundTaskCompletedEventHandler(this, &Scenario5::OnCompleted));
UpdateButtonStates(/*registered:*/ true);
// Check the background access status of the application and display the appropriate status message
switch (backgroundAccessStatus)
{
case BackgroundAccessStatus::AlwaysAllowed:
case BackgroundAccessStatus::AllowedSubjectToSystemPolicy:
rootPage->NotifyUser("Background task registered.", NotifyType::StatusMessage);
// Need to request access to location
// This must be done with background task registration
// because the background task cannot display UI
RequestLocationAccess();
break;
default:
rootPage->NotifyUser("Background tasks may be disabled for this app", NotifyType::ErrorMessage);
break;
}
});
}
catch (Exception^ ex)
{
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
UpdateButtonStates(/*registered:*/ false);
}
}
void Scenario5::UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
// Unregister the background task
if (geofenceTask != nullptr)
{
geofenceTask->Unregister(true);
geofenceTask = nullptr;
}
rootPage->NotifyUser("Background task unregistered", NotifyType::StatusMessage);
UpdateButtonStates(/*registered:*/ false);
}
void Scenario5::OnCompleted(BackgroundTaskRegistration^ task, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ args)
{
// Update the UI with progress reported by the background task
// We need to dispatch to the UI thread to display the output
Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new DispatchedHandler(
[this, args]()
{
try
{
// Throw an exception if the background task had an unrecoverable error
args->CheckResult();
// Update the UI with the completion status of the background task
auto settings = ApplicationData::Current->LocalSettings->Values;
if (settings->HasKey("Status"))
{
rootPage->NotifyUser(safe_cast<String^>(settings->Lookup("Status")), NotifyType::StatusMessage);
}
// add background events to listbox
FillEventListBoxWithExistingEvents();
}
catch (Exception^ ex)
{
// The background task had an error
rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
}
},
CallbackContext::Any
)
);
}
void Scenario5::FillEventListBoxWithExistingEvents()
{
auto settings = ApplicationData::Current->LocalSettings->Values;
if (settings->HasKey("BackgroundGeofenceEventCollection"))
{
String^ geofenceEvent = safe_cast<String^>(settings->Lookup("BackgroundGeofenceEventCollection"));
if (0 != geofenceEvent->Length())
{
// remove all entries and repopulate
geofenceBackgroundEvents->Clear();
auto events = JsonValue::Parse(geofenceEvent)->GetArray();
// NOTE: the events are accessed in reverse order
// because the events were added to JSON from
// newer to older. geofenceBackgroundEvents->InsertAt(0,...) adds
// each new entry to the beginning of the collection.
for (int pos = events->Size - 1; pos >= 0; pos--)
{
auto element = events->GetAt(pos)->GetString();
geofenceBackgroundEvents->InsertAt(0, element);
}
}
}
}
/// <summary>
/// Update the enable state of the register/unregister buttons.
/// </summary>
void Scenario5::UpdateButtonStates(bool registered)
{
auto uiDelegate = [this, registered]()
{
RegisterBackgroundTaskButton->IsEnabled = !registered;
UnregisterBackgroundTaskButton->IsEnabled = registered;
};
auto handler = ref new Windows::UI::Core::DispatchedHandler(uiDelegate, Platform::CallbackContext::Any);
Dispatcher->RunAsync(CoreDispatcherPriority::Normal, handler);
}
void Scenario5::RequestLocationAccess()
{
task<GeolocationAccessStatus> geolocationAccessRequestTask(Windows::Devices::Geolocation::Geolocator::RequestAccessAsync());
geolocationAccessRequestTask.then([this](task<GeolocationAccessStatus> accessStatusTask)
{
auto accessStatus = accessStatusTask.get();
switch (accessStatus)
{
case GeolocationAccessStatus::Allowed:
break;
case GeolocationAccessStatus::Denied:
rootPage->NotifyUser("Access to location is denied.", NotifyType::ErrorMessage);
break;
case GeolocationAccessStatus::Unspecified:
rootPage->NotifyUser("Unspecified error!", NotifyType::ErrorMessage);
break;
}
});
}

Просмотреть файл

@ -1,58 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// Scenario5_BackgroundTask.xaml.h
// Declaration of the Scenario5 class
//
#pragma once
#include "pch.h"
#include "Scenario5_GeofenceBackgroundTask.g.h"
#include "MainPage.xaml.h"
namespace SDKTemplate
{
namespace GeolocationCPP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Scenario5 sealed
{
private:
Platform::Collections::Vector<Platform::String^>^ geofenceBackgroundEvents;
public:
Scenario5();
protected:
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
private:
MainPage^ rootPage;
Platform::String^ sampleBackgroundTaskName;
Platform::String^ sampleBackgroundTaskEntryPoint;
Windows::ApplicationModel::Background::BackgroundTaskRegistration^ geofenceTask;
Windows::Foundation::EventRegistrationToken taskCompletedToken;
void RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void RequestLocationAccess();
void OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ sender, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ e);
void FillEventListBoxWithExistingEvents();
void UpdateButtonStates(bool registered);
};
}
}

Просмотреть файл

@ -1,67 +0,0 @@
<!--
//*********************************************************
//
// 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.
//
//*********************************************************
-->
<Page x:Class="SDKTemplate.GeolocationCPP.Scenario6" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:SDKTemplate.GeolocationCPP" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid x:Name="LayoutRoot" HorizontalAlignment="Left" VerticalAlignment="Top">
<StackPanel Orientation="Vertical">
<TextBlock x:Name="InputTextBlock" TextWrapping="Wrap" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Geolocation API allows application to get the last visit report." />
<Grid HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,10,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
</Grid>
<StackPanel Orientation="Horizontal" Margin="0,10,0,10">
<Button x:Name="GetLastVisitButton" Content="Get last Visit" Margin="0,0,10,0" Click="GetLastVisitButtonClicked"/>
</StackPanel>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="0" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="State change: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="1" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Timestamp: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="2" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Latitude: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="3" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Longitude: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="4" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Accuracy: " />
<TextBlock x:Name="ScenarioOutput_VisitStateChange" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="0" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Timestamp" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="1" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Latitude" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="2" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Longitude" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="3" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Accuracy" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="4" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
</Grid>
<TextBlock TextWrapping="Wrap" x:Name="LocationDisabledMessage" Margin="0,10,0,0" FontStyle="Italic" Visibility="Collapsed">
<Run Text="Application is not able to get location data. Go to " />
<Hyperlink NavigateUri="ms-settings:privacy-location">
<Run Text="Settings" />
</Hyperlink>
<Run Text=" to check the location permissions."/>
</TextBlock>
</StackPanel>
</Grid>
</Page>

Просмотреть файл

@ -1,117 +0,0 @@
//*********************************************************
//
// 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_GetLastVisit.xaml.h"
using namespace SDKTemplate;
using namespace SDKTemplate::GeolocationCPP;
using namespace concurrency;
using namespace Platform;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Foundation;
using namespace Windows::Globalization::DateTimeFormatting;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
Scenario6::Scenario6() : rootPage(MainPage::Current)
{
InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void Scenario6::OnNavigatedTo(NavigationEventArgs^ e)
{
GetLastVisitButton->IsEnabled = true;
}
void Scenario6::GetLastVisitButtonClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
GetLastVisitButton->IsEnabled = false;
LocationDisabledMessage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
// Request permission to access location.
create_task(Geolocator::RequestAccessAsync()).then([this](GeolocationAccessStatus accessStatus)
{
switch (accessStatus)
{
case GeolocationAccessStatus::Allowed:
rootPage->NotifyUser("Waiting for update...", NotifyType::StatusMessage);
// Get the last visit report, if any.
return create_task(GeovisitMonitor::GetLastReportAsync()).then([this](Geovisit^ visit)
{
rootPage->NotifyUser("Location updated.", NotifyType::StatusMessage);
return visit;
});
case GeolocationAccessStatus::Denied:
rootPage->NotifyUser("Access to location is denied.", NotifyType::ErrorMessage);
LocationDisabledMessage->Visibility = Windows::UI::Xaml::Visibility::Visible;
break;
case GeolocationAccessStatus::Unspecified:
default:
rootPage->NotifyUser("Unspecified error!", NotifyType::ErrorMessage);
break;
}
return task_from_result<Geovisit^>(nullptr);
}).then([this](Geovisit^ visit)
{
UpdateLastVisit(visit);
GetLastVisitButton->IsEnabled = true;
});
}
/// <summary>
/// Updates the user interface with the Geovisit data provided
/// </summary>
/// <param name="visit">Geovisit to display its details</param>
void Scenario6::UpdateLastVisit(Geovisit^ visit)
{
if (visit == nullptr)
{
ScenarioOutput_Latitude->Text = "No data";
ScenarioOutput_Longitude->Text = "No data";
ScenarioOutput_Accuracy->Text = "No data";
ScenarioOutput_Timestamp->Text = "No data";
ScenarioOutput_VisitStateChange->Text = "No data";
}
else
{
// A valid visit is available, extract the state change and Timestamp.
ScenarioOutput_VisitStateChange->Text = visit->StateChange.ToString();
DateTimeFormatter^ dateFormatter = ref new DateTimeFormatter("shortdate longtime");
ScenarioOutput_Timestamp->Text = dateFormatter->Format(visit->Timestamp);
// If a valid position is available, extract the position information that caused the state change to happen.
if (visit->Position == nullptr)
{
ScenarioOutput_Latitude->Text = "No data";
ScenarioOutput_Longitude->Text = "No data";
ScenarioOutput_Accuracy->Text = "No data";
}
else
{
ScenarioOutput_Latitude->Text = visit->Position->Coordinate->Point->Position.Latitude.ToString();
ScenarioOutput_Longitude->Text = visit->Position->Coordinate->Point->Position.Longitude.ToString();
ScenarioOutput_Accuracy->Text = visit->Position->Coordinate->Accuracy.ToString();
}
}
}

Просмотреть файл

@ -1,41 +0,0 @@
//*********************************************************
//
// 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"
#include "Scenario6_GetLastVisit.g.h"
#include "MainPage.xaml.h"
namespace SDKTemplate
{
namespace GeolocationCPP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Scenario6 sealed
{
public:
Scenario6();
protected:
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
private:
MainPage^ rootPage;
void GetLastVisitButtonClicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void UpdateLastVisit(Windows::Devices::Geolocation::Geovisit^ Visit);
};
}
}

Просмотреть файл

@ -1,55 +0,0 @@
<!--
//*********************************************************
//
// 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.
//
//*********************************************************
-->
<Page x:Class="SDKTemplate.GeolocationCPP.Scenario7" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:SDKTemplate.GeolocationCPP" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid x:Name="LayoutRoot" HorizontalAlignment="Left" VerticalAlignment="Top">
<StackPanel Orientation="Vertical">
<TextBlock x:Name="InputTextBlock" TextWrapping="Wrap" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Geolocation API allows application to monitor user's visits in the foreground." Margin="1,0,-1,10" />
<StackPanel Orientation="Horizontal" Margin="0,10,0,10">
<Button x:Name="StartMonitoringButton" Content="Start Monitoring" Margin="0,0,10,0" Click="StartMonitoring"/>
<Button x:Name="StopMonitoringButton" Content="Stop Monitoring" Margin="0,0,10,0" Click="StopMonitoring"/>
</StackPanel>
<Grid HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="0" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="State change: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="1" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Timestamp: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="2" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Latitude: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="3" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Longitude: " />
<TextBlock TextWrapping="Wrap" Margin="0,0,10,0" Grid.Row="4" Grid.Column="0" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Accuracy: " />
<TextBlock x:Name="ScenarioOutput_VisitStateChange" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="0" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Timestamp" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="1" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Latitude" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="2" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Longitude" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="3" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
<TextBlock x:Name="ScenarioOutput_Accuracy" Margin="0,0,10,0" TextWrapping="Wrap" Grid.Row="4" Grid.Column="1" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="No data" />
</Grid>
<TextBlock TextWrapping="Wrap" x:Name="LocationDisabledMessage" Margin="0,10,0,0" FontStyle="Italic" Visibility="Collapsed">
<Run Text="Application is not able to get location data. Go to " />
<Hyperlink NavigateUri="ms-settings:privacy-location">
<Run Text="Settings" />
</Hyperlink>
<Run Text=" to check the location permissions."/>
</TextBlock>
</StackPanel>
</Grid>
</Page>

Просмотреть файл

@ -1,161 +0,0 @@
//*********************************************************
//
// 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_ForegroundVisits.xaml.h"
using namespace SDKTemplate;
using namespace SDKTemplate::GeolocationCPP;
using namespace concurrency;
using namespace Platform;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Foundation;
using namespace Windows::Globalization::DateTimeFormatting;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
Scenario7::Scenario7() : rootPage(MainPage::Current)
{
InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void Scenario7::OnNavigatedTo(NavigationEventArgs^ e)
{
StartMonitoringButton->IsEnabled = true;
StopMonitoringButton->IsEnabled = false;
}
/// <summary>
/// Invoked when this page is no longer displayed.
/// </summary>
/// <param name="e"></param>
void Scenario7::OnNavigatedFrom(NavigationEventArgs^ e)
{
if (_visitMonitor)
{
_visitMonitor->Stop();
}
}
/// <summary>
/// This is the click handler for the 'StartMonitoring' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Scenario7::StartMonitoring(Object^ sender, RoutedEventArgs^ e)
{
// Request permission to access location.
create_task(Geolocator::RequestAccessAsync()).then([this](GeolocationAccessStatus accessStatus)
{
switch (accessStatus)
{
case GeolocationAccessStatus::Allowed:
_visitMonitor = ref new GeovisitMonitor();
// Add visit state changed event handler
_visitMonitor->VisitStateChanged += ref new TypedEventHandler<GeovisitMonitor^, GeovisitStateChangedEventArgs^>(this, &Scenario7::OnVisitStateChanged);
// Start monitoring with the desired scope.
// For higher granularity, choose venue/building level changes.
// For lower granularity more or less in the range of zipcode level changes, choose city.
// Choosing Venue here as an example.
_visitMonitor->Start(VisitMonitoringScope::Venue);
LocationDisabledMessage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
rootPage->NotifyUser("Waiting for update...", NotifyType::StatusMessage);
StartMonitoringButton->IsEnabled = false;
StopMonitoringButton->IsEnabled = true;
break;
case GeolocationAccessStatus::Denied:
rootPage->NotifyUser("Access to location is denied.", NotifyType::ErrorMessage);
LocationDisabledMessage->Visibility = Windows::UI::Xaml::Visibility::Visible;
break;
case GeolocationAccessStatus::Unspecified:
default:
rootPage->NotifyUser("Unspecified error!", NotifyType::ErrorMessage);
LocationDisabledMessage->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
break;
}
});
}
/// <summary>
/// This is the click handler for the 'StopMonitoring' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Scenario7::StopMonitoring(Object^ sender, RoutedEventArgs^ e)
{
// Stop visit monitoring.
_visitMonitor->Stop();
_visitMonitor = nullptr;
StartMonitoringButton->IsEnabled = true;
StopMonitoringButton->IsEnabled = false;
// Clear status
rootPage->NotifyUser("", NotifyType::StatusMessage);
}
/// <summary>
/// Event handler for Visitstatechanged events. It is raised when
/// a new visit state change is available based on the monitoring scope specified.
/// </summary>
/// <param name="sender">Geovisitmonitor instance</param>
/// <param name="args">visitstatechanged args data</param>
void Scenario7::OnVisitStateChanged(GeovisitMonitor^ sender, GeovisitStateChangedEventArgs^ args)
{
Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]()
{
rootPage->NotifyUser("Visit state changed.", NotifyType::StatusMessage);
UpdateVisitData(args->Visit);
}));
}
/// <summary>
/// Updates the user interface with the Geovisit data provided
/// </summary>
/// <param name="visit">Geovisit to display its details</param>
void Scenario7::UpdateVisitData(Geovisit^ visit)
{
// A valid visit is available, extract the state change and Timestamp.
ScenarioOutput_VisitStateChange->Text = visit->StateChange.ToString();
DateTimeFormatter^ dateFormatter = ref new DateTimeFormatter("shortdate longtime");
ScenarioOutput_Timestamp->Text = dateFormatter->Format(visit->Timestamp);
// If a valid position is available, extract the position information that caused the state change to happen.
if (visit->Position == nullptr)
{
ScenarioOutput_Latitude->Text = "No data";
ScenarioOutput_Longitude->Text = "No data";
ScenarioOutput_Accuracy->Text = "No data";
}
else
{
ScenarioOutput_Latitude->Text = visit->Position->Coordinate->Point->Position.Latitude.ToString();
ScenarioOutput_Longitude->Text = visit->Position->Coordinate->Point->Position.Longitude.ToString();
ScenarioOutput_Accuracy->Text = visit->Position->Coordinate->Accuracy.ToString();
}
}

Просмотреть файл

@ -1,48 +0,0 @@
//*********************************************************
//
// 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"
#include "Scenario7_ForegroundVisits.g.h"
#include "MainPage.xaml.h"
namespace SDKTemplate
{
namespace GeolocationCPP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Scenario7 sealed
{
public:
Scenario7();
protected:
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
virtual void OnNavigatedFrom(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
private:
MainPage^ rootPage;
Windows::Devices::Geolocation::GeovisitMonitor^ _visitMonitor;
void StartMonitoring(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void StopMonitoring(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void UpdateVisitData(Windows::Devices::Geolocation::Geovisit^ Visit);
void OnVisitStateChanged(Windows::Devices::Geolocation::GeovisitMonitor^ sender, Windows::Devices::Geolocation::GeovisitStateChangedEventArgs^ args);
};
}
}

Просмотреть файл

@ -1,40 +0,0 @@
<!--
//*********************************************************
//
// 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.
//
//*********************************************************
-->
<Page x:Class="SDKTemplate.GeolocationCPP.Scenario8" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:SDKTemplate.GeolocationCPP" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">
<Grid x:Name="LayoutRoot" HorizontalAlignment="Left" VerticalAlignment="Top">
<StackPanel Orientation="Vertical">
<TextBlock x:Name="InputTextBlock" TextWrapping="Wrap" Style="{StaticResource BasicTextStyle}" HorizontalAlignment="Left" Text="Control registration of a background task to receive Visit state change events." />
<StackPanel Orientation="Horizontal" Margin="0,10,0,10">
<Button x:Name="RegisterBackgroundTaskButton" Content="Register" Margin="0,0,10,0" Click="RegisterBackgroundTask"/>
<Button x:Name="UnregisterBackgroundTaskButton" Content="Unregister" Margin="0,0,10,0" Click="UnregisterBackgroundTask"/>
</StackPanel>
<Grid Name="Grid_VisitEvents" HorizontalAlignment="Left" VerticalAlignment="Top">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Grid.Column="0" Margin="10" Orientation="Vertical">
<TextBlock Style="{StaticResource BasicTextStyle}" Text="Visit"/>
<TextBlock Style="{StaticResource BasicTextStyle}" Text="Events"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="10" Grid.Row="1" Grid.Column="1">
<ListBox Name="VisitBackgroundEventsListBox" Width="460" Height="240" ItemsSource="{Binding}"/>
</StackPanel>
</Grid>
</StackPanel>
</Grid>
</Page>

Просмотреть файл

@ -1,266 +0,0 @@
//*********************************************************
//
// 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 "Scenario8_VisitsBackgroundTask.xaml.h"
using namespace SDKTemplate;
using namespace SDKTemplate::GeolocationCPP;
using namespace concurrency;
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::ApplicationModel::Background;
using namespace Windows::Data::Json;
using namespace Windows::Devices::Geolocation;
using namespace Windows::Storage;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Navigation;
Scenario8::Scenario8() :
rootPage(MainPage::Current),
_sampleBackgroundTaskName("SampleVisitBackgroundTask"),
_sampleBackgroundTaskEntryPoint("BackgroundTask.VisitBackgroundTask")
{
InitializeComponent();
// using data binding to the root page collection of Visit Items associated with events
_visitBackgroundEvents = ref new Vector<String^>();
VisitBackgroundEventsListBox->DataContext = _visitBackgroundEvents;
FillEventListBoxWithExistingEvents();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void Scenario8::OnNavigatedTo(NavigationEventArgs^ e)
{
// Look for an already registered background task
_visitTask = nullptr;
auto iter = BackgroundTaskRegistration::AllTasks->First();
while (iter->HasCurrent)
{
auto task = iter->Current;
if (task->Value->Name == _sampleBackgroundTaskName)
{
_visitTask = safe_cast<BackgroundTaskRegistration^>(task->Value);
break;
}
iter->MoveNext();
}
if (_visitTask != nullptr)
{
FillEventListBoxWithExistingEvents();
// Register for background task completion notifications
_taskCompletedToken = _visitTask->Completed += ref new BackgroundTaskCompletedEventHandler(this, &Scenario8::OnCompleted);
// Check the background access status of the application and display the appropriate status message
switch (BackgroundExecutionManager::GetAccessStatus())
{
case BackgroundAccessStatus::AlwaysAllowed:
case BackgroundAccessStatus::AllowedSubjectToSystemPolicy:
rootPage->NotifyUser("Background task is already registered. Waiting for next update...", NotifyType::StatusMessage);
break;
default:
rootPage->NotifyUser("Not able to run in background.", NotifyType::ErrorMessage);
break;
}
UpdateButtonStates(/*registered:*/ true);
}
else
{
UpdateButtonStates(/*registered:*/ false);
}
}
void Scenario8::RegisterBackgroundTask(Object^ sender, RoutedEventArgs^ e)
{
try
{
// Get permission for a background task from the user. If the user has already answered once,
// this does nothing and the user must manually update their preference via PC Settings.
create_task(BackgroundExecutionManager::RequestAccessAsync()).then([this](BackgroundAccessStatus backgroundAccessStatus)
{
// Create a new background task builder
BackgroundTaskBuilder^ _visitTaskBuilder = ref new BackgroundTaskBuilder();
_visitTaskBuilder->Name = _sampleBackgroundTaskName;
_visitTaskBuilder->TaskEntryPoint = _sampleBackgroundTaskEntryPoint;
// Create a new visit trigger
auto trigger = ref new GeovisitTrigger();
// Set the desired monitoring scope.
// For higher granularity, choose venue/building level changes.
// For lower granularity more or less in the range of zipcode level changes, choose city.
// Choosing Venue here as an example.
trigger->MonitoringScope = VisitMonitoringScope::Venue;
// Associate the trigger with the background task builder
_visitTaskBuilder->SetTrigger(trigger);
// If it is important that there is user presence and/or
// internet connection when OnCompleted is called
// the following could be called before calling Register()
// SystemCondition^ condition = ref new SystemCondition(SystemConditionType::UserPresent | SystemConditionType::InternetAvailable);
// _visitTaskBuilder->AddCondition(condition);
// Register the background task
_visitTask = _visitTaskBuilder->Register();
// Register for background task completion notifications
_taskCompletedToken = _visitTask->Completed += ref new BackgroundTaskCompletedEventHandler(this, &Scenario8::OnCompleted);
UpdateButtonStates(/*registered:*/ true);
// Check the background access status of the application and display the appropriate status message
switch (backgroundAccessStatus)
{
case BackgroundAccessStatus::AlwaysAllowed:
case BackgroundAccessStatus::AllowedSubjectToSystemPolicy:
rootPage->NotifyUser("Background task registered.", NotifyType::StatusMessage);
// Need to request access to location
// This must be done with background task registration
// because the background task cannot display UI
RequestLocationAccess();
break;
default:
rootPage->NotifyUser("Background tasks may be disabled for this app", NotifyType::ErrorMessage);
break;
}
});
}
catch (Exception^ ex)
{
rootPage->NotifyUser(ex->ToString(), NotifyType::ErrorMessage);
UpdateButtonStates(/*registered:*/ false);
}
}
void Scenario8::UnregisterBackgroundTask(Object^ sender, RoutedEventArgs^ e)
{
// Unregister the background task
if (_visitTask != nullptr)
{
_visitTask->Completed -= _taskCompletedToken;
_visitTask->Unregister(true);
_visitTask = nullptr;
}
rootPage->NotifyUser("Visit background task unregistered", NotifyType::StatusMessage);
ClearExistingEvents();
UpdateButtonStates(/*registered:*/ false);
}
void Scenario8::OnCompleted(BackgroundTaskRegistration^ sender, BackgroundTaskCompletedEventArgs^ args)
{
// Update the UI with progress reported by the background task
// We need to dispatch to the UI thread to display the output
Dispatcher->RunAsync(
CoreDispatcherPriority::Normal,
ref new DispatchedHandler(
[this, args]()
{
try
{
// Throw an exception if the background task had an unrecoverable error
args->CheckResult();
// add background events to listbox
FillEventListBoxWithExistingEvents();
}
catch (Exception^ ex)
{
// The background task had an error
rootPage->NotifyUser(ex->Message, NotifyType::ErrorMessage);
}
}));
}
/// <summary>
/// Populate events list box with entries from BackgroundVisitEventCollection.
/// </summary>
void Scenario8::FillEventListBoxWithExistingEvents()
{
auto settings = ApplicationData::Current->LocalSettings->Values;
if (settings->HasKey("BackgroundVisitEventCollection"))
{
String^ visitEvent = safe_cast<String^>(settings->Lookup("BackgroundVisitEventCollection"));
if (0 != visitEvent->Length())
{
// remove all entries and repopulate
_visitBackgroundEvents->Clear();
for (auto& element : JsonValue::Parse(visitEvent)->GetArray())
{
_visitBackgroundEvents->Append(element->ToString());
}
}
}
}
/// <summary>
/// Clear events from BackgroundVisitEventCollection.
/// </summary>
void Scenario8::ClearExistingEvents()
{
auto settings = ApplicationData::Current->LocalSettings->Values;
settings->Insert("BackgroundVisitEventCollection", "");
_visitBackgroundEvents->Clear();
}
/// <summary>
/// Update the enable state of the register/unregister buttons.
/// </summary>
void Scenario8::UpdateButtonStates(bool registered)
{
Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, registered]()
{
RegisterBackgroundTaskButton->IsEnabled = !registered;
UnregisterBackgroundTaskButton->IsEnabled = registered;
}));
}
void Scenario8::RequestLocationAccess()
{
create_task(Windows::Devices::Geolocation::Geolocator::RequestAccessAsync()).then([this](GeolocationAccessStatus accessStatus)
{
switch (accessStatus)
{
case GeolocationAccessStatus::Allowed:
break;
case GeolocationAccessStatus::Denied:
rootPage->NotifyUser("Access to location is denied.", NotifyType::ErrorMessage);
break;
default:
case GeolocationAccessStatus::Unspecified:
rootPage->NotifyUser("Unspecified error!", NotifyType::ErrorMessage);
break;
}
});
}

Просмотреть файл

@ -1,50 +0,0 @@
// 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"
#include "Scenario8_VisitsBackgroundTask.g.h"
#include "MainPage.xaml.h"
namespace SDKTemplate
{
namespace GeolocationCPP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Scenario8 sealed
{
public:
Scenario8();
protected:
virtual void OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs^ e) override;
private:
MainPage^ rootPage;
Platform::String^ _sampleBackgroundTaskName;
Platform::String^ _sampleBackgroundTaskEntryPoint;
Windows::ApplicationModel::Background::BackgroundTaskRegistration^ _visitTask;
Windows::Foundation::EventRegistrationToken _taskCompletedToken;
Platform::Collections::Vector<Platform::String^>^ _visitBackgroundEvents;
void RegisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void UnregisterBackgroundTask(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void RequestLocationAccess();
void OnCompleted(Windows::ApplicationModel::Background::BackgroundTaskRegistration^ sender, Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs^ e);
void UpdateButtonStates(bool registered);
void FillEventListBoxWithExistingEvents();
void ClearExistingEvents();
};
}
}

Просмотреть файл

@ -1,17 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// pch.cpp
// Include the standard header and generate the precompiled header.
//
#include "pch.h"

Просмотреть файл

@ -1,46 +0,0 @@
//*********************************************************
//
// 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.
//
//*********************************************************
//
// pch.h
// Header for standard system include files.
//
#pragma once
#include <string>
#include <sstream>
#include <locale>
#include <iomanip>
#include <ctime>
#include <vector>
#include <array>
#include <collection.h>
#include <ppltasks.h>
#include "App.xaml.h"
template <class T>
inline T FromStringTo(Platform::String^ str)
{
std::wistringstream wiss(str->Data());
T value = 0;
wiss >> value;
return value;
}
template <class T>
inline T FromStringTo(std::wstring str)
{
std::wistringstream wiss(str);
T value = 0;
wiss >> value;
return value;
}

Просмотреть файл

@ -1,48 +0,0 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26228.4
MinimumVisualStudioVersion = 10.0.40219.1
Project("{262852C6-CD72-467D-83FE-5EEB1973A190}") = "Geolocation", "GeolocationJS\Geolocation.jsproj", "{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|ARM = Debug|ARM
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|ARM = Release|ARM
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Debug|ARM.ActiveCfg = Debug|ARM
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Debug|ARM.Build.0 = Debug|ARM
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Debug|ARM.Deploy.0 = Debug|ARM
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Debug|x64.ActiveCfg = Debug|x64
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Debug|x64.Build.0 = Debug|x64
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Debug|x64.Deploy.0 = Debug|x64
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Debug|x86.ActiveCfg = Debug|x86
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Debug|x86.Build.0 = Debug|x86
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Debug|x86.Deploy.0 = Debug|x86
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Release|Any CPU.Build.0 = Release|Any CPU
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Release|Any CPU.Deploy.0 = Release|Any CPU
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Release|ARM.ActiveCfg = Release|ARM
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Release|ARM.Build.0 = Release|ARM
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Release|ARM.Deploy.0 = Release|ARM
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Release|x64.ActiveCfg = Release|x64
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Release|x64.Build.0 = Release|x64
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Release|x64.Deploy.0 = Release|x64
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Release|x86.ActiveCfg = Release|x86
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Release|x86.Build.0 = Release|x86
{97CD8D8F-C8A6-5F8F-A311-81CDBB82379E}.Release|x86.Deploy.0 = Release|x86
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

Просмотреть файл

@ -1,169 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|AnyCPU">
<Configuration>Debug</Configuration>
<Platform>AnyCPU</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|ARM">
<Configuration>Debug</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x86">
<Configuration>Debug</Configuration>
<Platform>x86</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|AnyCPU">
<Configuration>Release</Configuration>
<Platform>AnyCPU</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM">
<Configuration>Release</Configuration>
<Platform>ARM</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x86">
<Configuration>Release</Configuration>
<Platform>x86</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>97cd8d8f-c8a6-5f8f-a311-81cdbb82379e</ProjectGuid>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup Condition="'$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0'">
<VisualStudioVersion>14.0</VisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\$(WMSJSProjectDirectory)\Microsoft.VisualStudio.$(WMSJSProject).Default.props" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\$(WMSJSProjectDirectory)\Microsoft.VisualStudio.$(WMSJSProject).props" />
<PropertyGroup>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion>10.0.18362.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.18362.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>$(VersionNumberMajor).$(VersionNumberMinor)</MinimumVisualStudioVersion>
<DefaultLanguage>en-US</DefaultLanguage>
</PropertyGroup>
<ItemGroup>
<AppxManifest Include="package.appxmanifest">
<SubType>Designer</SubType>
</AppxManifest>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\css\default.css">
<Link>css\default.css</Link>
</Content>
<Content Include="css\scenario1_TrackPosition.css" />
<Content Include="css\scenario2_GetPosition.css" />
<Content Include="css\scenario3_BackgroundTask.css" />
<Content Include="css\scenario4_ForegroundGeofence.css" />
<Content Include="css\scenario5_GeofenceBackgroundTask.css" />
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\default.html">
<Link>default.html</Link>
</Content>
<Content Include="css\scenario8_VisitsBackgroundTask.css" />
<Content Include="html\scenario1_TrackPosition.html" />
<Content Include="html\scenario2_GetPosition.html" />
<Content Include="html\scenario3_BackgroundTask.html" />
<Content Include="html\scenario4_ForegroundGeofence.html" />
<Content Include="html\scenario5_GeofenceBackgroundTask.html" />
<Content Include="..\..\..\..\SharedContent\media\badge-logo.png">
<Link>images\badge-logo.png</Link>
</Content>
<Content Include="..\..\..\..\SharedContent\media\microsoft-sdk.png">
<Link>images\microsoft-sdk.png</Link>
</Content>
<Content Include="..\..\..\..\SharedContent\media\smalltile-sdk.png">
<Link>images\smallTile-sdk.png</Link>
</Content>
<Content Include="..\..\..\..\SharedContent\media\splash-sdk.png">
<Link>images\splash-sdk.png</Link>
</Content>
<Content Include="..\..\..\..\SharedContent\media\storelogo-sdk.png">
<Link>images\storeLogo-sdk.png</Link>
</Content>
<Content Include="..\..\..\..\SharedContent\media\squaretile-sdk.png">
<Link>images\squaretile-sdk.png</Link>
</Content>
<Content Include="..\..\..\..\SharedContent\media\tile-sdk.png">
<Link>images\tile-sdk.png</Link>
</Content>
<Content Include="..\..\..\..\SharedContent\media\windows-sdk.png">
<Link>images\windows-sdk.png</Link>
</Content>
<Content Include="html\scenario6_GetLastVisit.html" />
<Content Include="html\scenario7_ForegroundVisits.html" />
<Content Include="html\scenario8_VisitsBackgroundTask.html" />
<Content Include="js\backgroundtask.js" />
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\js\default.js">
<Link>js\default.js</Link>
</Content>
<Content Include="js\geofencebackgroundtask.js" />
<Content Include="js\geofenceitem.js" />
<Content Include="js\sample-configuration.js" />
<Content Include="js\scenario1_TrackPosition.js" />
<Content Include="js\scenario2_GetPosition.js" />
<Content Include="js\scenario3_BackgroundTask.js" />
<Content Include="js\scenario4_ForegroundGeofence.js" />
<Content Include="js\scenario5_GeofenceBackgroundTask.js" />
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\Microsoft.WinJS\css\ui-dark.css">
<Link>Microsoft.WinJS.4.0\css\ui-dark.css</Link>
</Content>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\Microsoft.WinJS\css\ui-light.css">
<Link>Microsoft.WinJS.4.0\css\ui-light.css</Link>
</Content>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\Microsoft.WinJS\js\en-US\ui.strings.js">
<Link>Microsoft.WinJS.4.0\js\en-US\ui.strings.js</Link>
</Content>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\Microsoft.WinJS\js\WinJS.intellisense-setup.js">
<Link>Microsoft.WinJS.4.0\js\WinJS.intellisense-setup.js</Link>
</Content>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\Microsoft.WinJS\js\WinJS.intellisense.js">
<Link>Microsoft.WinJS.4.0\js\WinJS.intellisense.js</Link>
</Content>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\Microsoft.WinJS\fonts\Symbols.ttf">
<Link>Microsoft.WinJS.4.0\fonts\Symbols.ttf</Link>
</Content>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\Microsoft.WinJS\js\base.js">
<Link>Microsoft.WinJS.4.0\js\base.js</Link>
</Content>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\Microsoft.WinJS\js\ui.js">
<Link>Microsoft.WinJS.4.0\js\ui.js</Link>
</Content>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\sample-utils\footer.html">
<Link>sample-utils\footer.html</Link>
</Content>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\sample-utils\header.html">
<Link>sample-utils\header.html</Link>
</Content>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\sample-utils\sample-utils.js">
<Link>sample-utils\sample-utils.js</Link>
</Content>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\sample-utils\scenario-select.css">
<Link>sample-utils\scenario-select.css</Link>
</Content>
<Content Include="\.\.\\\.\.\\\.\.\\SharedContent\\js\sample-utils\scenario-select.html">
<Link>sample-utils\scenario-select.html</Link>
</Content>
<Content Include="js\scenario6_GetLastVisit.js" />
<Content Include="js\scenario7_ForegroundVisits.js" />
<Content Include="js\scenario8_VisitsBackgroundTask.js" />
<Content Include="js\visitbackgroundtask.js" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\$(WMSJSProjectDirectory)\Microsoft.VisualStudio.$(WMSJSProject).targets" />
<!-- To modify your build process, add your task inside one of the targets below then uncomment
that target and the DisableFastUpToDateCheck PropertyGroup.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
<PropertyGroup>
<DisableFastUpToDateCheck>true</DisableFastUpToDateCheck>
</PropertyGroup>
-->
</Project>

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше