diff --git a/Samples/360VideoPlayback/README.md b/Samples/360VideoPlayback/README.md
index 2b7fa99628..2a8a86ea75 100644
--- a/Samples/360VideoPlayback/README.md
+++ b/Samples/360VideoPlayback/README.md
@@ -5,7 +5,7 @@ languages:
- cpp
products:
- windows
-- uwp
+- windows-uwp
---
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario1_DevicePicker.xaml.cs b/Samples/DeviceEnumerationAndPairing/cs/Scenario1_DevicePicker.xaml.cs
index 44d46b599e..e382c144a7 100644
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario1_DevicePicker.xaml.cs
+++ b/Samples/DeviceEnumerationAndPairing/cs/Scenario1_DevicePicker.xaml.cs
@@ -9,26 +9,19 @@
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
-using SDKTemplate;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
-namespace DeviceEnumeration
+namespace SDKTemplate
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class Scenario1 : Page
{
- private MainPage rootPage;
+ private MainPage rootPage = MainPage.Current;
- private DevicePicker devicePicker = null;
-
- public ObservableCollection ResultCollection
- {
- get;
- private set;
- }
+ private ObservableCollection resultCollection = new ObservableCollection();
public Scenario1()
{
@@ -37,17 +30,9 @@ public Scenario1()
protected override void OnNavigatedTo(NavigationEventArgs e)
{
- rootPage = MainPage.Current;
- ResultCollection = new ObservableCollection();
-
+ resultsListView.ItemsSource = resultCollection;
selectorComboBox.ItemsSource = DeviceSelectorChoices.DevicePickerSelectors;
selectorComboBox.SelectedIndex = 0;
-
- DataContext = this;
- }
-
- protected override void OnNavigatedFrom(NavigationEventArgs e)
- {
}
private void PickSingleDeviceButton_Click(object sender, RoutedEventArgs e)
@@ -67,9 +52,9 @@ private void ShowDevicePickerButton_Click(object sender, RoutedEventArgs e)
private async void ShowDevicePicker(bool pickSingle)
{
showDevicePickerButton.IsEnabled = false;
- ResultCollection.Clear();
+ resultCollection.Clear();
- devicePicker = new DevicePicker();
+ var devicePicker = new DevicePicker();
// First get the device selector chosen by the UI.
DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;
@@ -97,7 +82,7 @@ private async void ShowDevicePicker(bool pickSingle)
DeviceInformation di = await devicePicker.PickSingleDeviceAsync(rect);
if (null != di)
{
- ResultCollection.Add(new DeviceInformationDisplay(di));
+ resultCollection.Add(new DeviceInformationDisplay(di));
}
showDevicePickerButton.IsEnabled = true;
}
@@ -106,7 +91,7 @@ private async void ShowDevicePicker(bool pickSingle)
devicePicker.DevicePickerDismissed += new TypedEventHandler(
async (picker, obj) =>
{
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
+ // Must access UI elements from the UI thread.
await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{
showDevicePickerButton.IsEnabled = true;
@@ -120,8 +105,8 @@ await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
// Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
{
- ResultCollection.Clear();
- ResultCollection.Add(new DeviceInformationDisplay(args.SelectedDevice));
+ resultCollection.Clear();
+ resultCollection.Add(new DeviceInformationDisplay(args.SelectedDevice));
});
});
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario2_DeviceWatcher.xaml b/Samples/DeviceEnumerationAndPairing/cs/Scenario2_DeviceWatcher.xaml
deleted file mode 100644
index 1c860bad19..0000000000
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario2_DeviceWatcher.xaml
+++ /dev/null
@@ -1,94 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario2_DeviceWatcher.xaml.cs b/Samples/DeviceEnumerationAndPairing/cs/Scenario2_DeviceWatcher.xaml.cs
index ef8f9ecd8f..13a3783a37 100644
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario2_DeviceWatcher.xaml.cs
+++ b/Samples/DeviceEnumerationAndPairing/cs/Scenario2_DeviceWatcher.xaml.cs
@@ -8,51 +8,39 @@
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
-using SDKTemplate;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
-namespace DeviceEnumeration
+namespace SDKTemplate
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class Scenario2 : Page
{
- private MainPage rootPage;
+ private MainPage rootPage = MainPage.Current;
- private DeviceWatcher deviceWatcher = null;
- private TypedEventHandler handlerAdded = null;
- private TypedEventHandler handlerUpdated = null;
- private TypedEventHandler handlerRemoved = null;
- private TypedEventHandler handlerEnumCompleted = null;
- private TypedEventHandler handlerStopped = null;
+ private DeviceWatcherHelper deviceWatcherHelper;
- public ObservableCollection ResultCollection
- {
- get;
- private set;
- }
+ private ObservableCollection resultCollection = new ObservableCollection();
public Scenario2()
{
this.InitializeComponent();
+
+ deviceWatcherHelper = new DeviceWatcherHelper(resultCollection, Dispatcher);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
- rootPage = MainPage.Current;
- ResultCollection = new ObservableCollection();
-
+ resultsListView.ItemsSource = resultCollection;
selectorComboBox.ItemsSource = DeviceSelectorChoices.DeviceWatcherSelectors;
selectorComboBox.SelectedIndex = 0;
-
- DataContext = this;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
- StopWatcher();
+ deviceWatcherHelper.Reset();
}
private void StartWatcherButton_Click(object sender, RoutedEventArgs e)
@@ -68,11 +56,12 @@ private void StopWatcherButton_Click(object sender, RoutedEventArgs e)
private void StartWatcher()
{
startWatcherButton.IsEnabled = false;
- ResultCollection.Clear();
+ resultCollection.Clear();
// First get the device selector chosen by the UI.
DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;
+ DeviceWatcher deviceWatcher;
if (null == deviceSelectorInfo.Selector)
{
// If the a pre-canned device class selector was chosen, call the DeviceClass overload
@@ -83,7 +72,7 @@ private void StartWatcher()
// Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
// Kind will be determined by the selector
deviceWatcher = DeviceInformation.CreateWatcher(
- deviceSelectorInfo.Selector,
+ deviceSelectorInfo.Selector,
null // don't request additional properties for this sample
);
}
@@ -96,115 +85,15 @@ private void StartWatcher()
deviceSelectorInfo.Kind);
}
- // Hook up handlers for the watcher events before starting the watcher
-
- handlerAdded = new TypedEventHandler(async (watcher, deviceInfo) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));
-
- rootPage.NotifyUser(
- String.Format("{0} devices found.", ResultCollection.Count),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.Added += handlerAdded;
-
- handlerUpdated = new TypedEventHandler(async (watcher, deviceInfoUpdate) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- // Find the corresponding updated DeviceInformation in the collection and pass the update object
- // to the Update method of the existing DeviceInformation. This automatically updates the object
- // for us.
- foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
- {
- if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
- {
- deviceInfoDisp.Update(deviceInfoUpdate);
- break;
- }
- }
- });
- });
- deviceWatcher.Updated += handlerUpdated;
-
- handlerRemoved = new TypedEventHandler(async (watcher, deviceInfoUpdate) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- // Find the corresponding DeviceInformation in the collection and remove it
- foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
- {
- if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
- {
- ResultCollection.Remove(deviceInfoDisp);
- break;
- }
- }
-
- rootPage.NotifyUser(
- String.Format("{0} devices found.", ResultCollection.Count),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.Removed += handlerRemoved;
-
- handlerEnumCompleted = new TypedEventHandler(async (watcher, obj) =>
- {
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- rootPage.NotifyUser(
- String.Format("{0} devices found. Enumeration completed. Watching for updates...", ResultCollection.Count),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.EnumerationCompleted += handlerEnumCompleted;
-
- handlerStopped = new TypedEventHandler(async (watcher, obj) =>
- {
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- rootPage.NotifyUser(
- String.Format("{0} devices found. Watcher {1}.",
- ResultCollection.Count,
- DeviceWatcherStatus.Aborted == watcher.Status ? "aborted" : "stopped"),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.Stopped += handlerStopped;
-
rootPage.NotifyUser("Starting Watcher...", NotifyType.StatusMessage);
- deviceWatcher.Start();
+ deviceWatcherHelper.StartWatcher(deviceWatcher);
stopWatcherButton.IsEnabled = true;
}
private void StopWatcher()
{
stopWatcherButton.IsEnabled = false;
-
- if (null != deviceWatcher)
- {
- // First unhook all event handlers except the stopped handler. This ensures our
- // event handlers don't get called after stop, as stop won't block for any "in flight"
- // event handler calls. We leave the stopped handler as it's guaranteed to only be called
- // once and we'll use it to know when the query is completely stopped.
- deviceWatcher.Added -= handlerAdded;
- deviceWatcher.Updated -= handlerUpdated;
- deviceWatcher.Removed -= handlerRemoved;
- deviceWatcher.EnumerationCompleted -= handlerEnumCompleted;
-
- if (DeviceWatcherStatus.Started == deviceWatcher.Status ||
- DeviceWatcherStatus.EnumerationCompleted == deviceWatcher.Status)
- {
- deviceWatcher.Stop();
- }
- }
-
+ deviceWatcherHelper.StopWatcher();
startWatcherButton.IsEnabled = true;
}
}
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario3_BackgroundDeviceWatcher.xaml b/Samples/DeviceEnumerationAndPairing/cs/Scenario3_BackgroundDeviceWatcher.xaml
deleted file mode 100644
index 145fb3e0a1..0000000000
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario3_BackgroundDeviceWatcher.xaml
+++ /dev/null
@@ -1,65 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario3_BackgroundDeviceWatcher.xaml.cs b/Samples/DeviceEnumerationAndPairing/cs/Scenario3_BackgroundDeviceWatcher.xaml.cs
index f78b052cab..3668c95992 100644
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario3_BackgroundDeviceWatcher.xaml.cs
+++ b/Samples/DeviceEnumerationAndPairing/cs/Scenario3_BackgroundDeviceWatcher.xaml.cs
@@ -1,26 +1,24 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
+using Windows.ApplicationModel.Background;
using Windows.Devices.Enumeration;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
-using SDKTemplate;
-// Needed for the DeviceWatcherTrigger
-using Windows.ApplicationModel.Background;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
-namespace DeviceEnumeration
+namespace SDKTemplate
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class Scenario3 : Page
{
- private MainPage rootPage;
+ private MainPage rootPage = MainPage.Current;
private string backgroundTaskName = "DeviceEnumerationCs_BackgroundTaskName";
private IBackgroundTaskRegistration backgroundTaskRegistration = null;
@@ -32,13 +30,9 @@ public Scenario3()
protected override void OnNavigatedTo(NavigationEventArgs e)
{
- rootPage = MainPage.Current;
-
selectorComboBox.ItemsSource = DeviceSelectorChoices.BackgroundDeviceWatcherSelectors;
selectorComboBox.SelectedIndex = 0;
- DataContext = this;
-
// Determine if the background task is already active
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
@@ -52,6 +46,15 @@ protected override void OnNavigatedTo(NavigationEventArgs e)
}
}
+ protected override void OnNavigatedFrom(NavigationEventArgs e)
+ {
+ if (backgroundTaskRegistration != null)
+ {
+ backgroundTaskRegistration.Completed -= OnTaskCompleted;
+ backgroundTaskRegistration = null;
+ }
+ }
+
private void StartWatcherButton_Click(object sender, RoutedEventArgs e)
{
StartWatcher();
@@ -102,7 +105,7 @@ private void StartWatcher()
// Register this trigger for our background task
RegisterBackgroundTask(deviceWatcherTrigger);
-
+
stopWatcherButton.IsEnabled = true;
rootPage.NotifyUser("Watcher started...", NotifyType.StatusMessage);
}
@@ -128,7 +131,7 @@ private void RegisterBackgroundTask(DeviceWatcherTrigger deviceWatcherTrigger)
taskBuilder.SetTrigger(deviceWatcherTrigger);
backgroundTaskRegistration = taskBuilder.Register();
- backgroundTaskRegistration.Completed += new BackgroundTaskCompletedEventHandler(OnTaskCompleted);
+ backgroundTaskRegistration.Completed += OnTaskCompleted;
}
private async void OnTaskCompleted(BackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario4_Snapshot.xaml b/Samples/DeviceEnumerationAndPairing/cs/Scenario4_Snapshot.xaml
deleted file mode 100644
index a29eb7d205..0000000000
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario4_Snapshot.xaml
+++ /dev/null
@@ -1,85 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario4_Snapshot.xaml.cs b/Samples/DeviceEnumerationAndPairing/cs/Scenario4_Snapshot.xaml.cs
index 58bbcd0fc0..350a759238 100644
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario4_Snapshot.xaml.cs
+++ b/Samples/DeviceEnumerationAndPairing/cs/Scenario4_Snapshot.xaml.cs
@@ -6,24 +6,19 @@
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
-using SDKTemplate;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
-namespace DeviceEnumeration
+namespace SDKTemplate
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class Scenario4 : Page
{
- private MainPage rootPage;
+ private MainPage rootPage = MainPage.Current;
- public ObservableCollection ResultCollection
- {
- get;
- private set;
- }
+ private ObservableCollection resultCollection = new ObservableCollection();
public Scenario4()
{
@@ -32,13 +27,10 @@ public Scenario4()
protected override void OnNavigatedTo(NavigationEventArgs e)
{
- rootPage = MainPage.Current;
- ResultCollection = new ObservableCollection();
+ resultsListView.ItemsSource = resultCollection;
selectorComboBox.ItemsSource = DeviceSelectorChoices.FindAllAsyncSelectors;
selectorComboBox.SelectedIndex = 0;
-
- DataContext = this;
}
private async void FindButton_Click(object sender, RoutedEventArgs e)
@@ -47,7 +39,7 @@ private async void FindButton_Click(object sender, RoutedEventArgs e)
DeviceInformationCollection deviceInfoCollection;
findButton.IsEnabled = false;
- ResultCollection.Clear();
+ resultCollection.Clear();
// First get the device selector chosen by the UI.
deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;
@@ -69,12 +61,12 @@ private async void FindButton_Click(object sender, RoutedEventArgs e)
}
rootPage.NotifyUser(
- String.Format("FindAllAsync operation completed. {0} devices found.", deviceInfoCollection.Count),
+ String.Format("FindAllAsync operation completed. {0} devices found.", deviceInfoCollection.Count),
NotifyType.StatusMessage);
foreach (DeviceInformation deviceInfo in deviceInfoCollection)
{
- ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));
+ resultCollection.Add(new DeviceInformationDisplay(deviceInfo));
}
findButton.IsEnabled = true;
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario5_GetSingleDevice.xaml b/Samples/DeviceEnumerationAndPairing/cs/Scenario5_GetSingleDevice.xaml
deleted file mode 100644
index c583fbdecb..0000000000
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario5_GetSingleDevice.xaml
+++ /dev/null
@@ -1,81 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- Enter a device interface id:
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario5_GetSingleDevice.xaml.cs b/Samples/DeviceEnumerationAndPairing/cs/Scenario5_GetSingleDevice.xaml.cs
index cb0952da4d..f5502dbf6e 100644
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario5_GetSingleDevice.xaml.cs
+++ b/Samples/DeviceEnumerationAndPairing/cs/Scenario5_GetSingleDevice.xaml.cs
@@ -7,25 +7,20 @@
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
-using SDKTemplate;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
-namespace DeviceEnumeration
+namespace SDKTemplate
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class Scenario5 : Page
{
- private MainPage rootPage;
+ private MainPage rootPage = MainPage.Current;
private DeviceInformationKind deviceInformationKind;
- public ObservableCollection ResultCollection
- {
- get;
- private set;
- }
+ private ObservableCollection resultCollection = new ObservableCollection();
public Scenario5()
{
@@ -34,10 +29,7 @@ public Scenario5()
protected override void OnNavigatedTo(NavigationEventArgs e)
{
- rootPage = MainPage.Current;
- ResultCollection = new ObservableCollection();
-
- DataContext = this;
+ resultsListView.ItemsSource = resultCollection;
}
private async void InterfaceIdTextBox_Loaded(object sender, RoutedEventArgs e)
@@ -61,8 +53,8 @@ private async void GetButton_Click(object sender, RoutedEventArgs e)
interfaceIdTextBox.IsEnabled = false;
getButton.IsEnabled = false;
- ResultCollection.Clear();
-
+ resultCollection.Clear();
+
rootPage.NotifyUser("CreateFromIdAsync operation started...", NotifyType.StatusMessage);
try
@@ -73,7 +65,7 @@ private async void GetButton_Click(object sender, RoutedEventArgs e)
rootPage.NotifyUser("CreateFromIdAsync operation completed.", NotifyType.StatusMessage);
- ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));
+ resultCollection.Add(new DeviceInformationDisplay(deviceInfo));
}
catch (FileNotFoundException)
{
@@ -81,7 +73,7 @@ private async void GetButton_Click(object sender, RoutedEventArgs e)
}
getButton.IsEnabled = true;
- getButton.Focus(Windows.UI.Xaml.FocusState.Keyboard);
+ getButton.Focus(FocusState.Keyboard);
interfaceIdTextBox.IsEnabled = true;
}
}
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario6_CustomFilterAddedProps.xaml b/Samples/DeviceEnumerationAndPairing/cs/Scenario6_CustomFilterAddedProps.xaml
deleted file mode 100644
index b149e4ae7b..0000000000
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario6_CustomFilterAddedProps.xaml
+++ /dev/null
@@ -1,103 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario6_CustomFilterAddedProps.xaml.cs b/Samples/DeviceEnumerationAndPairing/cs/Scenario6_CustomFilterAddedProps.xaml.cs
index 43de89876e..2f85329109 100644
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario6_CustomFilterAddedProps.xaml.cs
+++ b/Samples/DeviceEnumerationAndPairing/cs/Scenario6_CustomFilterAddedProps.xaml.cs
@@ -8,47 +8,37 @@
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
-using SDKTemplate;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
-namespace DeviceEnumeration
+namespace SDKTemplate
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class Scenario6 : Page
{
- private MainPage rootPage;
+ private MainPage rootPage = MainPage.Current;
- private DeviceWatcher deviceWatcher = null;
- private TypedEventHandler handlerAdded = null;
- private TypedEventHandler handlerUpdated = null;
- private TypedEventHandler handlerRemoved = null;
- private TypedEventHandler handlerEnumCompleted = null;
- private TypedEventHandler handlerStopped = null;
+ private DeviceWatcherHelper deviceWatcherHelper;
- public ObservableCollection ResultCollection
- {
- get;
- private set;
- }
+ private ObservableCollection resultCollection = new ObservableCollection();
public Scenario6()
{
this.InitializeComponent();
+
+ deviceWatcherHelper = new DeviceWatcherHelper(resultCollection, Dispatcher);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
- rootPage = MainPage.Current;
- ResultCollection = new ObservableCollection();
- DataContext = this;
+ resultsListView.ItemsSource = resultCollection;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
- StopWatcher();
+ deviceWatcherHelper.Reset();
}
private void StartWatcherButton_Click(object sender, RoutedEventArgs e)
@@ -65,10 +55,10 @@ private void StartWatcher()
{
aqsFilterTextBox.IsEnabled = false;
startWatcherButton.IsEnabled = false;
- ResultCollection.Clear();
+ resultCollection.Clear();
- // Request some additional properties. In this saample, these extra properties are just used in the ResultsListViewTemplate.
- // Take a look there in the XAML. Also look at the coverter used by the XAML GeneralPropertyValueConverter. In general you just use
+ // Request some additional properties. In this saample, these extra properties are just used in the ResultsListViewTemplate.
+ // Take a look there in the XAML. Also look at the converter used by the XAML GeneralPropertyValueConverter. In general you just use
// DeviceInformation.Properties[""] to get a property. e.g. DeviceInformation.Properties["System.Devices.InterfaceClassGuid"].
string[] requestedProperties = new string[] {
"System.Devices.InterfaceClassGuid",
@@ -76,94 +66,12 @@ private void StartWatcher()
};
// Use AQS string filter from the text box
- deviceWatcher = DeviceInformation.CreateWatcher(
+ DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher(
aqsFilterTextBox.Text,
requestedProperties);
- // Hook up handlers for the watcher events before starting the watcher
-
- handlerAdded = new TypedEventHandler(async (watcher, deviceInfo) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
- {
- ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));
-
- rootPage.NotifyUser(
- String.Format("{0} devices found.", ResultCollection.Count),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.Added += handlerAdded;
-
- handlerUpdated = new TypedEventHandler(async (watcher, deviceInfoUpdate) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
- {
- // Find the corresponding updated DeviceInformation in the collection and pass the update object
- // to the Update method of the existing DeviceInformation. This automatically updates the object
- // for us.
- foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
- {
- if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
- {
- deviceInfoDisp.Update(deviceInfoUpdate);
- break;
- }
- }
- });
- });
- deviceWatcher.Updated += handlerUpdated;
-
- handlerRemoved = new TypedEventHandler(async (watcher, deviceInfoUpdate) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
- {
- // Find the corresponding DeviceInformation in the collection and remove it
- foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
- {
- if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
- {
- ResultCollection.Remove(deviceInfoDisp);
- break;
- }
- }
-
- rootPage.NotifyUser(
- String.Format("{0} devices found.", ResultCollection.Count),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.Removed += handlerRemoved;
-
- handlerEnumCompleted = new TypedEventHandler(async (watcher, obj) =>
- {
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
- {
- rootPage.NotifyUser(
- String.Format("{0} devices found. Enumeration completed. Watching for updates...", ResultCollection.Count),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.EnumerationCompleted += handlerEnumCompleted;
-
- handlerStopped = new TypedEventHandler(async (watcher, obj) =>
- {
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
- {
- rootPage.NotifyUser(
- String.Format("{0} devices found. Watcher {1}.",
- ResultCollection.Count,
- DeviceWatcherStatus.Aborted == watcher.Status ? "aborted" : "stopped"),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.Stopped += handlerStopped;
-
rootPage.NotifyUser("Starting Watcher...", NotifyType.StatusMessage);
- deviceWatcher.Start();
+ deviceWatcherHelper.StartWatcher(deviceWatcher);
stopWatcherButton.IsEnabled = true;
stopWatcherButton.Focus(FocusState.Keyboard);
aqsFilterTextBox.IsEnabled = true;
@@ -174,23 +82,7 @@ private void StopWatcher()
aqsFilterTextBox.IsEnabled = false;
stopWatcherButton.IsEnabled = false;
- if (null != deviceWatcher)
- {
- // First unhook all event handlers except the stopped handler. This ensures our
- // event handlers don't get called after stop, as stop won't block for any "in flight"
- // event handler calls. We leave the stopped handler as it's guaranteed to only be called
- // once and we'll use it to know when the query is completely stopped.
- deviceWatcher.Added -= handlerAdded;
- deviceWatcher.Updated -= handlerUpdated;
- deviceWatcher.Removed -= handlerRemoved;
- deviceWatcher.EnumerationCompleted -= handlerEnumCompleted;
-
- if (DeviceWatcherStatus.Started == deviceWatcher.Status ||
- DeviceWatcherStatus.EnumerationCompleted == deviceWatcher.Status)
- {
- deviceWatcher.Stop();
- }
- }
+ deviceWatcherHelper.StopWatcher();
startWatcherButton.IsEnabled = true;
startWatcherButton.Focus(FocusState.Keyboard);
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario7_DeviceInformationKind.xaml b/Samples/DeviceEnumerationAndPairing/cs/Scenario7_DeviceInformationKind.xaml
deleted file mode 100644
index 2c482b0c97..0000000000
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario7_DeviceInformationKind.xaml
+++ /dev/null
@@ -1,101 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- This scenario demonstrates requesting various DeviceInformationKinds. Methods without the
- DeviceInformationKind parameter default to DeviceInterface
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario7_DeviceInformationKind.xaml.cs b/Samples/DeviceEnumerationAndPairing/cs/Scenario7_DeviceInformationKind.xaml.cs
index 4d5bcf488a..3daa3aec28 100644
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario7_DeviceInformationKind.xaml.cs
+++ b/Samples/DeviceEnumerationAndPairing/cs/Scenario7_DeviceInformationKind.xaml.cs
@@ -9,136 +9,54 @@
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
-using SDKTemplate;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
-namespace DeviceEnumeration
+namespace SDKTemplate
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class Scenario7 : Page
{
- private MainPage rootPage;
+ private MainPage rootPage = MainPage.Current;
- private List deviceWatchers = null;
- private TypedEventHandler handlerAdded = null;
- private TypedEventHandler handlerUpdated = null;
- private TypedEventHandler handlerRemoved = null;
- private TypedEventHandler handlerEnumCompleted = null;
- private TypedEventHandler handlerStopped = null;
+ private List deviceWatcherHelpers = new List();
- public ObservableCollection ResultCollection
- {
- get;
- private set;
- }
+ private ObservableCollection resultCollection = new ObservableCollection();
public Scenario7()
{
this.InitializeComponent();
- deviceWatchers = new List();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
- rootPage = MainPage.Current;
- ResultCollection = new ObservableCollection();
+ resultsListView.ItemsSource = resultCollection;
- kindComboBox.DataContext = DeviceInformationKindChoices.Choices;
+ kindComboBox.ItemsSource = DeviceInformationKindChoices.Choices;
kindComboBox.SelectedIndex = 0;
-
- DataContext = this;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
- StopWatcher();
+ StopWatchers(/* reset */ true);
}
private void StartWatcherButton_Click(object sender, RoutedEventArgs e)
{
- StartWatcher();
+ StartWatchers();
}
private void StopWatcherButton_Click(object sender, RoutedEventArgs e)
{
- StopWatcher();
+ StopWatchers();
}
- private void StartWatcher()
+ private void StartWatchers()
{
startWatcherButton.IsEnabled = false;
- ResultCollection.Clear();
- deviceWatchers.Clear();
-
- // Create all the event handlers
-
- handlerAdded = new TypedEventHandler(async (watcher, deviceInfo) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));
-
- UpdateStatusText();
- });
- });
-
- handlerUpdated = new TypedEventHandler(async (watcher, deviceInfoUpdate) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- // Find the corresponding updated DeviceInformation in the collection and pass the update object
- // to the Update method of the existing DeviceInformation. This automatically updates the object
- // for us.
- foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
- {
- if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
- {
- deviceInfoDisp.Update(deviceInfoUpdate);
- break;
- }
- }
- });
- });
-
- handlerRemoved = new TypedEventHandler(async (watcher, deviceInfoUpdate) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- // Find the corresponding DeviceInformation in the collection and remove it
- foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
- {
- if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
- {
- ResultCollection.Remove(deviceInfoDisp);
- break;
- }
- }
-
- UpdateStatusText();
- });
- });
-
- handlerEnumCompleted = new TypedEventHandler(async (watcher, obj) =>
- {
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- UpdateStatusText();
- });
- });
-
- handlerStopped = new TypedEventHandler(async (watcher, obj) =>
- {
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- UpdateStatusText();
- });
- });
+ resultCollection.Clear();
// Create a watcher for each DeviceInformationKind selected by the user
foreach (DeviceInformationKind deviceInfoKind in ((DeviceInformationKindChoice)kindComboBox.SelectedItem).DeviceInformationKinds)
@@ -148,73 +66,51 @@ await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
null, // requested properties
deviceInfoKind);
- deviceWatchers.Add(deviceWatcher);
-
- // Hook up handlers for the watcher events before starting the watcher
+ DeviceWatcherHelper deviceWatcherHelper = new DeviceWatcherHelper(resultCollection, Dispatcher);
+ deviceWatcherHelper.UpdateStatus = false; // we will show our own status messages
+ deviceWatcherHelper.DeviceChanged += OnDeviceListChanged;
+ deviceWatcherHelpers.Add(deviceWatcherHelper);
- deviceWatcher.Added += handlerAdded;
- deviceWatcher.Updated += handlerUpdated;
- deviceWatcher.Removed += handlerRemoved;
- deviceWatcher.EnumerationCompleted += handlerEnumCompleted;
- deviceWatcher.Stopped += handlerStopped;
-
- deviceWatcher.Start();
+ deviceWatcherHelper.StartWatcher(deviceWatcher);
}
stopWatcherButton.IsEnabled = true;
stopWatcherButton.Focus(FocusState.Keyboard);
}
- private void StopWatcher()
+ private void StopWatchers(bool reset = false)
{
stopWatcherButton.IsEnabled = false;
- foreach (DeviceWatcher deviceWatcher in deviceWatchers)
+ foreach (DeviceWatcherHelper deviceWatcherHelper in deviceWatcherHelpers)
{
- // First unhook all event handlers except the stopped handler. This ensures our
- // event handlers don't get called after stop, as stop won't block for any "in flight"
- // event handler calls. We leave the stopped handler as it's guaranteed to only be called
- // once and we'll use it to know when the query is completely stopped.
- deviceWatcher.Added -= handlerAdded;
- deviceWatcher.Updated -= handlerUpdated;
- deviceWatcher.Removed -= handlerRemoved;
- deviceWatcher.EnumerationCompleted -= handlerEnumCompleted;
-
- if (DeviceWatcherStatus.Started == deviceWatcher.Status ||
- DeviceWatcherStatus.EnumerationCompleted == deviceWatcher.Status)
+ deviceWatcherHelper.StopWatcher();
+ if (reset)
{
- deviceWatcher.Stop();
+ deviceWatcherHelper.Reset();
}
}
+ deviceWatcherHelpers.Clear();
startWatcherButton.IsEnabled = true;
startWatcherButton.Focus(FocusState.Keyboard);
}
- public void UpdateStatusText()
+ private void OnDeviceListChanged(DeviceWatcher sender, string id)
{
int watchersRunning = 0;
- string statusTxt = null;
// Count running watchers
- foreach (DeviceWatcher deviceWatcher in deviceWatchers)
+ foreach (DeviceWatcherHelper deviceWatcherHelper in deviceWatcherHelpers)
{
- if (deviceWatcher.Status == DeviceWatcherStatus.Started ||
- deviceWatcher.Status == DeviceWatcherStatus.EnumerationCompleted ||
- deviceWatcher.Status == DeviceWatcherStatus.Stopping)
+ if (deviceWatcherHelper.IsWatcherRunning())
{
watchersRunning++;
}
}
- // First add the collective state of the watchers
- statusTxt = String.Format(
- "{0}/{1} Watchers running. {2} devices found.",
- watchersRunning,
- deviceWatchers.Count,
- ResultCollection.Count);
-
- rootPage.NotifyUser(statusTxt, NotifyType.StatusMessage);
+ string message = $"{watchersRunning}/{deviceWatcherHelpers.Count} watchers running. {resultCollection.Count} devices found.";
+ rootPage.NotifyUser(message, NotifyType.StatusMessage);
}
}
}
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario8_PairDevice.xaml b/Samples/DeviceEnumerationAndPairing/cs/Scenario8_PairDevice.xaml
deleted file mode 100644
index b71992312f..0000000000
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario8_PairDevice.xaml
+++ /dev/null
@@ -1,132 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- This scenario demonstrates how to perform basic pairing. Basic pairing allows you to tell Windows which device you want paired, and then Windows will
- handle the ceremony and the UI. If you want to display your own UI and be involved in the pairing ceremony, please see the Custom Pairing scenario.
- This method can be used to pair devices like WiFiDirect, WSD, UPnP, Bluetooth or Bluetooth LE devices.
- Pairing can only be performed on DeviceInformation objects of kind DeviceInformationKind.AssociationEndpoint.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario8_PairDevice.xaml.cs b/Samples/DeviceEnumerationAndPairing/cs/Scenario8_PairDevice.xaml.cs
index 6fd62570b0..e325a54c8b 100644
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario8_PairDevice.xaml.cs
+++ b/Samples/DeviceEnumerationAndPairing/cs/Scenario8_PairDevice.xaml.cs
@@ -8,51 +8,41 @@
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
-using SDKTemplate;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
-namespace DeviceEnumeration
+namespace SDKTemplate
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class Scenario8 : Page
{
- private MainPage rootPage;
+ private MainPage rootPage = MainPage.Current;
- private DeviceWatcher deviceWatcher = null;
- private TypedEventHandler handlerAdded = null;
- private TypedEventHandler handlerUpdated = null;
- private TypedEventHandler handlerRemoved = null;
- private TypedEventHandler handlerEnumCompleted = null;
- private TypedEventHandler handlerStopped = null;
+ private DeviceWatcherHelper deviceWatcherHelper;
- public ObservableCollection ResultCollection
- {
- get;
- private set;
- }
+ private ObservableCollection resultCollection = new ObservableCollection();
public Scenario8()
{
this.InitializeComponent();
+
+ deviceWatcherHelper = new DeviceWatcherHelper(resultCollection, Dispatcher);
+ deviceWatcherHelper.DeviceChanged += OnDeviceListChanged;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
- rootPage = MainPage.Current;
- ResultCollection = new ObservableCollection();
+ resultsListView.ItemsSource = resultCollection;
selectorComboBox.ItemsSource = DeviceSelectorChoices.PairingSelectors;
selectorComboBox.SelectedIndex = 0;
-
- DataContext = this;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
- StopWatcher();
+ deviceWatcherHelper.Reset();
}
private void StartWatcherButton_Click(object sender, RoutedEventArgs e)
@@ -68,14 +58,14 @@ private void StopWatcherButton_Click(object sender, RoutedEventArgs e)
private void StartWatcher()
{
startWatcherButton.IsEnabled = false;
- ResultCollection.Clear();
+ resultCollection.Clear();
- // Get the device selector chosen by the UI then add additional constraints for devices that
+ // Get the device selector chosen by the UI then add additional constraints for devices that
// can be paired or are already paired.
DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;
- //string selector = "(" + deviceSelectorInfo.Selector + ")" + " AND (System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True)";
- string selector = deviceSelectorInfo.Selector;
+ string selector = "(" + deviceSelectorInfo.Selector + ")" + " AND (System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True)";
+ DeviceWatcher deviceWatcher;
if (deviceSelectorInfo.Kind == DeviceInformationKind.Unknown)
{
// Kind will be determined by the selector
@@ -93,121 +83,26 @@ private void StartWatcher()
deviceSelectorInfo.Kind);
}
- // Hook up handlers for the watcher events before starting the watcher
-
- handlerAdded = new TypedEventHandler(async (watcher, deviceInfo) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));
-
- rootPage.NotifyUser(
- String.Format("{0} devices found.", ResultCollection.Count),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.Added += handlerAdded;
-
- handlerUpdated = new TypedEventHandler(async (watcher, deviceInfoUpdate) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- // Find the corresponding updated DeviceInformation in the collection and pass the update object
- // to the Update method of the existing DeviceInformation. This automatically updates the object
- // for us.
- foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
- {
- if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
- {
- deviceInfoDisp.Update(deviceInfoUpdate);
-
- // If the item being updated is currently "selected", then update the pairing buttons
- DeviceInformationDisplay selectedDeviceInfoDisp = (DeviceInformationDisplay)resultsListView.SelectedItem;
- if (deviceInfoDisp == selectedDeviceInfoDisp)
- {
- UpdatePairingButtons();
- }
- break;
- }
- }
- });
- });
- deviceWatcher.Updated += handlerUpdated;
-
- handlerRemoved = new TypedEventHandler(async (watcher, deviceInfoUpdate) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- // Find the corresponding DeviceInformation in the collection and remove it
- foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
- {
- if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
- {
- ResultCollection.Remove(deviceInfoDisp);
- break;
- }
- }
-
- rootPage.NotifyUser(
- String.Format("{0} devices found.", ResultCollection.Count),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.Removed += handlerRemoved;
-
- handlerEnumCompleted = new TypedEventHandler(async (watcher, obj) =>
- {
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- rootPage.NotifyUser(
- String.Format("{0} devices found. Enumeration completed. Watching for updates...", ResultCollection.Count),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.EnumerationCompleted += handlerEnumCompleted;
-
- handlerStopped = new TypedEventHandler(async (watcher, obj) =>
- {
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- rootPage.NotifyUser(
- String.Format("{0} devices found. Watcher {1}.",
- ResultCollection.Count,
- DeviceWatcherStatus.Aborted == watcher.Status ? "aborted" : "stopped"),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.Stopped += handlerStopped;
-
rootPage.NotifyUser("Starting Watcher...", NotifyType.StatusMessage);
- deviceWatcher.Start();
+ deviceWatcherHelper.StartWatcher(deviceWatcher);
stopWatcherButton.IsEnabled = true;
}
+ private void OnDeviceListChanged(DeviceWatcher sender, string id)
+ {
+ // If the item being updated is currently "selected", then update the pairing buttons
+ DeviceInformationDisplay selectedDeviceInfoDisp = (DeviceInformationDisplay)resultsListView.SelectedItem;
+ if ((selectedDeviceInfoDisp != null) && (selectedDeviceInfoDisp.Id == id))
+ {
+ UpdatePairingButtons();
+ }
+ }
+
private void StopWatcher()
{
stopWatcherButton.IsEnabled = false;
- if (null != deviceWatcher)
- {
- // First unhook all event handlers except the stopped handler. This ensures our
- // event handlers don't get called after stop, as stop won't block for any "in flight"
- // event handler calls. We leave the stopped handler as it's guaranteed to only be called
- // once and we'll use it to know when the query is completely stopped.
- deviceWatcher.Added -= handlerAdded;
- deviceWatcher.Updated -= handlerUpdated;
- deviceWatcher.Removed -= handlerRemoved;
- deviceWatcher.EnumerationCompleted -= handlerEnumCompleted;
-
- if (DeviceWatcherStatus.Started == deviceWatcher.Status ||
- DeviceWatcherStatus.EnumerationCompleted == deviceWatcher.Status)
- {
- deviceWatcher.Stop();
- }
- }
+ deviceWatcherHelper.StopWatcher();
startWatcherButton.IsEnabled = true;
}
@@ -224,7 +119,7 @@ private async void PairButton_Click(object sender, RoutedEventArgs e)
DevicePairingResult dpr = await deviceInfoDisp.DeviceInformation.Pairing.PairAsync();
rootPage.NotifyUser(
- "Pairing result = " + dpr.Status.ToString(),
+ "Pairing result = " + dpr.Status.ToString(),
dpr.Status == DevicePairingResultStatus.Paired ? NotifyType.StatusMessage : NotifyType.ErrorMessage);
UpdatePairingButtons();
@@ -239,7 +134,7 @@ private async void UnpairButton_Click(object sender, RoutedEventArgs e)
rootPage.NotifyUser("Unpairing started. Please wait...", NotifyType.StatusMessage);
DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay;
-
+
DeviceUnpairingResult dupr = await deviceInfoDisp.DeviceInformation.Pairing.UnpairAsync();
rootPage.NotifyUser(
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario9_CustomPairDevice.xaml b/Samples/DeviceEnumerationAndPairing/cs/Scenario9_CustomPairDevice.xaml
deleted file mode 100644
index c8c96c0c20..0000000000
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario9_CustomPairDevice.xaml
+++ /dev/null
@@ -1,158 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- This scenario demonstrates how to perform custom pairing. Custom pairing allows your app to be involved in the pairing ceremony and use your on UI.
- If you want Windows to control the ceremony and display system UI, please look at the basic pairing scenario.
- This method can be used to pair devices like WiFiDirect, WSD, UPnP, Bluetooth or Bluetooth LE devices.
- Pairing can only be performed on DeviceInformation objects of kind DeviceInformationKind.AssociationEndpoint.
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cs/Scenario9_CustomPairDevice.xaml.cs b/Samples/DeviceEnumerationAndPairing/cs/Scenario9_CustomPairDevice.xaml.cs
index 8fdfcafa58..2d471758a1 100644
--- a/Samples/DeviceEnumerationAndPairing/cs/Scenario9_CustomPairDevice.xaml.cs
+++ b/Samples/DeviceEnumerationAndPairing/cs/Scenario9_CustomPairDevice.xaml.cs
@@ -5,62 +5,52 @@
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Foundation;
+using Windows.Security.Credentials;
using Windows.UI.Core;
-using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
-using SDKTemplate;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
-namespace DeviceEnumeration
+namespace SDKTemplate
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class Scenario9 : Page
{
- private MainPage rootPage;
-
- private DeviceWatcher deviceWatcher = null;
- private TypedEventHandler handlerAdded = null;
- private TypedEventHandler handlerUpdated = null;
- private TypedEventHandler handlerRemoved = null;
- private TypedEventHandler handlerEnumCompleted = null;
- private TypedEventHandler handlerStopped = null;
-
+ private MainPage rootPage = MainPage.Current;
+
+ private DeviceWatcherHelper deviceWatcherHelper;
+
TaskCompletionSource providePinTaskSrc;
TaskCompletionSource confirmPinTaskSrc;
- public ObservableCollection ResultCollection
- {
- get;
- private set;
- }
+ private ObservableCollection resultCollection = new ObservableCollection();
public Scenario9()
{
this.InitializeComponent();
+
+ deviceWatcherHelper = new DeviceWatcherHelper(resultCollection, Dispatcher);
+ deviceWatcherHelper.DeviceChanged += OnDeviceListChanged;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
- rootPage = MainPage.Current;
- ResultCollection = new ObservableCollection();
+ resultsListView.ItemsSource = resultCollection;
selectorComboBox.ItemsSource = DeviceSelectorChoices.PairingSelectors;
selectorComboBox.SelectedIndex = 0;
protectionLevelComboBox.ItemsSource = ProtectionSelectorChoices.Selectors;
protectionLevelComboBox.SelectedIndex = 0;
-
- DataContext = this;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
- StopWatcher();
+ deviceWatcherHelper.Reset();
}
private void StartWatcherButton_Click(object sender, RoutedEventArgs e)
@@ -76,9 +66,10 @@ private void StopWatcherButton_Click(object sender, RoutedEventArgs e)
private void StartWatcher()
{
startWatcherButton.IsEnabled = false;
- ResultCollection.Clear();
+ resultCollection.Clear();
+ DeviceWatcher deviceWatcher;
- // Get the device selector chosen by the UI then add additional constraints for devices that
+ // Get the device selector chosen by the UI then add additional constraints for devices that
// can be paired or are already paired.
DeviceSelectorInfo deviceSelectorInfo = (DeviceSelectorInfo)selectorComboBox.SelectedItem;
string selector = "(" + deviceSelectorInfo.Selector + ")" + " AND (System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True)";
@@ -100,122 +91,25 @@ private void StartWatcher()
deviceSelectorInfo.Kind);
}
- // Hook up handlers for the watcher events before starting the watcher
-
- handlerAdded = new TypedEventHandler(async (watcher, deviceInfo) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- ResultCollection.Add(new DeviceInformationDisplay(deviceInfo));
-
- rootPage.NotifyUser(
- String.Format("{0} devices found.", ResultCollection.Count),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.Added += handlerAdded;
-
- handlerUpdated = new TypedEventHandler(async (watcher, deviceInfoUpdate) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- // Find the corresponding updated DeviceInformation in the collection and pass the update object
- // to the Update method of the existing DeviceInformation. This automatically updates the object
- // for us.
- foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
- {
- if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
- {
- deviceInfoDisp.Update(deviceInfoUpdate);
-
- // If the item being updated is currently "selected", then update the pairing buttons
- DeviceInformationDisplay selectedDeviceInfoDisp = (DeviceInformationDisplay)resultsListView.SelectedItem;
- if (deviceInfoDisp == selectedDeviceInfoDisp)
- {
- UpdatePairingButtons();
- }
- break;
- }
- }
- });
- });
- deviceWatcher.Updated += handlerUpdated;
-
- handlerRemoved = new TypedEventHandler(async (watcher, deviceInfoUpdate) =>
- {
- // Since we have the collection databound to a UI element, we need to update the collection on the UI thread.
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- // Find the corresponding DeviceInformation in the collection and remove it
- foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection)
- {
- if (deviceInfoDisp.Id == deviceInfoUpdate.Id)
- {
- ResultCollection.Remove(deviceInfoDisp);
- break;
- }
- }
-
- rootPage.NotifyUser(
- String.Format("{0} devices found.", ResultCollection.Count),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.Removed += handlerRemoved;
-
- handlerEnumCompleted = new TypedEventHandler(async (watcher, obj) =>
- {
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- rootPage.NotifyUser(
- String.Format("{0} devices found. Enumeration completed. Watching for updates...", ResultCollection.Count),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.EnumerationCompleted += handlerEnumCompleted;
-
- handlerStopped = new TypedEventHandler(async (watcher, obj) =>
- {
- await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
- {
- rootPage.NotifyUser(
- String.Format("{0} devices found. Watcher {1}.",
- ResultCollection.Count,
- DeviceWatcherStatus.Aborted == watcher.Status ? "aborted" : "stopped"),
- NotifyType.StatusMessage);
- });
- });
- deviceWatcher.Stopped += handlerStopped;
-
rootPage.NotifyUser("Starting Watcher...", NotifyType.StatusMessage);
- deviceWatcher.Start();
+ deviceWatcherHelper.StartWatcher(deviceWatcher);
stopWatcherButton.IsEnabled = true;
}
- private void StopWatcher()
+ private void OnDeviceListChanged(DeviceWatcher sender, string id)
{
- stopWatcherButton.IsEnabled = false;
-
- if (null != deviceWatcher)
+ // If the item being updated is currently "selected", then update the pairing buttons
+ DeviceInformationDisplay selectedDeviceInfoDisp = (DeviceInformationDisplay)resultsListView.SelectedItem;
+ if ((selectedDeviceInfoDisp != null) && (selectedDeviceInfoDisp.Id == id))
{
- // First unhook all event handlers except the stopped handler. This ensures our
- // event handlers don't get called after stop, as stop won't block for any "in flight"
- // event handler calls. We leave the stopped handler as it's guaranteed to only be called
- // once and we'll use it to know when the query is completely stopped.
- deviceWatcher.Added -= handlerAdded;
- deviceWatcher.Updated -= handlerUpdated;
- deviceWatcher.Removed -= handlerRemoved;
- deviceWatcher.EnumerationCompleted -= handlerEnumCompleted;
-
- if (DeviceWatcherStatus.Started == deviceWatcher.Status ||
- DeviceWatcherStatus.EnumerationCompleted == deviceWatcher.Status)
- {
- deviceWatcher.Stop();
- }
+ UpdatePairingButtons();
}
+ }
+ private void StopWatcher()
+ {
+ stopWatcherButton.IsEnabled = false;
+ deviceWatcherHelper.StopWatcher();
startWatcherButton.IsEnabled = true;
}
@@ -297,7 +191,7 @@ await rootPage.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
break;
case DevicePairingKinds.ProvidePin:
- // A PIN may be shown on the target device and the user needs to enter the matching PIN on
+ // A PIN may be shown on the target device and the user needs to enter the matching PIN on
// this Windows device. Get a deferral so we can perform the async request to the user.
var collectPinDeferral = args.GetDeferral();
diff --git a/Samples/DeviceEnumerationAndPairing/js/js/sample-configuration.js b/Samples/DeviceEnumerationAndPairing/js/js/sample-configuration.js
index 868551007e..16a370dc72 100644
--- a/Samples/DeviceEnumerationAndPairing/js/js/sample-configuration.js
+++ b/Samples/DeviceEnumerationAndPairing/js/js/sample-configuration.js
@@ -2,6 +2,7 @@
(function () {
"use strict";
+ var DevEnum = Windows.Devices.Enumeration;
var sampleTitle = "Device Enumeration and Pairing JS Sample";
@@ -17,8 +18,147 @@
{ url: "/html/scenario9_custompairdevice.html", title: "Custom Device Pairing" }
];
+ ///
+ /// Updates a WinJS.Binding.List based on events from a DeviceWatcher.
+ ///
+ ///
+ /// Encapsulates the work necessary to register for watcher events,
+ /// start and stop the watcher, handle race conditions, and break cycles.
+ ///
+
+ class DeviceWatcherHelper {
+ constructor(resultCollection) {
+ this._resultCollection = resultCollection;
+ this._deviceWatcher = null;
+ this.updateStatus = true;
+ }
+
+ startWatcher(deviceWatcher) {
+ this._deviceWatcher = deviceWatcher;
+
+ // Connect events to update our collection as the watcher report results.
+ deviceWatcher.addEventListener("added", DeviceWatcherHelper._onDeviceAdded.bind(this));
+ deviceWatcher.addEventListener("updated", DeviceWatcherHelper._onDeviceUpdated.bind(this));
+ deviceWatcher.addEventListener("removed", DeviceWatcherHelper._onDeviceRemoved.bind(this));
+ deviceWatcher.addEventListener("enumerationcompleted", DeviceWatcherHelper._onEnumerationCompleted.bind(this));
+ deviceWatcher.addEventListener("stopped", DeviceWatcherHelper._onStopped.bind(this));
+
+ deviceWatcher.start();
+ }
+
+ stopWatcher() {
+ // Since the device watcher runs in the background, it is possible that
+ // a notification is "in flight" at the time we stop the watcher.
+ // In other words, it is possible for the watcher to become stopped while a
+ // handler is running, or for a handler to run after the watcher has stopped.
+
+ if (DeviceWatcherHelper.isWatcherStarted(this._deviceWatcher)) {
+ // We do not null out the deviceWatcher yet because we want to receive
+ // the Stopped event.
+ this._deviceWatcher.stop();
+ }
+ }
+
+ reset() {
+ if (this._deviceWatcher) {
+ this.stopWatcher();
+ this._deviceWatcher = null;
+ }
+ }
+
+ static isWatcherStarted(watcher) {
+ return (watcher.status === DevEnum.DeviceWatcherStatus.started) ||
+ (watcher.status === DevEnum.DeviceWatcherStatus.enumerationCompleted);
+ }
+
+ static _onDeviceAdded(deviceInfo) {
+ var sender = deviceInfo.target;
+
+ // Watcher may have stopped while we were waiting for our chance to run.
+ if (DeviceWatcherHelper.isWatcherStarted(sender)) {
+
+ // For simplicity, just creating a new "display object" on the fly since databinding directly with deviceInfo from
+ // the callback doesn't work.
+ this._resultCollection.push(new DisplayHelpers.DeviceInformationDisplay(deviceInfo));
+ this._raiseDeviceChanged(sender, deviceInfo.id);
+ }
+ }
+
+ static _onDeviceUpdated(deviceInfoUpdate) {
+ var sender = deviceInfoUpdate.target;
+
+ // Watcher may have stopped while we were waiting for our chance to run.
+ if (DeviceWatcherHelper.isWatcherStarted(sender)) {
+
+ // Find the corresponding updated DeviceInformation in the collection and pass the update object
+ // to the Update method of the existing DeviceInformation. This automatically updates the object
+ // for us.
+ this._resultCollection.forEach(value => {
+ if (value.id === deviceInfoUpdate.id) {
+ value.update(deviceInfoUpdate);
+ this._raiseDeviceChanged(sender, deviceInfoUpdate.id);
+ }
+ });
+ }
+ }
+
+ static _onDeviceRemoved(deviceInfoUpdate) {
+ var sender = deviceInfoUpdate.target;
+
+ // Watcher may have stopped while we were waiting for our chance to run.
+ if (DeviceWatcherHelper.isWatcherStarted(sender)) {
+ for (var i = 0; this._resultCollection.length; i++) {
+ if (this._resultCollection.getAt(i).id == deviceInfoUpdate.id) {
+ this._resultCollection.splice(i, 1);
+ this._raiseDeviceChanged(sender, deviceInfoUpdate.id);
+ break;
+ }
+ }
+ }
+ }
+
+ static _onEnumerationCompleted(e) {
+ this._raiseDeviceChanged(e.target, "");
+ }
+
+ static _onStopped(e) {
+ this._raiseDeviceChanged(e.target, "");
+ }
+
+ _raiseDeviceChanged(sender, id) {
+ if (this.updateStatus) {
+ // Display a default status message.
+ var message = "";
+ switch (sender.status) {
+ case DevEnum.DeviceWatcherStatus.started:
+ message = `${this._resultCollection.length} devices found.`;
+ break;
+
+ case DevEnum.DeviceWatcherStatus.enumerationCompleted:
+ message = `${this._resultCollection.length} devices found. Enumeration completed. Watching for updates...`;
+ break;
+
+ case DevEnum.DeviceWatcherStatus.stopped:
+ message = `${this._resultCollection.length} devices found. Watcher stopped.`;
+ break;
+
+ case DevEnum.DeviceWatcherStatus.aborted:
+ message = `${this._resultCollection.length} devices found. Watcher aborted.`;
+ break;
+ }
+
+ if (message) {
+ WinJS.log && WinJS.log(message, "sample", "status");
+ }
+ }
+
+ this._resultCollection.dispatchEvent("deviceupdated", { sender: sender, id: id });
+ }
+ }
+
WinJS.Namespace.define("SdkSample", {
sampleTitle: sampleTitle,
- scenarios: new WinJS.Binding.List(scenarios)
+ scenarios: new WinJS.Binding.List(scenarios),
+ DeviceWatcherHelper: DeviceWatcherHelper
});
})();
\ No newline at end of file
diff --git a/Samples/DeviceEnumerationAndPairing/js/js/scenario1_devicepicker.js b/Samples/DeviceEnumerationAndPairing/js/js/scenario1_devicepicker.js
index 729d7d2ac4..67074a251b 100644
--- a/Samples/DeviceEnumerationAndPairing/js/js/scenario1_devicepicker.js
+++ b/Samples/DeviceEnumerationAndPairing/js/js/scenario1_devicepicker.js
@@ -4,16 +4,12 @@
"use strict";
var DevEnum = Windows.Devices.Enumeration;
- var devicePicker = null;
var resultCollection = new WinJS.Binding.List([]);
var resultsListView;
var page = WinJS.UI.Pages.define("/html/scenario1_devicepicker.html", {
ready: function (element, options) {
- // Setup beforeNavigate event
- WinJS.Navigation.addEventListener("beforenavigate", onLeavingPage);
-
// Hook up button event handlers
document.getElementById("pickSingleDeviceButton").addEventListener("click", pickSingleDeviceClick, false);
document.getElementById("showDevicePickerButton").addEventListener("click", showDevicePickerClick, false);
@@ -31,14 +27,12 @@
// Process any data bindings
WinJS.UI.processAll();
+ },
+ unload: function () {
+ resultCollection.splice(0, resultCollection.length);
}
});
- function onLeavingPage() {
- WinJS.Navigation.removeEventListener("beforenavigate", onLeavingPage);
- resultCollection.splice(0, resultCollection.length);
- }
-
function pickSingleDeviceClick() {
showDevicePicker(true);
}
@@ -52,7 +46,7 @@
showDevicePickerButton.disabled = true;
resultCollection.splice(0, resultCollection.length);
- devicePicker = new DevEnum.DevicePicker();
+ var devicePicker = new DevEnum.DevicePicker();
var selectedItem = DisplayHelpers.devicePickerSelectors.getAt(selectorComboBox.selectedIndex);
@@ -99,8 +93,7 @@
}
function onDeviceSelected(args) {
- resultCollection.splice(0, resultCollection.length);
- resultCollection.push(new DisplayHelpers.DeviceInformationDisplay(args.selectedDevice));
+ resultCollection.splice(0, resultCollection.length, new DisplayHelpers.DeviceInformationDisplay(args.selectedDevice));
}
})();
diff --git a/Samples/DeviceEnumerationAndPairing/js/js/scenario2_devicewatcher.js b/Samples/DeviceEnumerationAndPairing/js/js/scenario2_devicewatcher.js
index f99507ffb6..fd683a59ea 100644
--- a/Samples/DeviceEnumerationAndPairing/js/js/scenario2_devicewatcher.js
+++ b/Samples/DeviceEnumerationAndPairing/js/js/scenario2_devicewatcher.js
@@ -4,16 +4,13 @@
"use strict";
var DevEnum = Windows.Devices.Enumeration;
- var deviceWatcher = null;
var resultCollection = new WinJS.Binding.List([]);
var resultsListView;
+ var deviceWatcherHelper = new SdkSample.DeviceWatcherHelper(resultCollection);
var page = WinJS.UI.Pages.define("/html/scenario2_devicewatcher.html", {
ready: function (element, options) {
- // Setup beforeNavigate event
- WinJS.Navigation.addEventListener("beforenavigate", onLeavingPage);
-
// Hook up button event handlers
document.getElementById("startWatcherButton").addEventListener("click", startWatcher, false);
document.getElementById("stopWatcherButton").addEventListener("click", stopWatcher, false);
@@ -31,15 +28,13 @@
// Process any data bindings
WinJS.UI.processAll();
+ },
+ unload: function () {
+ deviceWatcherHelper.reset();
+ resultCollection.splice(0, resultCollection.length);
}
});
- function onLeavingPage() {
- stopWatcher();
- WinJS.Navigation.removeEventListener("beforenavigate", onLeavingPage);
- resultCollection.splice(0, resultCollection.length);
- }
-
function startWatcher() {
startWatcherButton.disabled = true;
resultCollection.splice(0, resultCollection.length);
@@ -47,11 +42,12 @@
// First get the device selector chosen by the UI.
var selectedItem = DisplayHelpers.deviceWatcherSelectors.getAt(selectorComboBox.selectedIndex);
- if (null != selectedItem.deviceClassSelector) {
- // If the a pre-canned device class selector was chosen, call the DeviceClass overloa
+ var deviceWatcher;
+ if (undefined !== selectedItem.deviceClassSelector) {
+ // If the a pre-canned device class selector was chosen, call the DeviceClass overload
deviceWatcher = DevEnum.DeviceInformation.createWatcher(selectedItem.deviceClassSelector);
}
- else if (selectedItem.kind == DevEnum.DeviceInformationKind.unknown){
+ else if (selectedItem.kind === DevEnum.DeviceInformationKind.unknown) {
// Use AQS string selector from dynamic call to a device api's GetDeviceSelector call
// Kind will be determined by the selector
deviceWatcher = DevEnum.DeviceInformation.createWatcher(
@@ -67,80 +63,14 @@
selectedItem.kind);
}
- // Add event handlers
- deviceWatcher.addEventListener("added", onAdded);
- deviceWatcher.addEventListener("updated", onUpdated);
- deviceWatcher.addEventListener("removed", onRemoved);
- deviceWatcher.addEventListener("enumerationcompleted", onEnumerationCompleted);
- deviceWatcher.addEventListener("stopped", onStopped);
-
WinJS.log && WinJS.log("Starting watcher...", "sample", "status");
- deviceWatcher.start();
+ deviceWatcherHelper.startWatcher(deviceWatcher);
stopWatcherButton.disabled = false;
}
function stopWatcher() {
-
stopWatcherButton.disabled = true;
-
- if (null != deviceWatcher) {
-
- // First unhook all event handlers except the stopped handler. This ensures our
- // event handlers don't get called after stop, as stop won't block for any "in flight"
- // event handler calls. We leave the stopped handler as it's guaranteed to only be called
- // once and we'll use it to know when the query is completely stopped.
- deviceWatcher.removeEventListener("added", onAdded);
- deviceWatcher.removeEventListener("updated", onUpdated);
- deviceWatcher.removeEventListener("removed", onRemoved);
- deviceWatcher.removeEventListener("enumerationcompleted", onEnumerationCompleted);
-
- if (DevEnum.DeviceWatcherStatus.started == deviceWatcher.status ||
- DevEnum.DeviceWatcherStatus.enumerationCompleted == deviceWatcher.status) {
- deviceWatcher.stop();
- }
- }
-
+ deviceWatcherHelper.stopWatcher();
startWatcherButton.disabled = false;
}
-
- function onAdded(deviceInfo) {
- // For simplicity, just creating a new "display object" on the fly since databinding directly with deviceInfo from
- // the callback doesn't work.
- resultCollection.push(new DisplayHelpers.DeviceInformationDisplay(deviceInfo));
-
- if (deviceWatcher.status == DevEnum.DeviceWatcherStatus.enumerationCompleted) {
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Watching for updates...", "sample", "status");
- }
- }
-
- function onUpdated(deviceInfoUpdate) {
- // Find the corresponding updated DeviceInformation in the collection and pass the update object
- // to the Update method of the existing DeviceInformation. This automatically updates the object
- // for us.
- resultCollection.forEach(function (value, index, array) {
- if (value.id == deviceInfoUpdate.id) {
- value.update(deviceInfoUpdate);
- }
- });
- }
-
- function onRemoved(deviceInfoUpdate) {
- for (var i = 0; resultCollection.length; i++) {
- if (resultCollection.getAt(i).id == deviceInfoUpdate.id) {
- resultCollection.splice(i, 1);
- break;
- }
- }
-
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Watching for updates...", "sample", "status");
- }
-
- function onEnumerationCompleted(obj) {
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Enumeration completed. Watching for updates...", "sample", "status");
- }
-
- function onStopped(obj) {
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Watcher stopped", "sample", "status");
- }
-
})();
diff --git a/Samples/DeviceEnumerationAndPairing/js/js/scenario3_backgrounddevicewatcher.js b/Samples/DeviceEnumerationAndPairing/js/js/scenario3_backgrounddevicewatcher.js
index 1feb3832d5..382cc6a700 100644
--- a/Samples/DeviceEnumerationAndPairing/js/js/scenario3_backgrounddevicewatcher.js
+++ b/Samples/DeviceEnumerationAndPairing/js/js/scenario3_backgrounddevicewatcher.js
@@ -40,6 +40,12 @@
iter.moveNext();
}
+ },
+ unload: function () {
+ if (backgroundTaskRegistration) {
+ backgroundTaskRegistration.removeEventListener("completed", onCompleted);
+ backgroundTaskRegistration = null;
+ }
}
});
@@ -115,7 +121,7 @@
taskBuilder.setTrigger(deviceWatcherTrigger);
backgroundTaskRegistration = taskBuilder.register();
- backgroundTaskRegistration.addEventListener("completed", onCompleted)
+ backgroundTaskRegistration.addEventListener("completed", onCompleted);
}
function onCompleted(args) {
diff --git a/Samples/DeviceEnumerationAndPairing/js/js/scenario4_snapshot.js b/Samples/DeviceEnumerationAndPairing/js/js/scenario4_snapshot.js
index 51e8747d14..c71e8bf25b 100644
--- a/Samples/DeviceEnumerationAndPairing/js/js/scenario4_snapshot.js
+++ b/Samples/DeviceEnumerationAndPairing/js/js/scenario4_snapshot.js
@@ -10,9 +10,6 @@
var page = WinJS.UI.Pages.define("/html/scenario4_snapshot.html", {
ready: function (element, options) {
- // Setup beforeNavigate event
- WinJS.Navigation.addEventListener("beforenavigate", onLeavingPage);
-
// Hook up button event handlers
document.getElementById("findButton").addEventListener("click", findButtonClick, false);
@@ -29,14 +26,12 @@
// Process any data bindings
WinJS.UI.processAll();
+ },
+ unload: function () {
+ resultCollection.splice(0, resultCollection.length);
}
});
- function onLeavingPage() {
- WinJS.Navigation.removeEventListener("beforenavigate", onLeavingPage);
- resultCollection.splice(0, resultCollection.length);
- }
-
function findButtonClick() {
var deviceInfoCollection = null;
diff --git a/Samples/DeviceEnumerationAndPairing/js/js/scenario5_getsingledevice.js b/Samples/DeviceEnumerationAndPairing/js/js/scenario5_getsingledevice.js
index 6519a5b228..561592403f 100644
--- a/Samples/DeviceEnumerationAndPairing/js/js/scenario5_getsingledevice.js
+++ b/Samples/DeviceEnumerationAndPairing/js/js/scenario5_getsingledevice.js
@@ -11,9 +11,6 @@
var page = WinJS.UI.Pages.define("/html/scenario5_getsingledevice.html", {
ready: function (element, options) {
- // Setup beforeNavigate event
- WinJS.Navigation.addEventListener("beforenavigate", onLeavingPage);
-
// Hook up button event handlers
document.getElementById("getButton").addEventListener("click", getButtonClick, false);
@@ -21,6 +18,9 @@
resultsListView = element.querySelector("#resultsListView").winControl;
resultsListView.itemDataSource = resultCollection.dataSource;
+ // Capture this in case the user navigates before the findAllAsync completes.
+ var interfaceIdTextBox = document.getElementById("interfaceIdTextBox");
+
// Pre-populate the interface id input box with something valid.
DevEnum.DeviceInformation.findAllAsync(DevEnum.DeviceClass.audioRender).done(
function (deviceInfoCollection) {
@@ -34,14 +34,12 @@
// Process any data bindings
WinJS.UI.processAll();
+ },
+ unload: function () {
+ resultCollection.splice(0, resultCollection.length);
}
});
- function onLeavingPage() {
- WinJS.Navigation.removeEventListener("beforenavigate", onLeavingPage);
- resultCollection.splice(0, resultCollection.length);
- }
-
function getButtonClick() {
resultCollection.splice(0, resultCollection.length);
diff --git a/Samples/DeviceEnumerationAndPairing/js/js/scenario6_customfilteraddedprops.js b/Samples/DeviceEnumerationAndPairing/js/js/scenario6_customfilteraddedprops.js
index c04addb241..c3ceafc75e 100644
--- a/Samples/DeviceEnumerationAndPairing/js/js/scenario6_customfilteraddedprops.js
+++ b/Samples/DeviceEnumerationAndPairing/js/js/scenario6_customfilteraddedprops.js
@@ -4,16 +4,13 @@
"use strict";
var DevEnum = Windows.Devices.Enumeration;
- var deviceWatcher = null;
var resultCollection = new WinJS.Binding.List([]);
var resultsListView;
+ var deviceWatcherHelper = new SdkSample.DeviceWatcherHelper(resultCollection);
var page = WinJS.UI.Pages.define("/html/scenario6_customfilteraddedprops.html", {
ready: function (element, options) {
- // Setup beforeNavigate event
- WinJS.Navigation.addEventListener("beforenavigate", onLeavingPage);
-
// Hook up button event handlers
document.getElementById("startWatcherButton").addEventListener("click", startWatcher, false);
document.getElementById("stopWatcherButton").addEventListener("click", stopWatcher, false);
@@ -24,15 +21,13 @@
// Process any data bindings
WinJS.UI.processAll();
+ },
+ unload: function () {
+ deviceWatcherHelper.reset();
+ resultCollection.splice(0, resultCollection.length);
}
});
- function onLeavingPage() {
- stopWatcher();
- WinJS.Navigation.removeEventListener("beforenavigate", onLeavingPage);
- resultCollection.splice(0, resultCollection.length);
- }
-
function startWatcher() {
startWatcherButton.disabled = true;
resultCollection.splice(0, resultCollection.length);
@@ -42,54 +37,31 @@
"System.ItemNameDisplay" // This is the property that's behind DeviceInformation.name
];
- deviceWatcher = DevEnum.DeviceInformation.createWatcher(
+ var deviceWatcher = DevEnum.DeviceInformation.createWatcher(
aqsFilterTextBox.value,
requestedProperties
);
- // Add event handlers
- deviceWatcher.addEventListener("added", onAdded);
- deviceWatcher.addEventListener("updated", onUpdated);
- deviceWatcher.addEventListener("removed", onRemoved);
- deviceWatcher.addEventListener("enumerationcompleted", onEnumerationCompleted);
- deviceWatcher.addEventListener("stopped", onStopped);
-
WinJS.log && WinJS.log("Starting watcher...", "sample", "status");
- deviceWatcher.start();
+ deviceWatcherHelper.startWatcher(deviceWatcher);
stopWatcherButton.disabled = false;
}
function stopWatcher() {
-
stopWatcherButton.disabled = true;
-
- if (null != deviceWatcher) {
-
- // First unhook all event handlers except the stopped handler. This ensures our
- // event handlers don't get called after stop, as stop won't block for any "in flight"
- // event handler calls. We leave the stopped handler as it's guaranteed to only be called
- // once and we'll use it to know when the query is completely stopped.
- deviceWatcher.removeEventListener("added", onAdded);
- deviceWatcher.removeEventListener("updated", onUpdated);
- deviceWatcher.removeEventListener("removed", onRemoved);
- deviceWatcher.removeEventListener("enumerationcompleted", onEnumerationCompleted);
-
- if (DevEnum.DeviceWatcherStatus.started == deviceWatcher.status ||
- DevEnum.DeviceWatcherStatus.enumerationCompleted == deviceWatcher.status) {
- deviceWatcher.stop();
- }
- }
-
+ deviceWatcherHelper.stopWatcher();
startWatcherButton.disabled = false;
}
+ //xx
function onAdded(deviceInfo) {
// For simplicity, just creating a new "display object" on the fly since databinding directly with deviceInfo from
// the callback doesn't work.
resultCollection.push(new DisplayHelpers.DeviceInformationDisplay(deviceInfo));
- if (deviceWatcher.status == DevEnum.DeviceWatcherStatus.enumerationCompleted) {
+ var watcher = deviceInfo.target;
+ if (watcher.status == DevEnum.DeviceWatcherStatus.enumerationCompleted) {
WinJS.log && WinJS.log(resultCollection.length + " devices found. Watching for updates...", "sample", "status");
}
}
diff --git a/Samples/DeviceEnumerationAndPairing/js/js/scenario7_deviceinformationkind.js b/Samples/DeviceEnumerationAndPairing/js/js/scenario7_deviceinformationkind.js
index e4d19be007..967598970d 100644
--- a/Samples/DeviceEnumerationAndPairing/js/js/scenario7_deviceinformationkind.js
+++ b/Samples/DeviceEnumerationAndPairing/js/js/scenario7_deviceinformationkind.js
@@ -4,16 +4,13 @@
"use strict";
var DevEnum = Windows.Devices.Enumeration;
- var deviceWatcher = null;
var resultCollection = new WinJS.Binding.List([]);
var resultsListView;
+ var deviceWatcherHelper = new SdkSample.DeviceWatcherHelper(resultCollection);
var page = WinJS.UI.Pages.define("/html/scenario7_deviceinformationkind.html", {
ready: function (element, options) {
- // Setup beforeNavigate event
- WinJS.Navigation.addEventListener("beforenavigate", onLeavingPage);
-
// Hook up button event handlers
document.getElementById("startWatcherButton").addEventListener("click", startWatcher, false);
document.getElementById("stopWatcherButton").addEventListener("click", stopWatcher, false);
@@ -31,100 +28,32 @@
// Process any data bindings
WinJS.UI.processAll();
+ },
+ unload: function () {
+ deviceWatcherHelper.reset();
+ resultCollection.splice(0, resultCollection.length);
}
});
- function onLeavingPage() {
- stopWatcher();
- WinJS.Navigation.removeEventListener("beforenavigate", onLeavingPage);
- resultCollection.splice(0, resultCollection.length);
- }
-
function startWatcher() {
startWatcherButton.disabled = true;
resultCollection.splice(0, resultCollection.length);
var selectedItem = DisplayHelpers.kindList.getAt(kindComboBox.selectedIndex);
- deviceWatcher = DevEnum.DeviceInformation.createWatcher(
+ var deviceWatcher = DevEnum.DeviceInformation.createWatcher(
"", // No filter
null, // No requested properties
selectedItem.deviceInformationKind);
- // Add event handlers
- deviceWatcher.addEventListener("added", onAdded);
- deviceWatcher.addEventListener("updated", onUpdated);
- deviceWatcher.addEventListener("removed", onRemoved);
- deviceWatcher.addEventListener("enumerationcompleted", onEnumerationCompleted);
- deviceWatcher.addEventListener("stopped", onStopped);
-
WinJS.log && WinJS.log("Starting watcher...", "sample", "status");
- deviceWatcher.start();
+ deviceWatcherHelper.startWatcher(deviceWatcher);
stopWatcherButton.disabled = false;
}
function stopWatcher() {
-
stopWatcherButton.disabled = true;
-
- if (null != deviceWatcher) {
-
- // First unhook all event handlers except the stopped handler. This ensures our
- // event handlers don't get called after stop, as stop won't block for any "in flight"
- // event handler calls. We leave the stopped handler as it's guaranteed to only be called
- // once and we'll use it to know when the query is completely stopped.
- deviceWatcher.removeEventListener("added", onAdded);
- deviceWatcher.removeEventListener("updated", onUpdated);
- deviceWatcher.removeEventListener("removed", onRemoved);
- deviceWatcher.removeEventListener("enumerationcompleted", onEnumerationCompleted);
-
- if (DevEnum.DeviceWatcherStatus.started == deviceWatcher.status ||
- DevEnum.DeviceWatcherStatus.enumerationCompleted == deviceWatcher.status) {
- deviceWatcher.stop();
- }
- }
-
+ deviceWatcherHelper.stopWatcher();
startWatcherButton.disabled = false;
}
-
- function onAdded(deviceInfo) {
- // For simplicity, just creating a new "display object" on the fly since databinding directly with deviceInfo from
- // the callback doesn't work.
- resultCollection.push(new DisplayHelpers.DeviceInformationDisplay(deviceInfo));
-
- if (deviceWatcher.status == DevEnum.DeviceWatcherStatus.enumerationCompleted) {
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Watching for updates...", "sample", "status");
- }
- }
-
- function onUpdated(deviceInfoUpdate) {
- // Find the corresponding updated DeviceInformation in the collection and pass the update object
- // to the Update method of the existing DeviceInformation. This automatically updates the object
- // for us.
- resultCollection.forEach(function (value, index, array) {
- if (value.id == deviceInfoUpdate.id) {
- value.update(deviceInfoUpdate);
- }
- });
- }
-
- function onRemoved(deviceInfoUpdate) {
- for (var i = 0; resultCollection.length; i++) {
- if (resultCollection.getAt(i).id == deviceInfoUpdate.id) {
- resultCollection.splice(i, 1);
- break;
- }
- }
-
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Watching for updates...", "sample", "status");
- }
-
- function onEnumerationCompleted(obj) {
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Enumeration completed. Watching for updates...", "sample", "status");
- }
-
- function onStopped(obj) {
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Watcher stopped", "sample", "status");
- }
-
})();
diff --git a/Samples/DeviceEnumerationAndPairing/js/js/scenario8_pairdevice.js b/Samples/DeviceEnumerationAndPairing/js/js/scenario8_pairdevice.js
index 6c1a18effd..b5d586adc5 100644
--- a/Samples/DeviceEnumerationAndPairing/js/js/scenario8_pairdevice.js
+++ b/Samples/DeviceEnumerationAndPairing/js/js/scenario8_pairdevice.js
@@ -4,16 +4,13 @@
"use strict";
var DevEnum = Windows.Devices.Enumeration;
- var deviceWatcher = null;
var resultCollection = new WinJS.Binding.List([]);
var resultsListView;
+ var deviceWatcherHelper = new SdkSample.DeviceWatcherHelper(resultCollection);
var page = WinJS.UI.Pages.define("/html/scenario8_pairdevice.html", {
ready: function (element, options) {
- // Setup beforeNavigate event
- WinJS.Navigation.addEventListener("beforenavigate", onLeavingPage);
-
// Hook up button event handlers
document.getElementById("startWatcherButton").addEventListener("click", startWatcher, false);
document.getElementById("stopWatcherButton").addEventListener("click", stopWatcher, false);
@@ -26,6 +23,10 @@
// Hook up result list data binding
resultsListView.itemDataSource = resultCollection.dataSource;
+ // We need to do some extra work when an item changes.
+ // This event is raised by the DeviceWatcherHelper.
+ resultCollection.addEventListener("deviceupdated", onDeviceUpdated);
+
// Manually bind selector options
DisplayHelpers.pairingSelectors.forEach(function each(item) {
var option = document.createElement("option");
@@ -36,15 +37,13 @@
// Process any data bindings
WinJS.UI.processAll();
+ },
+ unload: function () {
+ deviceWatcherHelper.reset();
+ resultCollection.splice(0, resultCollection.length);
}
});
- function onLeavingPage() {
- stopWatcher();
- WinJS.Navigation.removeEventListener("beforenavigate", onLeavingPage);
- resultCollection.splice(0, resultCollection.length);
- }
-
function startWatcher() {
startWatcherButton.disabled = true;
resultCollection.splice(0, resultCollection.length);
@@ -54,6 +53,7 @@
var selectedItem = DisplayHelpers.pairingSelectors.getAt(selectorComboBox.selectedIndex);
var selector = "(" + selectedItem.selector + ")" + " AND (System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True)";
+ var deviceWatcher;
if (selectedItem.kind == DevEnum.DeviceInformationKind.unknown) {
// Kind will be determined by the selector
deviceWatcher = DevEnum.DeviceInformation.createWatcher(
@@ -69,89 +69,31 @@
selectedItem.kind);
}
- // Add event handlers
- deviceWatcher.addEventListener("added", onAdded);
- deviceWatcher.addEventListener("updated", onUpdated);
- deviceWatcher.addEventListener("removed", onRemoved);
- deviceWatcher.addEventListener("enumerationcompleted", onEnumerationCompleted);
- deviceWatcher.addEventListener("stopped", onStopped);
-
WinJS.log && WinJS.log("Starting watcher...", "sample", "status");
- deviceWatcher.start();
+ deviceWatcherHelper.startWatcher(deviceWatcher);
stopWatcherButton.disabled = false;
}
function stopWatcher() {
-
stopWatcherButton.disabled = true;
-
- if (null != deviceWatcher) {
-
- // First unhook all event handlers except the stopped handler. This ensures our
- // event handlers don't get called after stop, as stop won't block for any "in flight"
- // event handler calls. We leave the stopped handler as it's guaranteed to only be called
- // once and we'll use it to know when the query is completely stopped.
- deviceWatcher.removeEventListener("added", onAdded);
- deviceWatcher.removeEventListener("updated", onUpdated);
- deviceWatcher.removeEventListener("removed", onRemoved);
- deviceWatcher.removeEventListener("enumerationcompleted", onEnumerationCompleted);
-
- if (DevEnum.DeviceWatcherStatus.started == deviceWatcher.status ||
- DevEnum.DeviceWatcherStatus.enumerationCompleted == deviceWatcher.status) {
- deviceWatcher.stop();
- }
- }
-
+ deviceWatcherHelper.stopWatcher();
startWatcherButton.disabled = false;
}
- function onAdded(deviceInfo) {
- // For simplicity, just creating a new "display object" on the fly since databinding directly with deviceInfo from
- // the callback doesn't work.
- resultCollection.push(new DisplayHelpers.DeviceInformationDisplay(deviceInfo));
-
- if (deviceWatcher.status == DevEnum.DeviceWatcherStatus.enumerationCompleted) {
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Watching for updates...", "sample", "status");
+ function getSelectedItem() {
+ var selectedIndices = resultsListView.selection.getIndices();
+ if (selectedIndices.length > 0) {
+ return resultCollection.getAt(selectedIndices[0]);
}
}
- function onUpdated(deviceInfoUpdate) {
- // Find the corresponding updated DeviceInformation in the collection and pass the update object
- // to the Update method of the existing DeviceInformation. This automatically updates the object
- // for us.
- resultCollection.forEach(function (value, index, array) {
- if (value.id == deviceInfoUpdate.id) {
- value.update(deviceInfoUpdate);
-
- // If the item being updated is currently "selected", then update the pairing buttons
- var selectedItems = resultsListView.selection.getIndices();
- if (selectedItems &&
- selectedItems.length > 0 &&
- value == selectedItems[0])
- {
- UpdatePairingButtons();
- }
- }
- });
- }
-
- function onRemoved(deviceInfoUpdate) {
- for (var i = 0; resultCollection.length; i++) {
- if (resultCollection.getAt(i).id == deviceInfoUpdate.id) {
- resultCollection.splice(i, 1);
- break;
- }
+ function onDeviceUpdated(e) {
+ var id = e.detail.id;
+ // If the item being updated is currently "selected", then update the pairing buttons
+ var selectedItem = getSelectedItem();
+ if (selectedItem && selectedItem.id === id) {
+ UpdatePairingButtons();
}
-
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Watching for updates...", "sample", "status");
- }
-
- function onEnumerationCompleted(obj) {
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Enumeration completed. Watching for updates...", "sample", "status");
- }
-
- function onStopped(obj) {
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Watcher stopped", "sample", "status");
}
function pairDevice() {
@@ -159,11 +101,8 @@
pairButton.disabled = true;
WinJS.log && WinJS.log("Pairing started. Please wait...", "sample", "status");
- var selectedItems = resultsListView.selection.getIndices();
-
- if (selectedItems.length > 0) {
- var deviceDispInfo = resultCollection.getAt(selectedItems[0]);
-
+ var deviceDispInfo = getSelectedItem();
+ if (deviceDispInfo) {
deviceDispInfo.deviceInfo.pairing.pairAsync().done(
function (pairingResult) {
var statusType = (pairingResult.status == DevEnum.DevicePairingResultStatus.paired) ? "status" : "error";
@@ -180,11 +119,8 @@
unpairButton.disabled = true;
WinJS.log && WinJS.log("Unpairing started. Please wait...", "sample", "status");
- var selectedItems = resultsListView.selection.getIndices();
-
- if (selectedItems.length > 0) {
- var deviceDispInfo = resultCollection.getAt(selectedItems[0]);
-
+ var deviceDispInfo = getSelectedItem();
+ if (deviceDispInfo) {
deviceDispInfo.deviceInfo.pairing.unpairAsync().done(
function (unpairingResult) {
var message = (unpairingResult.status == DevEnum.DeviceUnpairingResultStatus.unpaired) ? "Unpaired" : "Failed";
@@ -203,13 +139,9 @@
function updatePairingButtons() {
var selectedItems = resultsListView.selection.getIndices();
- var deviceDispInfo = null;
-
- if (selectedItems.length > 0) {
- deviceDispInfo = resultCollection.getAt(selectedItems[0]);
- }
+ var deviceDispInfo = getSelectedItem();
- if (null != deviceDispInfo &&
+ if (deviceDispInfo &&
deviceDispInfo.canPair &&
!deviceDispInfo.isPaired) {
pairButton.disabled = false;
@@ -218,7 +150,7 @@
pairButton.disabled = true;
}
- if (null != deviceDispInfo &&
+ if (deviceDispInfo &&
deviceDispInfo.isPaired) {
unpairButton.disabled = false;
}
diff --git a/Samples/DeviceEnumerationAndPairing/js/js/scenario9_custompairdevice.js b/Samples/DeviceEnumerationAndPairing/js/js/scenario9_custompairdevice.js
index c0d4e586f6..9cb43596f7 100644
--- a/Samples/DeviceEnumerationAndPairing/js/js/scenario9_custompairdevice.js
+++ b/Samples/DeviceEnumerationAndPairing/js/js/scenario9_custompairdevice.js
@@ -4,18 +4,15 @@
"use strict";
var DevEnum = Windows.Devices.Enumeration;
- var deviceWatcher = null;
var resultCollection = new WinJS.Binding.List([]);
var resultsListView;
+ var deviceWatcherHelper = new SdkSample.DeviceWatcherHelper(resultCollection);
var providePinTaskSrc;
var confirmPinTaskSrc;
var page = WinJS.UI.Pages.define("/html/scenario9_custompairdevice.html", {
ready: function (element, options) {
- // Setup beforeNavigate event
- WinJS.Navigation.addEventListener("beforenavigate", onLeavingPage);
-
// Hook up button event handlers
document.getElementById("startWatcherButton").addEventListener("click", startWatcher, false);
document.getElementById("stopWatcherButton").addEventListener("click", stopWatcher, false);
@@ -31,6 +28,10 @@
// Hook up result list data binding
resultsListView.itemDataSource = resultCollection.dataSource;
+ // We need to do some extra work when an item changes.
+ // This event is raised by the DeviceWatcherHelper.
+ resultCollection.addEventListener("deviceupdated", onDeviceUpdated);
+
// Manually bind selector options
DisplayHelpers.pairingSelectors.forEach(function each(item) {
var option = document.createElement("option");
@@ -41,15 +42,13 @@
// Process any data bindings
WinJS.UI.processAll();
+ },
+ unload: function () {
+ deviceWatcherHelper.reset();
+ resultCollection.splice(0, resultCollection.length);
}
});
- function onLeavingPage() {
- stopWatcher();
- WinJS.Navigation.removeEventListener("beforenavigate", onLeavingPage);
- resultCollection.splice(0, resultCollection.length);
- }
-
function startWatcher() {
startWatcherButton.disabled = true;
resultCollection.splice(0, resultCollection.length);
@@ -59,6 +58,7 @@
var selectedItem = DisplayHelpers.pairingSelectors.getAt(selectorComboBox.selectedIndex);
var selector = "(" + selectedItem.selector + ")" + " AND (System.Devices.Aep.CanPair:=System.StructuredQueryType.Boolean#True OR System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True)";
+ var deviceWatcher;
if (selectedItem.kind == DevEnum.DeviceInformationKind.unknown) {
// Kind will be determined by the selector
deviceWatcher = DevEnum.DeviceInformation.createWatcher(
@@ -74,88 +74,31 @@
selectedItem.kind);
}
- // Add event handlers
- deviceWatcher.addEventListener("added", onAdded);
- deviceWatcher.addEventListener("updated", onUpdated);
- deviceWatcher.addEventListener("removed", onRemoved);
- deviceWatcher.addEventListener("enumerationcompleted", onEnumerationCompleted);
- deviceWatcher.addEventListener("stopped", onStopped);
-
WinJS.log && WinJS.log("Starting watcher...", "sample", "status");
- deviceWatcher.start();
+ deviceWatcherHelper.startWatcher(deviceWatcher);
stopWatcherButton.disabled = false;
}
function stopWatcher() {
-
stopWatcherButton.disabled = true;
-
- if (null != deviceWatcher) {
-
- // First unhook all event handlers except the stopped handler. This ensures our
- // event handlers don't get called after stop, as stop won't block for any "in flight"
- // event handler calls. We leave the stopped handler as it's guaranteed to only be called
- // once and we'll use it to know when the query is completely stopped.
- deviceWatcher.removeEventListener("added", onAdded);
- deviceWatcher.removeEventListener("updated", onUpdated);
- deviceWatcher.removeEventListener("removed", onRemoved);
- deviceWatcher.removeEventListener("enumerationcompleted", onEnumerationCompleted);
-
- if (DevEnum.DeviceWatcherStatus.started == deviceWatcher.status ||
- DevEnum.DeviceWatcherStatus.enumerationCompleted == deviceWatcher.status) {
- deviceWatcher.stop();
- }
- }
-
+ deviceWatcherHelper.stopWatcher();
startWatcherButton.disabled = false;
}
- function onAdded(deviceInfo) {
- // For simplicity, just creating a new "display object" on the fly since databinding directly with deviceInfo from
- // the callback doesn't work.
- resultCollection.push(new DisplayHelpers.DeviceInformationDisplay(deviceInfo));
-
- if (deviceWatcher.status == DevEnum.DeviceWatcherStatus.enumerationCompleted) {
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Watching for updates...", "sample", "status");
+ function getSelectedItem() {
+ var selectedIndices = resultsListView.selection.getIndices();
+ if (selectedIndices.length > 0) {
+ return resultCollection.getAt(selectedIndices[0]);
}
}
- function onUpdated(deviceInfoUpdate) {
- // Find the corresponding updated DeviceInformation in the collection and pass the update object
- // to the Update method of the existing DeviceInformation. This automatically updates the object
- // for us.
- resultCollection.forEach(function (value, index, array) {
- if (value.id == deviceInfoUpdate.id) {
- value.update(deviceInfoUpdate);
- }
-
- // If the item being updated is currently "selected", then update the pairing buttons
- var selectedItems = resultsListView.selection.getIndices();
- if (selectedItems &&
- selectedItems.length > 0 &&
- value == selectedItems[0]) {
- UpdatePairingButtons();
- }
- });
- }
-
- function onRemoved(deviceInfoUpdate) {
- for (var i = 0; resultCollection.length; i++) {
- if (resultCollection.getAt(i).id == deviceInfoUpdate.id) {
- resultCollection.splice(i, 1);
- break;
- }
+ function onDeviceUpdated(e) {
+ var id = e.detail.id;
+ // If the item being updated is currently "selected", then update the pairing buttons
+ var selectedItem = getSelectedItem();
+ if (selectedItem && selectedItem.id === id) {
+ UpdatePairingButtons();
}
-
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Watching for updates...", "sample", "status");
- }
-
- function onEnumerationCompleted(obj) {
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Enumeration completed. Watching for updates...", "sample", "status");
- }
-
- function onStopped(obj) {
- WinJS.log && WinJS.log(resultCollection.length + " devices found. Watcher stopped", "sample", "status");
}
function pairDevice() {
@@ -163,10 +106,8 @@
pairButton.disabled = true;
WinJS.log && WinJS.log("Pairing started. Please wait...", "sample", "status");
- var selectedItems = resultsListView.selection.getIndices();
-
- if (selectedItems.length > 0) {
- var deviceDispInfo = resultCollection.getAt(selectedItems[0]);
+ var deviceDispInfo = getSelectedItem();
+ if (deviceDispInfo) {
var ceremoniesSelected = GetSelectedCeremonies();
var protectionLevel = protectionLevelComboBox.selectedIndex;
@@ -192,11 +133,8 @@
unpairButton.disabled = true;
WinJS.log && WinJS.log("Unpairing started. Please wait...", "sample", "status");
- var selectedItems = resultsListView.selection.getIndices();
-
- if (selectedItems.length > 0) {
- var deviceDispInfo = resultCollection.getAt(selectedItems[0]);
-
+ var deviceDispInfo = getSelectedItem();
+ if (deviceDispInfo) {
unpairButton.disabled = true;
deviceDispInfo.deviceInfo.pairing.unpairAsync().done(
function (unpairingResult) {
@@ -369,14 +307,9 @@
function updatePairingButtons() {
- var selectedItems = resultsListView.selection.getIndices();
- var deviceDispInfo = null;
-
- if (selectedItems.length > 0) {
- deviceDispInfo = resultCollection.getAt(selectedItems[0]);
- }
+ var deviceDispInfo = getSelectedItem();
- if (null != deviceDispInfo &&
+ if (deviceDispInfo &&
deviceDispInfo.canPair &&
!deviceDispInfo.isPaired) {
pairButton.disabled = false;
@@ -385,7 +318,7 @@
pairButton.disabled = true;
}
- if (null != deviceDispInfo &&
+ if (deviceDispInfo &&
deviceDispInfo.isPaired) {
unpairButton.disabled = false;
}
diff --git a/Samples/DeviceEnumerationAndPairing/cpp/Scenario1_DevicePicker.xaml b/Samples/DeviceEnumerationAndPairing/shared/Scenario1_DevicePicker.xaml
similarity index 83%
rename from Samples/DeviceEnumerationAndPairing/cpp/Scenario1_DevicePicker.xaml
rename to Samples/DeviceEnumerationAndPairing/shared/Scenario1_DevicePicker.xaml
index dfc4df9150..43af1ec9a5 100644
--- a/Samples/DeviceEnumerationAndPairing/cpp/Scenario1_DevicePicker.xaml
+++ b/Samples/DeviceEnumerationAndPairing/shared/Scenario1_DevicePicker.xaml
@@ -58,8 +58,7 @@
+ ItemTemplate="{StaticResource ComboBoxItemTemplate}"/>
-
-
-
-
+
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cpp/Scenario2_DeviceWatcher.xaml b/Samples/DeviceEnumerationAndPairing/shared/Scenario2_DeviceWatcher.xaml
similarity index 90%
rename from Samples/DeviceEnumerationAndPairing/cpp/Scenario2_DeviceWatcher.xaml
rename to Samples/DeviceEnumerationAndPairing/shared/Scenario2_DeviceWatcher.xaml
index 8d856a278b..2eb183e7f4 100644
--- a/Samples/DeviceEnumerationAndPairing/cpp/Scenario2_DeviceWatcher.xaml
+++ b/Samples/DeviceEnumerationAndPairing/shared/Scenario2_DeviceWatcher.xaml
@@ -58,8 +58,7 @@
+ ItemTemplate="{StaticResource ComboBoxItemTemplate}" />
-
-
-
-
+
diff --git a/Samples/DeviceEnumerationAndPairing/cpp/Scenario3_BackgroundDeviceWatcher.xaml b/Samples/DeviceEnumerationAndPairing/shared/Scenario3_BackgroundDeviceWatcher.xaml
similarity index 88%
rename from Samples/DeviceEnumerationAndPairing/cpp/Scenario3_BackgroundDeviceWatcher.xaml
rename to Samples/DeviceEnumerationAndPairing/shared/Scenario3_BackgroundDeviceWatcher.xaml
index ad056fb682..90971c2968 100644
--- a/Samples/DeviceEnumerationAndPairing/cpp/Scenario3_BackgroundDeviceWatcher.xaml
+++ b/Samples/DeviceEnumerationAndPairing/shared/Scenario3_BackgroundDeviceWatcher.xaml
@@ -33,8 +33,7 @@
+ ItemTemplate="{StaticResource ComboBoxItemTemplate}"/>
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cpp/Scenario5_GetSingleDevice.xaml b/Samples/DeviceEnumerationAndPairing/shared/Scenario5_GetSingleDevice.xaml
similarity index 82%
rename from Samples/DeviceEnumerationAndPairing/cpp/Scenario5_GetSingleDevice.xaml
rename to Samples/DeviceEnumerationAndPairing/shared/Scenario5_GetSingleDevice.xaml
index 272a32177d..aa41212e80 100644
--- a/Samples/DeviceEnumerationAndPairing/cpp/Scenario5_GetSingleDevice.xaml
+++ b/Samples/DeviceEnumerationAndPairing/shared/Scenario5_GetSingleDevice.xaml
@@ -63,19 +63,11 @@
Get
-
-
-
-
+
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cpp/Scenario6_CustomFilterAddedProps.xaml b/Samples/DeviceEnumerationAndPairing/shared/Scenario6_CustomFilterAddedProps.xaml
similarity index 86%
rename from Samples/DeviceEnumerationAndPairing/cpp/Scenario6_CustomFilterAddedProps.xaml
rename to Samples/DeviceEnumerationAndPairing/shared/Scenario6_CustomFilterAddedProps.xaml
index 035c1d7611..b65f04bd53 100644
--- a/Samples/DeviceEnumerationAndPairing/cpp/Scenario6_CustomFilterAddedProps.xaml
+++ b/Samples/DeviceEnumerationAndPairing/shared/Scenario6_CustomFilterAddedProps.xaml
@@ -84,20 +84,11 @@
-
-
-
-
+
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cpp/Scenario7_DeviceInformationKind.xaml b/Samples/DeviceEnumerationAndPairing/shared/Scenario7_DeviceInformationKind.xaml
similarity index 83%
rename from Samples/DeviceEnumerationAndPairing/cpp/Scenario7_DeviceInformationKind.xaml
rename to Samples/DeviceEnumerationAndPairing/shared/Scenario7_DeviceInformationKind.xaml
index cb97afaa40..64212a113f 100644
--- a/Samples/DeviceEnumerationAndPairing/cpp/Scenario7_DeviceInformationKind.xaml
+++ b/Samples/DeviceEnumerationAndPairing/shared/Scenario7_DeviceInformationKind.xaml
@@ -64,8 +64,7 @@
+ ItemTemplate="{StaticResource ComboBoxItemTemplate}"/>
-
-
-
-
+
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cpp/Scenario8_PairDevice.xaml b/Samples/DeviceEnumerationAndPairing/shared/Scenario8_PairDevice.xaml
similarity index 87%
rename from Samples/DeviceEnumerationAndPairing/cpp/Scenario8_PairDevice.xaml
rename to Samples/DeviceEnumerationAndPairing/shared/Scenario8_PairDevice.xaml
index 53d366248b..74dc7b0e8f 100644
--- a/Samples/DeviceEnumerationAndPairing/cpp/Scenario8_PairDevice.xaml
+++ b/Samples/DeviceEnumerationAndPairing/shared/Scenario8_PairDevice.xaml
@@ -71,8 +71,7 @@
+ ItemTemplate="{StaticResource ComboBoxItemTemplate}" />
-
-
-
-
+
-
-
-
-
diff --git a/Samples/DeviceEnumerationAndPairing/cpp/Scenario9_CustomPairDevice.xaml b/Samples/DeviceEnumerationAndPairing/shared/Scenario9_CustomPairDevice.xaml
similarity index 90%
rename from Samples/DeviceEnumerationAndPairing/cpp/Scenario9_CustomPairDevice.xaml
rename to Samples/DeviceEnumerationAndPairing/shared/Scenario9_CustomPairDevice.xaml
index 6b96e1108c..d0f603f85b 100644
--- a/Samples/DeviceEnumerationAndPairing/cpp/Scenario9_CustomPairDevice.xaml
+++ b/Samples/DeviceEnumerationAndPairing/shared/Scenario9_CustomPairDevice.xaml
@@ -62,7 +62,7 @@
- This scenario demonstrates how to perform custom pairing. Custom pairing allows your app to be involved in the pairing ceremony and use your on UI.
+ This scenario demonstrates how to perform custom pairing. Custom pairing allows your app to be involved in the pairing ceremony and use your own UI.
If you want Windows to control the ceremony and display system UI, please look at the basic pairing scenario.
This method can be used to pair devices like WiFiDirect, WSD, UPnP, Bluetooth or Bluetooth LE devices.
Pairing can only be performed on DeviceInformation objects of kind DeviceInformationKind.AssociationEndpoint.
@@ -139,21 +139,13 @@
-
-
-
-
+
-
-
-
-
diff --git a/Samples/DeviceLockdownAzureLogin/README.md b/Samples/DeviceLockdownAzureLogin/README.md
index d179203ee4..4071d2692c 100644
--- a/Samples/DeviceLockdownAzureLogin/README.md
+++ b/Samples/DeviceLockdownAzureLogin/README.md
@@ -4,7 +4,7 @@ languages:
- csharp
products:
- windows
-- uwp
+- windows-uwp
---
+
\ No newline at end of file
diff --git a/Samples/ShareTarget/js/ShareTarget.sln b/Samples/ShareTarget/js/ShareTarget.sln
new file mode 100644
index 0000000000..554efa0abc
--- /dev/null
+++ b/Samples/ShareTarget/js/ShareTarget.sln
@@ -0,0 +1,48 @@
+
+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}") = "ShareTarget", "ShareTarget.jsproj", "{BF4F0A05-D096-51DA-AE3C-5A320D71CA32}"
+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
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Debug|ARM.ActiveCfg = Debug|ARM
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Debug|ARM.Build.0 = Debug|ARM
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Debug|ARM.Deploy.0 = Debug|ARM
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Debug|x64.ActiveCfg = Debug|x64
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Debug|x64.Build.0 = Debug|x64
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Debug|x64.Deploy.0 = Debug|x64
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Debug|x86.ActiveCfg = Debug|x86
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Debug|x86.Build.0 = Debug|x86
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Debug|x86.Deploy.0 = Debug|x86
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Release|Any CPU.Build.0 = Release|Any CPU
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Release|Any CPU.Deploy.0 = Release|Any CPU
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Release|ARM.ActiveCfg = Release|ARM
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Release|ARM.Build.0 = Release|ARM
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Release|ARM.Deploy.0 = Release|ARM
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Release|x64.ActiveCfg = Release|x64
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Release|x64.Build.0 = Release|x64
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Release|x64.Deploy.0 = Release|x64
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Release|x86.ActiveCfg = Release|x86
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Release|x86.Build.0 = Release|x86
+ {BF4F0A05-D096-51DA-AE3C-5A320D71CA32}.Release|x86.Deploy.0 = Release|x86
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/Samples/ShareTarget/js/css/share-target.css b/Samples/ShareTarget/js/css/share-target.css
new file mode 100644
index 0000000000..d58f72f8ae
--- /dev/null
+++ b/Samples/ShareTarget/js/css/share-target.css
@@ -0,0 +1,44 @@
+/*
+Copyright (c) Microsoft Corporation. All rights reserved
+*/
+
+.hidden {
+ display: none;
+}
+
+.unhidden {
+ visibility: visible;
+}
+
+#quickLinkError {
+ color: red;
+}
+
+.package-logo {
+ width: 40px;
+ height: 40px;
+ display: flex;
+}
+
+.thumbnail img {
+ max-height: 48px;
+ max-width: 48px;
+}
+
+.package-bitmap img {
+ max-height: 200px;
+ max-width: 200px;
+}
+
+.error {
+ color: red;
+}
+
+#contentWrapper {
+ padding: 10px 42px 10px 42px;
+ overflow-y: auto;
+}
+
+#scenarioPane {
+ flex-grow: 1;
+}
diff --git a/Samples/ShareTarget/js/html/scenario1-welcome.html b/Samples/ShareTarget/js/html/scenario1-welcome.html
new file mode 100644
index 0000000000..22b28824c8
--- /dev/null
+++ b/Samples/ShareTarget/js/html/scenario1-welcome.html
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
Description:
+
+ This app demonstrates how to receive content as a share target.
+ To try it, share from an app that supports share, such as the Share Source Sample App,
+ and select the Share Target Sample App from the share pane.
+
+
+
+
+
\ No newline at end of file
diff --git a/Samples/ShareTarget/js/images/placeholder.txt b/Samples/ShareTarget/js/images/placeholder.txt
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/Samples/ShareTarget/js/js/sample-configuration.js b/Samples/ShareTarget/js/js/sample-configuration.js
new file mode 100644
index 0000000000..04c1ef754f
--- /dev/null
+++ b/Samples/ShareTarget/js/js/sample-configuration.js
@@ -0,0 +1,16 @@
+//// Copyright (c) Microsoft Corporation. All rights reserved
+
+(function () {
+ "use strict";
+
+ var sampleTitle = "Share target JS sample";
+
+ var scenarios = [
+ { url: "/html/scenario1-welcome.html", title: "Welcome" },
+ ];
+
+ WinJS.Namespace.define("SdkSample", {
+ sampleTitle: sampleTitle,
+ scenarios: new WinJS.Binding.List(scenarios)
+ });
+})();
diff --git a/Samples/ShareTarget/js/js/scenario1-welcome.js b/Samples/ShareTarget/js/js/scenario1-welcome.js
new file mode 100644
index 0000000000..db906eddbd
--- /dev/null
+++ b/Samples/ShareTarget/js/js/scenario1-welcome.js
@@ -0,0 +1,11 @@
+//// Copyright (c) Microsoft Corporation. All rights reserved
+
+(function () {
+ "use strict";
+ var page = WinJS.UI.Pages.define("/html/scenario1-welcome.html", {
+ ready: function (element, options) {
+ },
+ unload: function () {
+ }
+ });
+})();
diff --git a/Samples/ShareTarget/js/js/share-target.js b/Samples/ShareTarget/js/js/share-target.js
new file mode 100644
index 0000000000..a692380ab9
--- /dev/null
+++ b/Samples/ShareTarget/js/js/share-target.js
@@ -0,0 +1,426 @@
+//// Copyright (c) Microsoft Corporation. All rights reserved
+
+(function () {
+ "use strict";
+
+ // Commonly-used types.
+ var StandardDataFormats = Windows.ApplicationModel.DataTransfer.StandardDataFormats;
+ var HtmlFormatHelper = Windows.ApplicationModel.DataTransfer.HtmlFormatHelper;
+ var QuickLink = Windows.ApplicationModel.DataTransfer.ShareTarget.QuickLink;
+
+ // Variable to store the ShareOperation object
+ var shareOperation = null;
+
+ // Variable to store the visibility of the Extended Sharing section
+ var extendedSharingCollapsed = true;
+
+ // Variable to store the custom format string
+ var customFormatName = "http://schema.org/Book";
+
+ ///
+ /// Helper function to set an element's inner text to a value.
+ ///
+ function setInnerText(id, value) {
+ document.getElementById(id).innerText = value;
+ }
+
+ ///
+ /// Helper function to display textual information in an element.
+ ///
+ ///
+ /// The element in which to add new information.
+ ///
+ ///
+ /// A text label to show before the text content.
+ ///
+ ///
+ /// The text content to display.
+ ///
+ ///
+ /// Optional class name to assign to the div.
+ ///
+ function addTextContent(container, label, text, className) {
+ var div = document.createElement("div");
+ var labelNode = document.createElement("strong");
+ labelNode.innerText = label;
+ div.appendChild(labelNode);
+ var span = document.createElement("span");
+ span.innerText = ": " + text;
+ div.appendChild(span);
+ if (className) {
+ div.className = className;
+ }
+ return container.appendChild(div);
+ }
+
+ function addError(container, label, message, e) {
+ return addTextContainer(container, label, "Error retrieving data: " + e, "error");
+ }
+
+ ///
+ /// Helper function to display bitmap information in an element.
+ /// Returns the div wrapper for the image.
+ ///
+ ///
+ /// The element in which to add new information.
+ ///
+ ///
+ /// A text label to show before the text content.
+ ///
+ ///
+ /// A random access stream reference containing the bitmap.
+ ///
+ ///
+ /// Class to assign to the div that wraps the image.
+ ///
+ function addImageContent(container, label, streamReference, className) {
+ addTextContent(container, label, "");
+ var div = document.createElement("div");
+ div.className = className;
+ streamReference.openReadAsync().done(function (stream) {
+ var img = document.createElement("img");
+ img.src = URL.createObjectURL(stream, { oneTimeOnly: true });
+ div.appendChild(img);
+ }, function (e) {
+ div.innerText = "Error reading image stream: " + e;
+ });
+ return container.appendChild(div);
+ }
+
+ function addContent(label, text) {
+ var contentValue = document.getElementById("contentValue");
+ addTextContent(contentValue, label, text);
+ }
+ function displayError(label, errorString) {
+ return addContent(label, errorString);
+ }
+
+ ///
+ /// Handler executed on activation of the target
+ ///
+ ///
+ /// Arguments of the event. In the case of the Share contract, it has the ShareOperation
+ ///
+ function activatedHandler(eventObject) {
+ // In this sample we only do something if it was activated with the Share contract
+ if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.shareTarget) {
+ eventObject.setPromise(WinJS.UI.processAll());
+
+ // We receive the ShareOperation object as part of the eventArgs
+ shareOperation = eventObject.detail.shareOperation;
+
+ // We queue an asychronous event so that working with the ShareOperation object does not
+ // block or delay the return of the activation handler.
+ WinJS.Application.queueEvent({ type: "shareready" });
+ }
+ }
+
+ ///
+ /// Display properties of the data package.
+ ///
+ function showProperties() {
+ var container = document.getElementById("dataPackageProperties");
+ var properties = shareOperation.data.properties;
+
+ addTextContent(container, "Title", properties.title);
+ addTextContent(container, "Description", properties.description);
+ addTextContent(container, "Package Family Name", properties.packageFamilyName);
+
+ if (properties.contentSourceWebLink) {
+ addTextContent(container, "Content Source Web Link", properties.contentSourceWebLink.rawUri);
+ }
+
+ if (properties.contentSourceApplicationLink) {
+ addTextContent(container, "Content Source Application Link", properties.contentSourceApplicationLink.rawUri);
+ }
+
+ if (properties.square30x30Logo) {
+ var div = addImageContent(container, "Logo", properties.square30x30Logo, "package-logo");
+ var backgroundColor = properties.logoBackgroundColor;
+ div.style.backgroundColor = "rgba(" + backgroundColor.r + "," + backgroundColor.g + "," + backgroundColor.b + "," + backgroundColor.a + ")";
+ }
+
+ if (properties.thumbnail) {
+ addImageContent(container, "Thumbnail", properties.thumbnail, "thumbnail");
+ }
+ }
+
+ ///
+ /// Handle the incoming shared data. This should be done outside the activation handler.
+ ///
+ function shareReady() {
+ var data = shareOperation.data;
+
+ // Display properties of the data package.
+ showProperties();
+
+ // If this app was activated via a QuickLink, display the QuickLinkId
+ if (shareOperation.quickLinkId) {
+ document.getElementById("selectedQuickLinkId").innerText = shareOperation.quickLinkId;
+ document.getElementById("quickLinkArea").className = "hidden";
+ }
+
+ // Display the data received based on data type
+ var container = document.getElementById("dataPackageContents");
+
+ if (data.contains(StandardDataFormats.text)) {
+ data.getTextAsync().done(function (text) {
+ addTextContent(container, "Text", text);
+ }, function (e) {
+ addError(container, "Text", e);
+ });
+ }
+ if (data.contains(StandardDataFormats.webLink)) {
+ data.getWebLinkAsync().done(function (webLink) {
+ addTextContent(container, "WebLink", webLink.rawUri);
+ }, function (e) {
+ addError(container, "WebLink", e);
+ });
+ }
+ if (data.contains(StandardDataFormats.applicationLink)) {
+ data.getApplicationLinkAsync().done(function (applicationLink) {
+ addTextContent(container, "ApplicationLink", applicationLink.rawUri);
+ }, function (e) {
+ addError(container, "ApplicationLink", e);
+ });
+ }
+ if (data.contains(StandardDataFormats.storageItems)) {
+ data.getStorageItemsAsync().done(function (storageItems) {
+ var itemCount = storageItems.size;
+ // Display info about the first 10 files.
+ if (storageItems.size > 10) {
+ storageItems = storageItems.slice(0, 10);
+ }
+ var fileList = storageItems.map(item => item.name).join(", ");
+ if (itemCount > 10) {
+ fileList += ` and ${itemCount - 10} more`;
+ }
+ addTextContent(container, "Storage Items", fileList);
+ }, function (e) {
+ addError(container, "Storage Items", e);
+ });
+ }
+ if (data.contains(StandardDataFormats.bitmap)) {
+ data.getBitmapAsync().done(function (bitmapStreamReference) {
+ addImageContent(container, "Bitmap", bitmapStreamReference, "package-bitmap");
+ }, function (e) {
+ addError(container, "Bitmap", e);
+ });
+ }
+
+ if (data.contains(StandardDataFormats.html)) {
+ data.getHtmlFormatAsync().done(function (htmlFormat) {
+ addTextContent(container, "HTML", "");
+
+ // Extract the HTML fragment from the HTML format
+ var htmlFragment = HtmlFormatHelper.getStaticFragment(htmlFormat);
+
+ // Create an iframe and add it to the content.
+ var iframe = document.createElement("iframe");
+ iframe.style.width = "600px";
+ container.appendChild(iframe);
+
+ // Set the innerHTML of the iframe to the HTML fragment
+ iframe.contentDocument.documentElement.innerHTML = htmlFragment;
+
+ // Now we loop through any images and use the resourceMap to map each image element's src
+ var images = iframe.contentDocument.documentElement.getElementsByTagName("img");
+ if (images.length > 0) {
+ data.getResourceMapAsync().done(function (resourceMap) {
+ Array.prototype.forEach.call(images, function (image) {
+ var streamReference = resourceMap[image.src];
+ if (streamReference) {
+ // Call a helper function to map the image element's src to a corresponding blob URL generated from the streamReference
+ setResourceMapURL(streamReference, image);
+ }
+ });
+ }, function (e) {
+ addError(container, "Resource Map", e);
+ });
+ }
+ }, function (e) {
+ addError(container, "HTML", e);
+ });
+ }
+
+ if (data.contains(customFormatName)) {
+ data.getTextAsync(customFormatName).done(function (customFormatString) {
+ var customFormatObject = {};
+ try {
+ customFormatObject = JSON.parse(customFormatString);
+ } catch (e) {
+ // invalid JSON
+ }
+ // This sample expects the custom format to be of type http://schema.org/Book
+ if (customFormatObject.type === "http://schema.org/Book") {
+ var lines = ["Type: " + customFormatObject.type];
+ var properties = customFormatObject.properties;
+ if (properties) {
+ lines.push(
+ `Image: ${properties.image}`,
+ `Name: ${properties.name}`,
+ `Book Format: ${properties.bookFormat}`,
+ `Author: ${properties.author}`,
+ `Number of Pages: ${properties.numberOfPages}`,
+ `Publisher: ${properties.publisher}`,
+ `Date Published: ${properties.datePublished}`,
+ `In Language: ${properties.inLanguage}`,
+ `ISBN: ${properties.isbn}`);
+ }
+ addTextContent(container, "Custom data", lines.join("\n"));
+ } else {
+ addError(container, "Custom data", "Malformed data");
+
+ }
+ }, function (e) {
+ addError(container, "Custom data", e);
+ });
+ }
+ }
+
+ ///
+ /// Sets the blob URL for an image element based on a reference to an image stream within a resource map
+ ///
+ function setResourceMapURL(streamReference, imageElement) {
+ if (streamReference) {
+ streamReference.openReadAsync().done(function (imageStream) {
+ if (imageStream) {
+ imageElement.src = URL.createObjectURL(imageStream, { oneTimeOnly: true });
+ }
+ }, function (e) {
+ imageElement.alt = "Failed to load";
+ });
+ }
+ }
+
+ ///
+ /// Use to simulate that an extended share operation has started
+ ///
+ function reportStarted() {
+ shareOperation.reportStarted();
+ }
+
+ ///
+ /// Use to simulate that an extended share operation has retrieved the data
+ ///
+ function reportDataRetrieved() {
+ shareOperation.reportDataRetrieved();
+ }
+
+ ///
+ /// Use to simulate that an extended share operation has reached the status "submittedToBackgroundManager"
+ ///
+ function reportSubmittedBackgroundTask() {
+ shareOperation.reportSubmittedBackgroundTask();
+ }
+
+ ///
+ /// Submit for extended share operations. Can either report success or failure, and in case of success, can add a quicklink.
+ /// This does NOT take care of all the prerequisites (such as calling reportExtendedShareStatus(started)) before submitting.
+ ///
+ function reportError() {
+ var errorText = document.getElementById("extendedShareErrorMessage").value;
+ shareOperation.reportError(errorText);
+ }
+
+ ///
+ /// Call the reportCompleted API with the proper quicklink (if needed)
+ ///
+ function reportCompleted() {
+ var addQuickLink = document.getElementById("addQuickLink").checked;
+ if (addQuickLink) {
+ var el;
+ var quickLink = new QuickLink();
+
+ var quickLinkId = document.getElementById("quickLinkId").value;
+ if (!quickLinkId) {
+ el = document.getElementById("quickLinkError");
+ el.className = "unhidden";
+ el.innerText = "Missing QuickLink ID";
+ return;
+ }
+ quickLink.id = quickLinkId;
+
+ var quickLinkTitle = document.getElementById("quickLinkTitle").value;
+ if (!quickLinkTitle) {
+ el = document.getElementById("quickLinkError");
+ el.className = "unhidden";
+ el.innerText = "Missing QuickLink title";
+ return;
+ }
+ quickLink.title = quickLinkTitle;
+
+ // For quicklinks, the supported FileTypes and DataFormats are set independently from the manifest
+ quickLink.supportedFileTypes.replaceAll(["*"]);
+ quickLink.supportedDataFormats.replaceAll([StandardDataFormats.text, StandardDataFormats.webLink, StandardDataFormats.applicationLink, StandardDataFormats.bitmap, StandardDataFormats.storageItems, StandardDataFormats.html, customFormatName]);
+
+ // Prepare the icon for a QuickLink
+ var iconUri = new Windows.Foundation.Uri(quickLinkIcon.src);
+ Windows.Storage.StorageFile.getFileFromApplicationUriAsync(iconUri).done(function (iconFile) {
+ quickLink.thumbnail = Windows.Storage.Streams.RandomAccessStreamReference.createFromFile(iconFile);
+ shareOperation.reportCompleted(quickLink);
+ }, function (e) {
+ // Even if the QuickLink cannot be created it is important to call ReportCompleted. Otherwise, if this is a long-running share,
+ // the app will stick around in the long-running share progress list.
+ shareOperation.reportCompleted();
+ throw e;
+ });
+ } else {
+ shareOperation.reportCompleted();
+ }
+ }
+
+ ///
+ /// Calls the share operation's dismiss UI function.
+ ///
+ function dismissUI() {
+ shareOperation.dismissUI();
+ }
+
+ ///
+ /// Expand/collapse the Extended Sharing div
+ ///
+ function expandoClick() {
+ if (extendedSharingCollapsed) {
+ document.getElementById("extendedSharing").className = "unhidden";
+ // Set expando glyph to up arrow
+ document.getElementById("expandoGlyph").innerHTML = "";
+ extendedSharingCollapsed = false;
+ } else {
+ document.getElementById("extendedSharing").className = "hidden";
+ // Set expando glyph to down arrow
+ document.getElementById("expandoGlyph").innerHTML = "";
+ extendedSharingCollapsed = true;
+ }
+ }
+
+ ///
+ /// Expand/collapse the QuickLink fields
+ ///
+ function addQuickLinkChanged() {
+ if (document.getElementById("addQuickLink").checked) {
+ quickLinkFields.className = "unhidden";
+ } else {
+ quickLinkFields.className = "hidden";
+ document.getElementById("quickLinkError").className = "hidden";
+ }
+ }
+
+ // Initialize the activation handler
+ WinJS.Application.addEventListener("activated", activatedHandler, false);
+ WinJS.Application.addEventListener("shareready", shareReady, false);
+ WinJS.Application.start();
+
+ function initialize() {
+ document.getElementById("addQuickLink").addEventListener("change", addQuickLinkChanged, false);
+ document.getElementById("reportCompleted").addEventListener("click", reportCompleted, false);
+ document.getElementById("dismissUI").addEventListener("click", dismissUI, false);
+ document.getElementById("expandoClick").addEventListener("click", expandoClick, false);
+ document.getElementById("reportStarted").addEventListener("click", reportStarted, false);
+ document.getElementById("reportDataRetrieved").addEventListener("click", reportDataRetrieved, false);
+ document.getElementById("reportSubmittedBackgroundTask").addEventListener("click", reportSubmittedBackgroundTask, false);
+ document.getElementById("reportError").addEventListener("click", reportError, false);
+ }
+
+ document.addEventListener("DOMContentLoaded", initialize, false);
+})();
\ No newline at end of file
diff --git a/Samples/ShareTarget/js/sample-utils/placeholder.txt b/Samples/ShareTarget/js/sample-utils/placeholder.txt
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/Samples/ShareTarget/js/share-target.html b/Samples/ShareTarget/js/share-target.html
new file mode 100644
index 0000000000..efe9f2a1a5
--- /dev/null
+++ b/Samples/ShareTarget/js/share-target.html
@@ -0,0 +1,102 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ QuickLink Id: This app was not activated through a frequent QuickLink.
+
+
The following Data Package was received from the source app:
+
Data Package Properties
+
+
+
Data Package Contents
+
+
HTML:
+
+
+
+ Your share target app should report completed after the share task completes successfully. This API applies to both quick
+ and long-running shares.
+
+
+
+ When reporting completed, you can optionally add a QuickLink to make it easier for users to repeat the way they share
+ most often. This saves them from having to select that person or group in your app every time they share to them.
+
+
+ If no user interaction is required, you can dismiss your share target programatically while continuing to execute
+ a task in the background. (e.g - Uploading a user selected file in the background)
+
+
+
+
+
+ QuickLink Id:
+ Title:
+ Icon:
+
+
+
+ Dismiss UI
+ Report Completed
+
+
Long-running Share Support
+
+ This API is required if your app supports uploading a format that may take some time, such as images or videos.
+ A user should be able to dismiss your app and have the upload continue in the background while they do other things.
+ In order for the dismiss behavior to work correctly, you need to report to the share platform that you finished getting
+ user input. After you call this, a user can go back to the share pane and see your application in the share progress
+ list.
+
+ Report Started
+
+ This API is optional and helps Windows to optimize resource usage of the system. You should report this if you have finished
+ extracting data from the Data Package so that Windows can suspend or terminate the source app as necessary to reclaim
+ system resources.
+
+ Report Data Retrieved
+
+ This API is optional and helps Windows to optimize resource usage of the system. You should report this if you have called
+ the Windows Runtime Background Transfer class to upload your content. Then Windows can suspend your app as necessary
+ to reclaim system resources. If you use this API, call it after Report Started.
+
+ Report Submitted To BackgroundTask
+
+ If for any reason the long-running share was unsuccessful and failed in the background, you should report failure and
+ include a message for the user about how they can recover from the error. When the user goes back to the share pane
+ they can see your message in the progress list. You must never call Report Error if your app is visible in the
+ foreground.
+
+ Error message:
+
+
+ Report Error
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Samples/Simple3DGameDX/README.md b/Samples/Simple3DGameDX/README.md
index 2383a2740b..0218944471 100644
--- a/Samples/Simple3DGameDX/README.md
+++ b/Samples/Simple3DGameDX/README.md
@@ -4,7 +4,7 @@ languages:
- cpp
products:
- windows
-- uwp
+- windows-uwp
---