NotifyUser() public method

public NotifyUser ( string strMessage, NotifyType type ) : void
strMessage string
type NotifyType
return void
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            ResultCollection = new ObservableCollection<WiFiNetworkDisplay>();
            rootPage = MainPage.Current;

            // RequestAccessAsync must have been called at least once by the app before using the API
            // Calling it multiple times is fine but not necessary
            // RequestAccessAsync must be called from the UI thread
            var access = await WiFiAdapter.RequestAccessAsync();
            if (access != WiFiAccessStatus.Allowed)
            {
                rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
            }
            else
            {
                DataContext = this;

                var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
                if (result.Count >= 1)
                {
                    firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
                    RegisterButton.IsEnabled = true;
                }
                else
                {
                    rootPage.NotifyUser("No WiFi Adapters detected on this machine", NotifyType.ErrorMessage);
                }
            }
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;
            // Clear the messages
            rootPage.NotifyUser(String.Empty, NotifyType.StatusMessage, true);

            if (!ApplicationData.Current.RoamingSettings.Values.ContainsKey("DenyIfPhoneLocked"))
            {
                ApplicationData.Current.RoamingSettings.Values["DenyIfPhoneLocked"] = false;
            }

            if (!ApplicationData.Current.RoamingSettings.Values.ContainsKey("LaunchAboveLock"))
            {
                ApplicationData.Current.RoamingSettings.Values["LaunchAboveLock"] = false;
            }

            chkDenyIfPhoneLocked.IsChecked = (bool)ApplicationData.Current.RoamingSettings.Values["DenyIfPhoneLocked"];
            chkLaunchAboveLock.IsChecked = (bool)ApplicationData.Current.RoamingSettings.Values["LaunchAboveLock"];

            if (!(await CheckHceSupport()))
            {
                // No HCE support on this device
                btnRegisterBgTask.IsEnabled = false;
                btnAddCard.IsEnabled = false;
            }
            else
            {
                lstCards.ItemsSource = await SmartCardEmulator.GetAppletIdGroupRegistrationsAsync();
            }
        }
        /// <summary>
        /// Clean up the notification area when user navigate to prediction page
        /// </summary>
        /// <param name="e">Event data that describes the click action on the button.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            // Clean notification area.
            rootPage.NotifyUser(string.Empty, NotifyType.StatusMessage);
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        ///
        /// We will enable/disable parts of the UI if the device doesn't support it.
        /// </summary>
        /// <param name="eventArgs">Event data that describes how this page was reached. The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            // Get the existing task if already registered
            if (taskRegistration == null)
            {
                // Find the task if we previously registered it
                foreach (var task in BackgroundTaskRegistration.AllTasks.Values)
                {
                    if (task.Name == taskName)
                    {
                        taskRegistration = task;
                        taskRegistration.Completed += OnBackgroundTaskCompleted;
                        break;
                    }
                }
            }
            else
                taskRegistration.Completed += OnBackgroundTaskCompleted;

            // Attach handlers for suspension to stop the watcher when the App is suspended.
            App.Current.Suspending += App_Suspending;
            App.Current.Resuming += App_Resuming;

            rootPage.NotifyUser("Press Run to register watcher.", NotifyType.StatusMessage);
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            ResultCollection = new ObservableCollection<WiFiNetworkDisplay>();
            rootPage = MainPage.Current;

            // RequestAccessAsync must have been called at least once by the app before using the API
            // Calling it multiple times is fine but not necessary
            // RequestAccessAsync must be called from the UI thread
            var result = await WiFiAdapter.RequestAccessAsync();
            if (result != WiFiAccessStatus.Allowed)
            {
                rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
            }
            else
            {
                DataContext = this;

                wiFiAdapters = await WiFiAdapter.FindAllAdaptersAsync();
                int index = 0;
                foreach (var adapter in wiFiAdapters)
                {
                    var button = new Button();
                    button.Tag = index;
                    button.Content = String.Format("WiFi Adapter {0}", ++index);
                    button.Click += Button_Click;
                    Buttons.Children.Add(button);
                }
            }
        }
 protected override async void OnNavigatedTo(NavigationEventArgs e)
 {
     rootPage = MainPage.Current;
     rootPage.NotifyUser("Waiting for client to connect...", NotifyType.StatusMessage);
     tcpListener = new StreamSocketListener();
     tcpListener.ConnectionReceived += OnConnected;
     await tcpListener.BindEndpointAsync(null, port);
 }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;
            try
            {
                foreach (var current in BackgroundTaskRegistration.AllTasks)
                {
                    if (current.Value.Name == "SocketActivityBackgroundTask")
                    {
                        task = current.Value;
                        break;
                    }
                }

                // If there is no task allready created, create a new one
                if (task == null)
                {
                    var socketTaskBuilder = new BackgroundTaskBuilder();
                    socketTaskBuilder.Name = "SocketActivityBackgroundTask";
                    socketTaskBuilder.TaskEntryPoint = "SocketActivityBackgroundTask.SocketActivityTask";
                    var trigger = new SocketActivityTrigger();
                    socketTaskBuilder.SetTrigger(trigger);
                    task = socketTaskBuilder.Register();
                }

                SocketActivityInformation socketInformation;
                if (SocketActivityInformation.AllSockets.TryGetValue(socketId, out socketInformation))
                {
                    // Application can take ownership of the socket and make any socket operation
                    // For sample it is just transfering it back.
                    socket = socketInformation.StreamSocket;
                    socket.TransferOwnership(socketId);
                    socket = null;
                    rootPage.NotifyUser("Connected. You may close the application", NotifyType.StatusMessage);
                    TargetServerTextBox.IsEnabled = false;
                    ConnectButton.IsEnabled = false;
                }

            }
            catch (Exception exception)
            {
                rootPage.NotifyUser(exception.Message, NotifyType.ErrorMessage);
            }
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            ResultCollection = new ObservableCollection<WiFiNetworkDisplay>();
            rootPage = MainPage.Current;

            // RequestAccessAsync must have been called at least once by the app before using the API
            // Calling it multiple times is fine but not necessary
            // RequestAccessAsync must be called from the UI thread
            var access = await WiFiAdapter.RequestAccessAsync();
            if (access != WiFiAccessStatus.Allowed)
            {
                rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
            }
            else
            {
                DataContext = this;

                var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDeviceSelector());
                if (result.Count >= 1)
                {
                    firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);

                    var scanButton = new Button();
                    scanButton.Content = string.Format("Scan");
                    scanButton.Click += ScanButton_Click;
                    Buttons.Children.Add(scanButton);

                    var disconnectButton = new Button();
                    disconnectButton.Content = string.Format("Disconnect");
                    disconnectButton.Click += DisconnectButton_Click; ;
                    Buttons.Children.Add(disconnectButton);

                    // Monitor network status changes
                    await UpdateConnectivityStatusAsync();
                    NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;
                }
                else
                {
                    rootPage.NotifyUser("No WiFi Adapters detected on this machine", NotifyType.ErrorMessage);
                }
            }
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            // RequestAccessAsync must be called at least once from the UI thread
            var accessLevel = await Radio.RequestAccessAsync();
            if (accessLevel != RadioAccessStatus.Allowed)
            {
                rootPage.NotifyUser("App is not allowed to control radios.", NotifyType.ErrorMessage);
            }
            else
            {
                InitializeRadios();
            }
        }
        public SendTextMessage()
        {
            this.InitializeComponent();

            rootPage = MainPage.Current;

            _accelerometer = Accelerometer.GetDefault();
            if (_accelerometer != null)
            {
                // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
                // This value will be used later to activate the sensor.
                uint minReportInterval = _accelerometer.MinimumReportInterval;
                _desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16;

                // Set up a DispatchTimer
                _dispatcherTimer = new DispatcherTimer();
                _dispatcherTimer.Tick += DisplayCurrentReading;
                _dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, (int)_desiredReportInterval);
            }
            else
            {
                 rootPage.NotifyUser("No accelerometer found. This app is not compatible with your device!", NotifyType.ErrorMessage);
            }
        }
Esempio n. 11
0
        public async Task SubscribeAsync()
        {
            PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

            channel.PushNotificationReceived += PushNotificationReceived;
            var result = await apiClient.SubscribeToUserNotificationsAsync(channel);

            if (result.Status != UserNotificationApiResultStatus.Succeeded)
            {
                throw new Exception($"GraphNotificationsSample failed to subscribe for notifications, status: {result.Status}");
            }
            else
            {
                // Save the last good subscription
                rootPage?.NotifyUser($"GraphNotificationsSample subscribed with {result.UserNotificationSubscriptionId} valid till {result.ExpirationDateTime}");

                UserNotificationSubscriptionId = result.UserNotificationSubscriptionId;

                // This App should send "UserNotificationSubscriptionId" to its appservice.
                // Appservice can use UserNotificationSubscriptionId to POST new notification
                // to https://graph.microsoft.com/beta/me/notifications without OAuth tokens.
            }
        }
        /// <summary
        /// This app is registered as a hanlder for WPD\IMageSourceAutoPlay event.
        /// When a user connects a WPD device (ie: Camera), OnNavigatedTo is called with DeviceInformationId
        /// that we can call FromIdAsync() and preselect the device.
        /// 
        /// We also need to handle the situation where the client was terminated while an import operation was in flight.
        /// Import will continue and we attempt to reconnect back to the session.
        /// </summary>
        /// <param name="e">Details about the NavigationEventArgs</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            rootPage = MainPage.Current;
            try
            {
                //An photo import session was in progress
                if (e.Parameter is PhotoImportOperation)
                {
                    PhotoImportOperation op = e.Parameter as PhotoImportOperation;
                    switch (op.Stage)
                    {
                        // file enumeration was running
                        case PhotoImportStage.FindingItems:

                            cts = new CancellationTokenSource();
                            rootPage.NotifyUser("Reconnected back to the file enumeration stage", NotifyType.StatusMessage);

                            // Set up progress handler for existing file enumeration
                            var findAllItemsProgress = new Progress<uint>((result) =>
                            {
                                rootPage.NotifyUser(String.Format("Found {0} Files", result.ToString()), NotifyType.StatusMessage);
                            });

                            // retrieve previous session
                            this.session = op.Session;
                            // get to the operation for the existing FindItemsAsync session
                            this.itemsResult = await op.ContinueFindingItemsAsync.AsTask(cts.Token, findAllItemsProgress);

                            // display the items we found in the previous session
                            setIncrementalFileList(this.itemsResult);
                            this.selectAllButton.IsEnabled = true;
                            this.selectNoneButton.IsEnabled = true;
                            this.selectNewButton.IsEnabled = true;
                            this.importButton.IsEnabled = true;

                            DisplayFindItemsResult();

                            cts = null;
                            break;

                        // Import was running
                        case PhotoImportStage.ImportingItems:

                            rootPage.NotifyUser("Reconnected back to the importing stage.", NotifyType.StatusMessage);

                            setButtonState(false);
                            cts = new CancellationTokenSource();

                            // Set up progress handler for the existing import session

                            var importSelectedItemsProgress = new Progress<PhotoImportProgress>((result) =>
                            {
                                progressBar.Value = result.ImportProgress;
                            });

                            // retrieve the previous operation
                            this.session = op.Session;
                            
                            // get the itemsResult that were found in the previous session
                            this.itemsResult = await op.ContinueFindingItemsAsync.AsTask();
                            
                            // hook up the ItemImported Handler to show progress
                            this.itemsResult.ItemImported += async (s, a) =>
                            {
                                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                {
                                    rootPage.NotifyUser(String.Format("Imported: {0}", a.ImportedItem.Name), NotifyType.StatusMessage);
                                });
                            };

                            // Get the operation for the import operation that was in flight
                            this.importedResult = await op.ContinueImportingItemsAsync.AsTask(cts.Token, importSelectedItemsProgress);

                            DisplayImportedSummary();

                            this.findSourceButton.IsEnabled = true;
                            this.deleteButton.IsEnabled = true;

                            cts = null;
                            break;

                        // Delete operation is in progress
                        case PhotoImportStage.DeletingImportedItemsFromSource:

                            rootPage.NotifyUser("Reconnected to the deletion stage.",NotifyType.StatusMessage);

                            this.findSourceButton.IsEnabled = false;
                            this.deleteButton.IsEnabled = false;
                            cts = new CancellationTokenSource();
                                                       
                            var progress = new Progress<double>((result) =>
                            {
                                this.progressBar.Value = result;
                            });

                            // get the operation for the existing delete session
                            this.deleteResult = await op.ContinueDeletingImportedItemsFromSourceAsync.AsTask(cts.Token, progress);

                            DisplayDeletedResults();

                            if (!deleteResult.HasSucceeded)
                            {
                                rootPage.NotifyUser("Deletion did not succeeded or was cancelled.", NotifyType.StatusMessage);
                            }

                            this.findSourceButton.IsEnabled = true;

                            // Set the CancellationTokenSource to null when the work is complete.
                            cts = null;
                            break;

                        // Idle State.
                        case PhotoImportStage.NotStarted:

                            rootPage.NotifyUser("No import tasks was started.", NotifyType.StatusMessage);
                            this.session = op.Session;
                            break;

                        default:
                            break;
                    }
                }

                // Activated by AutoPlay
                if (e.Parameter is DeviceActivatedEventArgs)
                {
                    this.arguments = e.Parameter as DeviceActivatedEventArgs;
                    bool importSupported = await PhotoImportManager.IsSupportedAsync();
                    this.sourceListBox.Items.Clear();

                    List<PhotoImportSource> source = new List<PhotoImportSource>();
                    
                    // Create the source from a device Id
                    source.Add(await PhotoImportSource.FromIdAsync(this.arguments.DeviceInformationId));

                    // bind and preselects source
                    this.sourceListBox.ItemsSource = source;
                    this.sourceListBox.SelectedIndex = 0;

                    rootPage.NotifyUser("Device selected from AutoPlay", NotifyType.StatusMessage);
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser("Exception: " + ex.ToString(), NotifyType.ErrorMessage);
            }
        }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            // It is recommended to only retrieve the m_shareOperation object in the activation handler, return as
            // quickly as possible, and retrieve all data from the share target asynchronously.

            m_shareOperation = (ShareOperation)e.Parameter;
            if (m_shareOperation == null)
            {
                return;
            }

            var result = await ProtectionPolicyManager.RequestAccessAsync(Scenario1.m_enterpriseId,
                                                                             m_shareOperation.Data.Properties.EnterpriseId);
            if (result == ProtectionPolicyEvaluationResult.Blocked)
            {
                rootPage.NotifyUser("\nSharing is blocked by policy from your Enterprise", NotifyType.ErrorMessage);
            }

            await Task.Factory.StartNew(async () =>
            {
                // Retrieve the data package properties.
                m_sharedDataTitle = m_shareOperation.Data.Properties.Title;
                m_sharedDataDescription = m_shareOperation.Data.Properties.Description;
                m_sharedDataPackageFamilyName = m_shareOperation.Data.Properties.PackageFamilyName;
                m_sharedDataContentSourceWebLink = m_shareOperation.Data.Properties.ContentSourceWebLink;
                m_sharedDataContentSourceApplicationLink = m_shareOperation.Data.Properties.ContentSourceApplicationLink;
                m_sharedDataLogoBackgroundColor = m_shareOperation.Data.Properties.LogoBackgroundColor;
                m_sharedDataSquare30x30Logo = m_shareOperation.Data.Properties.Square30x30Logo;
                m_sharedThumbnailStreamRef = m_shareOperation.Data.Properties.Thumbnail;
                shareQuickLinkId = m_shareOperation.QuickLinkId;

                // Retrieve the data package content.
                // The GetWebLinkAsync(), GetTextAsync(), GetStorageItemsAsync(), etc. APIs will throw if there was an error retrieving the data from the source app.
                // In this sample, we just display the error. It is recommended that a share target app handles these in a way appropriate for that particular app.
                if (m_shareOperation.Data.Contains(StandardDataFormats.WebLink))
                {
                    try
                    {
                        m_sharedWebLink = await m_shareOperation.Data.GetWebLinkAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetWebLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }
                if (m_shareOperation.Data.Contains(StandardDataFormats.ApplicationLink))
                {
                    try
                    {
                        m_sharedApplicationLink = await m_shareOperation.Data.GetApplicationLinkAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetApplicationLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }
                if (m_shareOperation.Data.Contains(StandardDataFormats.Text))
                {
                    try
                    {
                        m_sharedText = await m_shareOperation.Data.GetTextAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetTextAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }
                if (m_shareOperation.Data.Contains(StandardDataFormats.StorageItems))
                {
                    try
                    {
                        m_sharedStorageItems = await m_shareOperation.Data.GetStorageItemsAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetStorageItemsAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }
                if (m_shareOperation.Data.Contains(dataFormatName))
                {
                    try
                    {
                        m_sharedCustomData = await m_shareOperation.Data.GetTextAsync(dataFormatName);
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetTextAsync(" + dataFormatName + ") - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }
                if (m_shareOperation.Data.Contains(StandardDataFormats.Html))
                {
                    try
                    {
                        m_sharedHtmlFormat = await m_shareOperation.Data.GetHtmlFormatAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetHtmlFormatAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }

                    try
                    {
                        m_sharedResourceMap = await m_shareOperation.Data.GetResourceMapAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetResourceMapAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }
                if (m_shareOperation.Data.Contains(StandardDataFormats.Bitmap))
                {
                    try
                    {
                        m_sharedBitmapStreamRef = await m_shareOperation.Data.GetBitmapAsync();
                    }
                    catch (Exception ex)
                    {
                        NotifyUserBackgroundThread("Failed GetBitmapAsync - " + ex.Message, NotifyType.ErrorMessage);
                    }
                }

                // In this sample, we just display the m_shared data content.

                // Get back to the UI thread using the dispatcher.
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                {
                    DataPackageTitle.Text = m_sharedDataTitle;
                    DataPackageDescription.Text = m_sharedDataDescription;
                    DataPackagePackageFamilyName.Text = m_sharedDataPackageFamilyName;
                    if (m_sharedDataContentSourceWebLink != null)
                    {
                        DataPackageContentSourceWebLink.Text = m_sharedDataContentSourceWebLink.AbsoluteUri;
                    }
                    if (m_sharedDataContentSourceApplicationLink != null)
                    {
                        DataPackageContentSourceApplicationLink.Text = m_sharedDataContentSourceApplicationLink.AbsoluteUri;
                    }

                    if (m_sharedDataSquare30x30Logo != null)
                    {
                        IRandomAccessStreamWithContentType logoStream = await m_sharedDataSquare30x30Logo.OpenReadAsync();
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(logoStream);
                        LogoHolder.Source = bitmapImage;
                        LogoBackground.Background = new SolidColorBrush(m_sharedDataLogoBackgroundColor);
                        LogoArea.Visibility = Visibility.Visible;
                    }

                    if (!String.IsNullOrEmpty(m_shareOperation.QuickLinkId))
                    {
                        SelectedQuickLinkId.Text = shareQuickLinkId;
                    }

                    if (m_sharedThumbnailStreamRef != null)
                    {
                        IRandomAccessStreamWithContentType thumbnailStream = await m_sharedThumbnailStreamRef.OpenReadAsync();
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(thumbnailStream);
                        ThumbnailHolder.Source = bitmapImage;
                        ThumbnailArea.Visibility = Visibility.Visible;
                    }

                    if (m_sharedWebLink != null)
                    {
                        AddContentValue("WebLink: ", m_sharedWebLink.AbsoluteUri);
                    }
                    if (m_sharedApplicationLink != null)
                    {
                        AddContentValue("ApplicationLink: ", m_sharedApplicationLink.AbsoluteUri);
                    }
                    if (m_sharedText != null)
                    {
                        AddContentValue("Text: ", m_sharedText);
                    }
                    if (m_sharedStorageItems != null)
                    {
                        // Display the name of the files being m_shared.
                        StringBuilder fileNames = new StringBuilder();
                        for (int index = 0; index < m_sharedStorageItems.Count; index++)
                        {
                            fileNames.Append(m_sharedStorageItems[index].Name);
                            if (index < m_sharedStorageItems.Count - 1)
                            {
                                fileNames.Append(", ");
                            }
                        }
                        fileNames.Append(".");

                        AddContentValue("StorageItems: ", fileNames.ToString());
                    }
                    if (m_sharedCustomData != null)
                    {
                        // This is an area to be especially careful parsing data from the source app to avoid buffer overruns.
                        // This sample doesn't perform data validation but will catch any exceptions thrown.
                        try
                        {
                            StringBuilder receivedStrings = new StringBuilder();
                            JsonObject customObject = JsonObject.Parse(m_sharedCustomData);
                            if (customObject.ContainsKey("type"))
                            {
                                if (customObject["type"].GetString() == "http://schema.org/Book")
                                {
                                    // This sample expects the custom format to be of type http://schema.org/Book
                                    receivedStrings.AppendLine("Type: " + customObject["type"].Stringify());
                                    JsonObject properties = customObject["properties"].GetObject();
                                    receivedStrings.AppendLine("Image: " + properties["image"].Stringify());
                                    receivedStrings.AppendLine("Name: " + properties["name"].Stringify());
                                    receivedStrings.AppendLine("Book Format: " + properties["bookFormat"].Stringify());
                                    receivedStrings.AppendLine("Author: " + properties["author"].Stringify());
                                    receivedStrings.AppendLine("Number of Pages: " + properties["numberOfPages"].Stringify());
                                    receivedStrings.AppendLine("Publisher: " + properties["publisher"].Stringify());
                                    receivedStrings.AppendLine("Date Published: " + properties["datePublished"].Stringify());
                                    receivedStrings.AppendLine("In Language: " + properties["inLanguage"].Stringify());
                                    receivedStrings.Append("ISBN: " + properties["isbn"].Stringify());

                                    AddContentValue("Custom format data:" + Environment.NewLine, receivedStrings.ToString());
                                }
                                else
                                {
                                    rootPage.NotifyUser("The custom format from the source app is not of type http://schema.org/Book", NotifyType.ErrorMessage);
                                }
                            }
                            else
                            {
                                rootPage.NotifyUser("The custom format from the source app doesn't contain a type", NotifyType.ErrorMessage);
                            }
                        }
                        catch (Exception ex)
                        {
                            rootPage.NotifyUser("Failed to parse the custom data - " + ex.Message, NotifyType.ErrorMessage);
                        }
                    }
                    if (m_sharedHtmlFormat != null)
                    {
                        string htmlFragment = HtmlFormatHelper.GetStaticFragment(m_sharedHtmlFormat);
                        if (!String.IsNullOrEmpty(htmlFragment))
                        {
                            AddContentValue("HTML: ");
                            ShareWebView.Visibility = Visibility.Visible;
                            ShareWebView.NavigateToString("<html><body>" + htmlFragment + "</body></html>");
                        }
                        else
                        {
                            rootPage.NotifyUser("GetStaticFragment failed to parse the HTML from the source app", NotifyType.ErrorMessage);
                        }

                        // Check if there are any local images in the resource map.
                        if (m_sharedResourceMap.Count > 0)
                        {
                            //ResourceMapValue.Text = "";
                            foreach (KeyValuePair<string, RandomAccessStreamReference> item in m_sharedResourceMap)
                            {
                                ResourceMapValue.Text += "\nKey: " + item.Key;
                            }
                            ResourceMapArea.Visibility = Visibility.Visible;
                        }
                    }
                    if (m_sharedBitmapStreamRef != null)
                    {
                        IRandomAccessStreamWithContentType bitmapStream = await m_sharedBitmapStreamRef.OpenReadAsync();
                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(bitmapStream);
                        ImageHolder.Source = bitmapImage;
                        ImageArea.Visibility = Visibility.Visible;
                    }
                });
            });
        }
        private async void PurchaseAddOnButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            var item = (ItemDetails)ProductsListView.SelectedItem;

            StorePurchaseResult result = await storeContext.RequestPurchaseAsync(item.StoreId);

            if (result.ExtendedError != null)
            {
                Utils.ReportExtendedError(result.ExtendedError);
                return;
            }

            switch (result.Status)
            {
            case StorePurchaseStatus.AlreadyPurchased:     // should never get this for a managed consumable since they are stackable
                rootPage.NotifyUser($"You already bought this consumable.", NotifyType.ErrorMessage);
                break;

            case StorePurchaseStatus.Succeeded:
                rootPage.NotifyUser($"You bought {item.Title}.", NotifyType.StatusMessage);
                break;

            case StorePurchaseStatus.NotPurchased:
                rootPage.NotifyUser("Product was not purchased, it may have been canceled.", NotifyType.ErrorMessage);
                break;

            case StorePurchaseStatus.NetworkError:
                rootPage.NotifyUser("Product was not purchased due to a network error.", NotifyType.ErrorMessage);
                break;

            case StorePurchaseStatus.ServerError:
                rootPage.NotifyUser("Product was not purchased due to a server error.", NotifyType.ErrorMessage);
                break;

            default:
                rootPage.NotifyUser("Product was not purchased due to an unknown error.", NotifyType.ErrorMessage);
                break;
            }
        }
Esempio n. 15
0
        private async void CreateFileButton_Click(object sender, RoutedEventArgs e)
        {
            rootPage.NotifyUser("", NotifyType.StatusMessage);

            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;

            savePicker.FileTypeChoices.Add("Plain Text", new string[] { ".txt" });
            savePicker.SuggestedFileName = "New Document";

            m_afterWriteFile = await savePicker.PickSaveFileAsync();

            if (m_afterWriteFile != null)
            {
                rootPage.NotifyUser("File created.", NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser("Operation cancelled.", NotifyType.ErrorMessage);
            }
            UpdateButtons();
        }
Esempio n. 16
0
        protected override async void OnNavigatedFrom(NavigationEventArgs e)
        {
            var success = await ClearBluetoothLEDeviceAsync();

            if (!success)
            {
                rootPage.NotifyUser("Error: Unable to reset app state", NotifyType.ErrorMessage);
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            await MainPage.ConfigureSimulatorAsync("in-app-purchase-consumables.xml");

            try
            {
                ListingInformation listing = await CurrentAppSimulator.LoadListingInformationAsync();

                var product1 = listing.ProductListings["product1"];
                Product1Name.Text  = product1.Name;
                Product1Price.Text = product1.FormattedPrice;
                rootPage.NotifyUser("", NotifyType.StatusMessage);
            }
            catch (Exception)
            {
                rootPage.NotifyUser("LoadListingInformationAsync API call failed", NotifyType.ErrorMessage);
            }
        }
 /// <summary>
 /// Callback function for the invocation of the dialog commands.
 /// </summary>
 /// <param name="command">The command that was invoked.</param>
 private void CommandInvokedHandler(IUICommand command)
 {
     // Display message showing the label of the command that was invoked
     rootPage.NotifyUser("The '" + command.Label + "' command has been selected.", NotifyType.StatusMessage);
 }
        public Scenario1_DeviceUse()
        {
            this.InitializeComponent();

            Accelerometer = Accelerometer.GetDefault();
            if (null != Accelerometer)
            {
                // Save trigger so that we may start the background task later.
                // Only one instance of the trigger can exist at a time. Since the trigger does not implement
                // IDisposable, it may still be in memory when a new trigger is created.
                _deviceUseTrigger = new DeviceUseTrigger();

                // Setup a timer to periodically refresh results when the app is visible.
                _refreshTimer = new DispatcherTimer()
                {
                    Interval = new TimeSpan(0, 0, 1) // Refresh once every second
                };
                _refreshTimer.Tick += RefreshTimer_Tick;
            }
            else
            {
                rootPage.NotifyUser("No accelerometer found", NotifyType.StatusMessage);
            }
        }
Esempio n. 20
0
        private void btnStartAdvertisement_Click(object sender, RoutedEventArgs e)
        {
            _publisher = new WiFiDirectAdvertisementPublisher();
            _publisher.StatusChanged += OnStatusChanged;

            _listener = new WiFiDirectConnectionListener();

            if (chkListener.IsChecked.Value)
            {
                try
                {
                    // This can raise an exception if the machine does not support WiFi. Sorry.
                    _listener.ConnectionRequested += OnConnectionRequested;
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser($"Error preparing Advertisement: {ex}", NotifyType.ErrorMessage);
                    return;
                }
            }

            var discoverability = Utils.GetSelectedItemTag <WiFiDirectAdvertisementListenStateDiscoverability>(cmbListenState);

            _publisher.Advertisement.ListenStateDiscoverability = discoverability;

            _publisher.Advertisement.IsAutonomousGroupOwnerEnabled = chkPreferGroupOwnerMode.IsChecked.Value;

            // Legacy settings are meaningful only if IsAutonomousGroupOwnerEnabled is true.
            if (_publisher.Advertisement.IsAutonomousGroupOwnerEnabled && chkLegacySetting.IsChecked.Value)
            {
                _publisher.Advertisement.LegacySettings.IsEnabled = true;
                if (!String.IsNullOrEmpty(txtPassphrase.Text))
                {
                    var creds = new Windows.Security.Credentials.PasswordCredential();
                    creds.Password = txtPassphrase.Text;
                    _publisher.Advertisement.LegacySettings.Passphrase = creds;
                }

                if (!String.IsNullOrEmpty(txtSsid.Text))
                {
                    _publisher.Advertisement.LegacySettings.Ssid = txtSsid.Text;
                }
            }

            // Add the information elements.
            foreach (WiFiDirectInformationElement informationElement in _informationElements)
            {
                _publisher.Advertisement.InformationElements.Add(informationElement);
            }

            _publisher.Start();

            if (_publisher.Status == WiFiDirectAdvertisementPublisherStatus.Started)
            {
                btnStartAdvertisement.IsEnabled = false;
                btnStopAdvertisement.IsEnabled  = true;
                rootPage.NotifyUser("Advertisement started.", NotifyType.StatusMessage);
            }
            else
            {
                rootPage.NotifyUser($"Advertisement failed to start. Status is {_publisher.Status}", NotifyType.ErrorMessage);
            }
        }
Esempio n. 21
0
        private async void ShowProperties()
        {
            var selectedUser = (UserViewModel)UserList.SelectedValue;

            if (selectedUser != null)
            {
                ResultsText.Text    = "";
                ProfileImage.Source = null;
                rootPage.NotifyUser("", NotifyType.StatusMessage);
                try
                {
                    User    user = User.GetFromId(selectedUser.UserId);
                    IBuffer aa   = SystemIdentification.GetSystemIdForUser(user).Id;
                    IBuffer bb   = SystemIdentification.GetSystemIdForUser(null).Id;
                    var     aaS  = SystemIdentification.GetSystemIdForUser(user).Id.ToArray();
                    var     bbS  = SystemIdentification.GetSystemIdForUser(null).Id.ToArray();

                    Debug.WriteLine("!!!" + aa + "~~~~~~~~~" + bb);
                    // Start with some fixed properties.
                    String result = "NonRoamableId: " + user.NonRoamableId + "\n";
                    result += "Type: " + user.Type.ToString() + "\n";
                    result += "AuthenticationStatus: " + user.AuthenticationStatus.ToString() + "\n";

                    // Build a list of all the properties we want.
                    String[] desiredProperties = new String[]
                    {
                        KnownUserProperties.FirstName,
                        KnownUserProperties.LastName,
                        KnownUserProperties.ProviderName,
                        KnownUserProperties.AccountName,
                        KnownUserProperties.GuestHost,
                        KnownUserProperties.PrincipalName,
                        KnownUserProperties.DomainName,
                        KnownUserProperties.SessionInitiationProtocolUri,
                    };
                    // Issue a bulk query for all of the properties.
                    IPropertySet values = await user.GetPropertiesAsync(desiredProperties);

                    // Add those properties to our results.
                    foreach (String property in desiredProperties)
                    {
                        result += property + ": " + values[property] + "\n";
                    }
                    ResultsText.Text = result;

                    // Get the user's picture.
                    IRandomAccessStreamReference streamReference = await user.GetPictureAsync(UserPictureSize.Size64x64);

                    if (streamReference != null)
                    {
                        IRandomAccessStream stream = await streamReference.OpenReadAsync();

                        BitmapImage bitmapImage = new BitmapImage();
                        bitmapImage.SetSource(stream);
                        ProfileImage.Source = bitmapImage;
                    }
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                }
            }
        }
        private async void GenerateRandomNumber_Click(object sender, RoutedEventArgs e)
        {
            //Parse user input
            int  minValueInput = 0;
            bool valueParsed   = int.TryParse(MinValue.Text, out minValueInput);

            if (!valueParsed)
            {
                rootPage.NotifyUser("The Minimum Value should be a valid integer", NotifyType.ErrorMessage);
                return;
            }

            int maxValueInput = 0;

            valueParsed = int.TryParse(MaxValue.Text, out maxValueInput);
            if (!valueParsed)
            {
                rootPage.NotifyUser("The Maximum Value should be a valid integer", NotifyType.ErrorMessage);
                return;
            }

            if (maxValueInput <= minValueInput)
            {
                rootPage.NotifyUser("Maximum Value must be larger than Minimum Value", NotifyType.ErrorMessage);
                return;
            }

            using (var connection = new AppServiceConnection())
            {
                //Set up a new app service connection
                connection.AppServiceName    = "com.microsoft.randomnumbergenerator";
                connection.PackageFamilyName = "Microsoft.SDKSamples.AppServicesProvider.CS_8wekyb3d8bbwe";
                AppServiceConnectionStatus status = await connection.OpenAsync();

                switch (status)
                {
                case AppServiceConnectionStatus.Success:
                    // The new connection opened successfully
                    rootPage.NotifyUser("Connection established", NotifyType.StatusMessage);
                    break;

                case AppServiceConnectionStatus.AppNotInstalled:
                    rootPage.NotifyUser("The app AppServicesProvider is not installed. Deploy AppServicesProvider to this device and try again.", NotifyType.ErrorMessage);
                    return;

                case AppServiceConnectionStatus.AppUnavailable:
                    rootPage.NotifyUser("The app AppServicesProvider is not available. This could be because it is currently being updated or was installed to a removable device that is no longer available.", NotifyType.ErrorMessage);
                    return;

                case AppServiceConnectionStatus.AppServiceUnavailable:
                    rootPage.NotifyUser($"The app AppServicesProvider is installed but it does not provide the app service {connection.AppServiceName}", NotifyType.ErrorMessage);
                    return;

                default:
                case AppServiceConnectionStatus.Unknown:
                    rootPage.NotifyUser("An unknown error occurred while we were trying to open an AppServiceConnection.", NotifyType.ErrorMessage);
                    return;
                }

                //Set up the inputs and send a message to the service
                var inputs = new ValueSet();
                inputs.Add("minvalue", minValueInput);
                inputs.Add("maxvalue", maxValueInput);
                AppServiceResponse response = await connection.SendMessageAsync(inputs);

                //If the service responded with success display the result and walk away
                if (response.Status == AppServiceResponseStatus.Success &&
                    response.Message.ContainsKey("result"))
                {
                    var resultText = response.Message["result"].ToString();
                    if (!string.IsNullOrEmpty(resultText))
                    {
                        Result.Text = resultText;
                        rootPage.NotifyUser("App service responded with a result", NotifyType.StatusMessage);
                    }
                    else
                    {
                        rootPage.NotifyUser("App service did not respond with a result", NotifyType.ErrorMessage);
                    }

                    return;
                }

                //Something went wrong while sending a message. Let display
                //a meaningful error message
                switch (response.Status)
                {
                case AppServiceResponseStatus.Failure:
                    rootPage.NotifyUser("The service failed to acknowledge the message we sent it. It may have been terminated or it's RequestReceived handler might not be handling incoming messages correctly.", NotifyType.ErrorMessage);
                    return;

                case AppServiceResponseStatus.ResourceLimitsExceeded:
                    rootPage.NotifyUser("The service exceeded the resources allocated to it and had to be terminated.", NotifyType.ErrorMessage);
                    return;

                default:
                case AppServiceResponseStatus.Unknown:
                    rootPage.NotifyUser("An unknown error occurred while we were trying to send a message to the service.", NotifyType.ErrorMessage);
                    return;
                }
            }
        }
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     rootPage = MainPage.Current;
     rootPage.NotifyUser("Windows Phone doesn’t currently support this function.", NotifyType.ErrorMessage);
 }
 private void UpdateStatus(string status, NotifyType statusType)
 {
     m_rootPage.NotifyUser(status, statusType);
 }
Esempio n. 25
0
        /// <summary>
        /// Starts previewing the selected scanner's video feed and prevents the display from going to sleep.
        /// </summary>
        private async Task StartMediaCaptureAsync(string videoDeviceId)
        {
            mediaCapture = new MediaCapture();

            // Register for a notification when something goes wrong
            mediaCapture.Failed += MediaCapture_Failed;

            var settings = new MediaCaptureInitializationSettings
            {
                VideoDeviceId        = videoDeviceId,
                StreamingCaptureMode = StreamingCaptureMode.Video,
            };

            // Initialize MediaCapture
            bool captureInitialized = false;

            try
            {
                await mediaCapture.InitializeAsync(settings);

                captureInitialized = true;
            }
            catch (UnauthorizedAccessException)
            {
                rootPage.NotifyUser("The app was denied access to the camera", NotifyType.ErrorMessage);
            }
            catch (Exception e)
            {
                rootPage.NotifyUser("Failed to initialize the camera: " + e.Message, NotifyType.ErrorMessage);
            }

            if (captureInitialized)
            {
                // Prevent the device from sleeping while the preview is running.
                displayRequest.RequestActive();

                PreviewControl.Source = mediaCapture;
                await mediaCapture.StartPreviewAsync();
                await SetPreviewRotationAsync(DisplayInformation.GetForCurrentView().CurrentOrientation);

                IsPreviewing = true;
                RaisePropertyChanged(nameof(IsPreviewing));
            }
            else
            {
                mediaCapture.Dispose();
                mediaCapture = null;
            }

            //check if cart is active
            //if so, start capturing

            //NEW CODE
            if (claimedScanner != null)
            {
                await claimedScanner.StartSoftwareTriggerAsync();

                SoftwareTriggerStarted = true;
                RaisePropertyChanged(nameof(SoftwareTriggerStarted));
            }
        }
        private void btnWatcher_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            if (_fWatcherStarted == false)
            {
                btnWatcher.Content = "Stop Watcher";
                _fWatcherStarted   = true;

                _discoveredDevices.Clear();
                rootPage.NotifyUser("Finding Devices...", NotifyType.StatusMessage);

                _deviceWatcher = null;
                String deviceSelector = WiFiDirectDevice.GetDeviceSelector((cmbDeviceSelector.ToString().Equals("Device Interface") == true) ?
                                                                           WiFiDirectDeviceSelectorType.DeviceInterface : WiFiDirectDeviceSelectorType.AssociationEndpoint);

                _deviceWatcher = DeviceInformation.CreateWatcher(deviceSelector, new string[] { "System.Devices.WiFiDirect.InformationElements" });

                _deviceWatcher.Added   += OnDeviceAdded;
                _deviceWatcher.Removed += OnDeviceRemoved;
                _deviceWatcher.Updated += OnDeviceUpdated;
                _deviceWatcher.EnumerationCompleted += OnEnumerationCompleted;
                _deviceWatcher.Stopped += OnStopped;

                _deviceWatcher.Start();
            }
            else
            {
                btnWatcher.Content = "Start Watcher";
                _fWatcherStarted   = false;

                _deviceWatcher.Added   -= OnDeviceAdded;
                _deviceWatcher.Removed -= OnDeviceRemoved;
                _deviceWatcher.Updated -= OnDeviceUpdated;
                _deviceWatcher.EnumerationCompleted -= OnEnumerationCompleted;
                _deviceWatcher.Stopped -= OnStopped;

                _deviceWatcher.Stop();
            }
        }
Esempio n. 27
0
        private async Task ConnectAsync()
        {
            if (String.IsNullOrEmpty(InputField.Text))
            {
                rootPage.NotifyUser("Please specify text to send", NotifyType.ErrorMessage);
                return;
            }

            // Validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling TryGetUri() that will return null for strings that are not
            // valid WebSocket URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet
            // or intErnet. In these cases the app requires the "Private Networks (Client and Server)" or
            // "Internet (Client)" capability respectively.
            Uri server = rootPage.TryGetUri(ServerAddressField.Text);

            if (server == null)
            {
                return;
            }

            messageWebSocket = new MessageWebSocket();
            messageWebSocket.Control.MessageType = SocketMessageType.Utf8;
            messageWebSocket.MessageReceived    += MessageReceived;
            messageWebSocket.Closed += OnClosed;

            // If we are connecting to wss:// endpoint, by default, the OS performs validation of
            // the server certificate based on well-known trusted CAs. We can perform additional custom
            // validation if needed.
            if (SecureWebSocketCheckBox.IsChecked == true)
            {
                // WARNING: Only test applications should ignore SSL errors.
                // In real applications, ignoring server certificate errors can lead to Man-In-The-Middle
                // attacks. (Although the connection is secure, the server is not authenticated.)
                // Note that not all certificate validation errors can be ignored.
                // In this case, we are ignoring these errors since the certificate assigned to the localhost
                // URI is self-signed and has subject name = fabrikam.com
                messageWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                messageWebSocket.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);

                // Add event handler to listen to the ServerCustomValidationRequested event. This enables performing
                // custom validation of the server certificate. The event handler must implement the desired
                // custom certificate validation logic.
                messageWebSocket.ServerCustomValidationRequested += OnServerCustomValidationRequested;

                // Certificate validation occurs only for secure connections.
                if (server.Scheme != "wss")
                {
                    AppendOutputLine("Note: Certificate validation is performed only for the wss: scheme.");
                }
            }

            AppendOutputLine($"Connecting to {server}...");
            try
            {
                await messageWebSocket.ConnectAsync(server);
            }
            catch (Exception ex) // For debugging
            {
                // Error happened during connect operation.
                messageWebSocket.Dispose();
                messageWebSocket = null;

                AppendOutputLine(MainPage.BuildWebSocketError(ex));
                AppendOutputLine(ex.Message);
                return;
            }

            // The default DataWriter encoding is Utf8.
            messageWriter = new DataWriter(messageWebSocket.OutputStream);
            rootPage.NotifyUser("Connected", NotifyType.StatusMessage);
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        ///
        /// We will enable/disable parts of the UI if the device doesn't support it.
        /// </summary>
        /// <param name="eventArgs">Event data that describes how this page was reached. The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            // Attach a handler to process the received advertisement. 
            // The watcher cannot be started without a Received handler attached
            watcher.Received += OnAdvertisementReceived;

            // Attach a handler to process watcher stopping due to various conditions,
            // such as the Bluetooth radio turning off or the Stop method was called
            watcher.Stopped += OnAdvertisementWatcherStopped;

            // Attach handlers for suspension to stop the watcher when the App is suspended.
            App.Current.Suspending += App_Suspending;
            App.Current.Resuming += App_Resuming;

            rootPage.NotifyUser("Press Run to start watcher.", NotifyType.StatusMessage);
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        ///
        /// We will enable/disable parts of the UI if the device doesn't support it.
        /// </summary>
        /// <param name="eventArgs">Event data that describes how this page was reached. The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            rootPage = MainPage.Current;

            // Attach a event handler to monitor the status of the publisher, which
            // can tell us whether the advertising has been serviced or is waiting to be serviced
            // due to lack of resources. It will also inform us of unexpected errors such as the Bluetooth
            // radio being turned off by the user.
            publisher.StatusChanged += OnPublisherStatusChanged;

            // Attach handlers for suspension to stop the publisher when the App is suspended.
            App.Current.Suspending += App_Suspending;
            App.Current.Resuming += App_Resuming;

            rootPage.NotifyUser("Press Run to start publisher.", NotifyType.StatusMessage);
        }
        private async void ConnectButton_Click()
        {
            ConnectButton.IsEnabled = false;

            ClearBluetoothLEDevice();
            try
            {
                // BT_Code: BluetoothLEDevice.FromIdAsync must be called from a UI thread because it may prompt for consent.
                bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(rootPage.SelectedBleDeviceId);
            }
            catch (Exception ex) when((uint)ex.HResult == 0x800710df)
            {
                // ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on.
            }

            if (bluetoothLeDevice != null)
            {
                // BT_Code: GattServices returns a list of all the supported services of the device.
                // If the services supported by the device are expected to change
                // during BT usage, subscribe to the GattServicesChanged event.
                foreach (var service in bluetoothLeDevice.GattServices)
                {
                    ServiceCollection.Add(new BluetoothLEAttributeDisplay(service));
                }
                ConnectButton.Visibility = Visibility.Collapsed;
                ServiceList.Visibility   = Visibility.Visible;
            }
            else
            {
                ClearBluetoothLEDevice();
                rootPage.NotifyUser("Failed to connect to device.", NotifyType.ErrorMessage);
            }
            ConnectButton.IsEnabled = true;
        }
Esempio n. 31
0
 private void InkPresenter_StrokesErased(InkPresenter sender, InkStrokesErasedEventArgs args)
 {
     rootPage.NotifyUser(args.Strokes.Count + " stroke(s) erased!", NotifyType.StatusMessage);
 }
Esempio n. 32
0
        private async void PublishButton_ClickAsync()
        {
            // Server not initialized yet - initialize it and start publishing
            if (serviceProvider == null)
            {
                var serviceStarted = await ServiceProviderInitAsync();

                if (serviceStarted)
                {
                    rootPage.NotifyUser("Service successfully started", NotifyType.StatusMessage);
                    PublishButton.Content = "Stop Service";
                }
                else
                {
                    rootPage.NotifyUser("Service not started", NotifyType.ErrorMessage);
                }
            }
            else
            {
                // BT_Code: Stops advertising support for custom GATT Service
                serviceProvider.StopAdvertising();
                serviceProvider       = null;
                PublishButton.Content = "Start Service";
            }
        }
Esempio n. 33
0
        private async void Start_Click(object sender, RoutedEventArgs e)
        {
            Uri resourceUri;

            // The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
            // valid, absolute URI, we'll notify the user about the incorrect input.
            if (!Helpers.TryGetUri(AddressField.Text, out resourceUri))
            {
                rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
                return;
            }

            Helpers.ScenarioStarted(StartButton, CancelButton, OutputField);
            rootPage.NotifyUser("In progress", NotifyType.StatusMessage);

            if (ReadDefaultRadio.IsChecked.Value)
            {
                filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.Default;
            }
            else if (ReadMostRecentRadio.IsChecked.Value)
            {
                filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
            }
            else if (ReadOnlyFromCacheRadio.IsChecked.Value)
            {
                filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.OnlyFromCache;
            }
            else if (ReadNoCacheRadio.IsChecked.Value)
            {
                filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.NoCache;
            }

            if (WriteDefaultRadio.IsChecked.Value)
            {
                filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.Default;
            }
            else if (WriteNoCacheRadio.IsChecked.Value)
            {
                filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
            }

            // ---------------------------------------------------------------------------
            // WARNING: Only test applications should ignore SSL errors.
            // In real applications, ignoring server certificate errors can lead to MITM
            // attacks (while the connection is secure, the server is not authenticated).
            //
            // The SetupServer script included with this sample creates a server certificate that is self-signed
            // and issued to fabrikam.com, and hence we need to ignore these errors here.
            // ---------------------------------------------------------------------------
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
            filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);

            // This sample uses a "try" in order to support TaskCanceledException.
            // If you don't need to support cancellation, then the "try" is not needed.
            try
            {
                HttpRequestResult result = await httpClient.TryGetAsync(resourceUri).AsTask(cts.Token);

                if (result.Succeeded)
                {
                    isFilterUsed = true;

                    await Helpers.DisplayTextResultAsync(result.ResponseMessage, OutputField, cts.Token);

                    rootPage.NotifyUser(
                        "Completed. Response came from " + result.ResponseMessage.Source + ". HTTP version used: " + result.ResponseMessage.Version.ToString() + ".",
                        NotifyType.StatusMessage);
                }
                else
                {
                    Helpers.DisplayWebError(rootPage, result.ExtendedError);
                }
            }
            catch (TaskCanceledException)
            {
                rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
            }

            Helpers.ScenarioCompleted(StartButton, CancelButton);
        }