Ejemplo n.º 1
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var details = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;
            string arguments = details.Argument;
            var result = details.UserInput;

            if (arguments == "check")
            {
                int sum = int.Parse(result["message"].ToString());
                string message = sum == 15 ? "Congratulations, the answer is correct!" : "Sorry, wrong answer!";

                string xml = $@"<toast>
                              <visual>
                                <binding template=""ToastGeneric"">
                                  <image placement=""appLogoOverride"" src=""Assets/MicrosoftLogo.png"" />
                                  <text>{message}</text>
                                </binding>
                              </visual>
                            </toast>";

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);

                ToastNotification notification = new ToastNotification(doc);
                ToastNotificationManager.CreateToastNotifier().Show(notification);
            }
        }
        private async void DoBufferWork(IBackgroundTaskInstance taskInstance)
        {
            string message = "Hello World!";
            string unprotectedMessage = "";
            string logFileName = "Bufferlog.txt";
            string logFileContent = "";

            StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            StorageFile logFile = await localFolder.CreateFileAsync(logFileName, CreationCollisionOption.OpenIfExists);


            IBuffer inputBuffer = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8);
            BufferProtectUnprotectResult procBuffer = await DataProtectionManager.ProtectAsync(inputBuffer, m_EnterpriseID);
            logFileContent += "\r\n" + DateTime.Now + ":" + "ProtStatus:" + procBuffer.ProtectionInfo.Status + "\n";
            logFileContent += "\r\n" + "Protected Buffer:" + CryptographicBuffer.EncodeToHexString(procBuffer.Buffer).Substring(0, 5);

            // If keys are dropped under lock, unprotectBuffer will fail so don't unprotectbuffer under lock
            if (!m_areKeysDropped)
            {
                BufferProtectUnprotectResult unBuffer = await DataProtectionManager.UnprotectAsync(procBuffer.Buffer);
                unprotectedMessage = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, procBuffer.Buffer);
                logFileContent += "\n Unprotected string:" + unprotectedMessage;
                if (message != unprotectedMessage)
                {
                    throw new Exception("Original string does not match with unprotectedMessage!");
                }
            }

            await FileIO.AppendTextAsync(logFile, logFileContent);

        }
Ejemplo n.º 3
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            AddQuestionsResult result = null;
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            #if DEBUG
            InvokeSimpleToast("Hello from " + taskInstance.Task.Name);
            #endif

            try
            {
                result = await FeedManager.QueryWebsitesAsync();

                #if DEBUG
                InvokeSimpleToast(String.Format(
                    "There are {0} new questions and {1} updated questions.",
                    result.AddedQuestions,
                    result.UpdatedQuestions));
                #endif
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);

                #if DEBUG
                InvokeSimpleToast(ex.Message);
                #endif
            }

            deferral.Complete();
        }
Ejemplo n.º 4
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // Ensure our background task remains running
            taskDeferral = taskInstance.GetDeferral();

            // Mutex will be used to ensure only one thread at a time is talking to the shield / isolated storage
            mutex = new Mutex(false, mutexId);

            // Initialize WeatherShield
            await shield.BeginAsync();

            //Initialise the MCP3008 ADC Chip
            mcp3008.Initialize();

            // Create a timer-initiated ThreadPool task to read data from I2C
            i2cTimer = ThreadPoolTimer.CreatePeriodicTimer(PopulateWeatherData, TimeSpan.FromSeconds(i2cReadIntervalSeconds));

            //Create a timer-initiated ThreadPool task to read data from the interrupt handler counting the wind instrument activity
            windInterruptSample = ThreadPoolTimer.CreatePeriodicTimer(MeasureWindEventData, TimeSpan.FromSeconds(windInterruptSampleInterval));

            // Task cancellation handler, release our deferral there 
            taskInstance.Canceled += OnCanceled;

            //Create the interrupt handler listening to the wind speed pin (13).  Triggers the GpioPin.ValueChanged event on that pin 
            //connected to the anemometer.
            shield.WindSpeedPin.ValueChanged += WindSpeedPin_ValueChanged;

            //Create the interrupt handler listening to the rain guage pin (26).  Triggers the Gpio.ValueChanged event on that pin
            //connected to the rain guage. 
            shield.RainPin.ValueChanged += RainPin_ValueChanged;
    }
Ejemplo n.º 5
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();

            try
            {
                await Log.InfoAsync("Synchronization background task started");

                var authenticatedSilently = await SecurityManager.TryAuthenticateSilently();

                if (authenticatedSilently)
                {
                    IBackendServiceClient storage = new MobileServiceBackendServiceClient(new SyncHandler(), new EventManager(), new LocalSettingsService());
                    await storage.InitializeAsync();
                    await storage.TrySyncAsync();
                }
                else
                {
                    await Log.WarnAsync("Authentication failed.");
                }

                await Log.InfoAsync("Synchronization background task completed");
            }
            catch (Exception ex)
            {
                await ExceptionHandlingHelper.HandleNonFatalErrorAsync(ex, "Synchronization background task failed.", sendTelemetry: false);
            }
            finally
            {
                deferral.Complete();
            }
        }
        /// <summary>
        /// The entry point of a background task.
        /// </summary>
        /// <param name="taskInstance">The current background task instance.</param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");

            // Associate a cancellation handler with the background task.
            // Even though this task isn't performing much work, it can still be canceled.
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            // Read the sensor readings from the trigger reports
            SensorDataThresholdTriggerDetails triggerDetails = taskInstance.TriggerDetails as SensorDataThresholdTriggerDetails;
            // Ensure the type of trigger we are dealing with is of type 'ProximitySensor'
            if (SensorType.ProximitySensor == triggerDetails.SensorType)
            {
                var reports = ProximitySensor.GetReadingsFromTriggerDetails(triggerDetails);
                var settings = ApplicationData.Current.LocalSettings;
                var lastReading = reports[reports.Count - 1];

                // cache appropriate details from this trigger in application data
                settings.Values["ReportCount"] = reports.Count.ToString();
                settings.Values["LastTimestamp"] = lastReading.Timestamp.ToString("u");
                settings.Values["Detected"] = lastReading.IsDetected.ToString();
                settings.Values["TaskStatus"] = "Completed at " + DateTime.Now.ToString("u");
            }

            // No deferral is held on taskInstance because we are returning immediately.
        }
 public async void Run(IBackgroundTaskInstance taskInstance)
 {
     var deferral = taskInstance.GetDeferral();
     var updater = new LiveTileScheduler();
     await updater.CreateSchedule();
     deferral.Complete();
 }
Ejemplo n.º 8
0
 public async  void Run(IBackgroundTaskInstance taskInstance)
 {
     //通知
     ApplicationDataContainer container = ApplicationData.Current.LocalSettings;
     bool Update = true;
     if (container.Values["UpdateCT"]!=null)
     {
         Update = (bool)container.Values["UpdateCT"];
     }
     else
     {
         container.Values["UpdateCT"] = true;
     }
     if (Update)
     {
         var deferral = taskInstance.GetDeferral();
         await GetLatestNews();
         deferral.Complete();
     }
     else
     {
         var updater = TileUpdateManager.CreateTileUpdaterForApplication();
         updater.Clear();
     }
 }
Ejemplo n.º 9
0
        private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            this.SendToForeground(CommunicationConstants.BackgroundTaskStopped);

            try
            {
                ApplicationSettings.BackgroundTaskResumeSongTime.Save(BackgroundMediaPlayer.Current.Position.TotalSeconds);
                /*
                //save state
                ApplicationSettingsHelper.SaveSettingsValue(Constants.CurrentTrack, Playlist.CurrentTrackName);
                ApplicationSettingsHelper.SaveSettingsValue(Constants.Position, BackgroundMediaPlayer.Current.Position.ToString());
                ApplicationSettingsHelper.SaveSettingsValue(Constants.BackgroundTaskState, Constants.BackgroundTaskCancelled);
                ApplicationSettingsHelper.SaveSettingsValue(Constants.AppState, Enum.GetName(typeof(ForegroundAppStatus), foregroundAppState));
                backgroundtaskrunning = false;
                //unsubscribe event handlers
                systemmediatransportcontrol.ButtonPressed -= systemmediatransportcontrol_ButtonPressed;
                systemmediatransportcontrol.PropertyChanged -= systemmediatransportcontrol_PropertyChanged;
                Playlist.TrackChanged -= playList_TrackChanged;

                //clear objects task cancellation can happen uninterrupted
                playlistManager.ClearPlaylist();
                playlistManager = null;
                 */
                this.mediaControls.ButtonPressed -= mediaControls_ButtonPressed;
                playlistManager = null;

                BackgroundMediaPlayer.Shutdown(); // shutdown media pipeline
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
            if (_deferral != null)
                _deferral.Complete();
        }
Ejemplo n.º 10
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // Create the deferral by requesting it from the task instance
            serviceDeferral = taskInstance.GetDeferral();

            AppServiceTriggerDetails triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            if (triggerDetails != null && triggerDetails.Name.Equals("IMCommandVoice"))
            {
                voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);

                VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                // Perform the appropriate command depending on the operation defined in VCD
                switch (voiceCommand.CommandName)
                {
                    case "oldback":
                        VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage();
                        userMessage.DisplayMessage = "The current temperature is 23 degrees";
                        userMessage.SpokenMessage = "The current temperature is 23 degrees";

                        VoiceCommandResponse response = VoiceCommandResponse.CreateResponse(userMessage, null);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                        break;

                    default:
                        break;
                }
            }

            // Once the asynchronous method(s) are done, close the deferral
            serviceDeferral.Complete();
        }
Ejemplo n.º 11
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();

            Initialize();
            Start();
        }
Ejemplo n.º 12
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                if (Hub.Instance.VoipTaskInstance != null)
                {
                    Debug.WriteLine("VoipTask already started.");
                    return;
                }

                _deferral = taskInstance.GetDeferral();
                Hub.Instance.VoipTaskInstance = this;
                Debug.WriteLine($"{DateTime.Now} VoipTask started.");
                taskInstance.Canceled += (s, e) => CloseVoipTask();
            }
            catch (Exception e)
            {
                if (Hub.Instance.IsAppInsightsEnabled)
                {
                    Hub.Instance.RTCStatsManager.TrackException(e);
                }
                if (_deferral != null)
                {
                    _deferral.Complete();
                }
                throw e;
            }
        }
Ejemplo n.º 13
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Connect the Ultrasonic Sensor to digital port 4
            IUltrasonicRangerSensor sensor = DeviceFactory.Build.UltraSonicSensor(Pin.DigitalPin4);

            // Loop endlessly
            while (true)
            {
                Task.Delay(100).Wait(); //Delay 0.1 second
                try
                {
                    // Check the value of the Ultrasonic Sensor
                    string sensorvalue = sensor.MeasureInCentimeters().ToString();
                    System.Diagnostics.Debug.WriteLine("Ultrasonic reads " + sensorvalue);

                }
                catch (Exception ex)
                {
                    // NOTE: There are frequent exceptions of the following:
                    // WinRT information: Unexpected number of bytes was transferred. Expected: '. Actual: '.
                    // This appears to be caused by the rapid frequency of writes to the GPIO
                    // These are being swallowed here/

                    // If you want to see the exceptions uncomment the following:
                    // System.Diagnostics.Debug.WriteLine(ex.ToString());
                }
            }
        }
Ejemplo n.º 14
0
        //
        // The Run method is the entry point of a background task.
        //
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");

            // For performing asynchronous operations in the background task
            BackgroundTaskDeferral asyncDeferral = taskInstance.GetDeferral();

           

            //
            // Query BackgroundWorkCost
            // Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
            // of work in the background task and return immediately.
            //
            var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
            var settings = ApplicationData.Current.LocalSettings;
            settings.Values["BackgroundWorkCost"] = cost.ToString();

            //
            // Associate a cancellation handler with the background task.
            //
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            //
            // Get the deferral object from the task instance, and take a reference to the taskInstance;
            //
            _deferral = taskInstance.GetDeferral();
            _taskInstance = taskInstance;

            _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));

            asyncDeferral.Complete();
        }
        // Completion groups allow us to immediately take action after a set of downloads completes.
        // In this sample, the server intentionally replies with an error status for some of the downloads.
        // Based on the trigger details, we can determine which of the downloads have failed and try them again
        // using a new completion group.
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTransferCompletionGroupTriggerDetails details = taskInstance.TriggerDetails
                as BackgroundTransferCompletionGroupTriggerDetails;

            if (details == null)
            {
                // This task was not triggered by a completion group.
                return;
            }

            List<DownloadOperation> failedDownloads = new List<DownloadOperation>();
            int succeeded = 0;
            foreach (DownloadOperation download in details.Downloads)
            {
                if (IsFailed(download))
                {
                    failedDownloads.Add(download);
                }
                else
                {
                    succeeded++;
                }
            }

            if (failedDownloads.Count > 0)
            {
                RetryDownloads(failedDownloads);
            }

            InvokeSimpleToast(succeeded, failedDownloads.Count);
        }
Ejemplo n.º 16
0
 public async void Run(IBackgroundTaskInstance taskInstance)
 {
     taskInstance.Canceled += OnCanceled;
     var defferal = taskInstance.GetDeferral();
     TileHelper.UpdateTile(HomeSensorHelper.GetSensorData());
     defferal.Complete(); 
 }
Ejemplo n.º 17
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Adapter adapter = null;
            deferral = taskInstance.GetDeferral();

            try
            {
                adapter = new Adapter();
                dsbBridge = new DsbBridge(adapter);

                var initResult = dsbBridge.Initialize();
                if (initResult != 0)
                {
                    throw new Exception("DSB Bridge initialization failed!");
                }
            }
            catch (Exception ex)
            {
                if (dsbBridge != null)
                {
                    dsbBridge.Shutdown();
                }

                if (adapter != null)
                {
                    adapter.Shutdown();
                }

                throw;
            }
        }
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     var backgroundTaskDeferral = taskInstance.GetDeferral();
     try { UpdateTile(); }
     catch (Exception ex) { Debug.WriteLine(ex); }
     finally { backgroundTaskDeferral.Complete(); }
 }
Ejemplo n.º 19
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            try {
                var triggerDetail = (AppServiceTriggerDetails) taskInstance.TriggerDetails;
                _deferral = taskInstance.GetDeferral();

                Hub.Instance.ForegroundConnection = triggerDetail.AppServiceConnection;
                Hub.Instance.ForegroundTask = this;

                taskInstance.Canceled += (s, e) => Close();
                triggerDetail.AppServiceConnection.ServiceClosed += (s, e) => Close();
            }
            catch (System.Exception e)
            {
                if (Hub.Instance.IsAppInsightsEnabled)
                {
                    Hub.Instance.RTCStatsManager.TrackException(e);
                }
                if (_deferral != null)
                {
                    _deferral.Complete();
                }
                throw e;
            }
        }
Ejemplo n.º 20
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            taskInstance.Canceled += TaskInstance_Canceled;

            var triggerDetails = taskInstance.TriggerDetails
                as AppServiceTriggerDetails;

            if (triggerDetails?.Name != nameof(VoiceCommandService))
                return;

            var connection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);

            connection.VoiceCommandCompleted += ConnectionOnVoiceCommandCompleted;

            var command = await connection.GetVoiceCommandAsync();
            //even if it's not used, you can run into issues without this line.

            switch (command.CommandName)
            {
                case "ReadTodaysNamedays":
                    await HandleReadNamedaysCommandAsync(connection);
                    break;
            }


            deferral.Complete();
        }
Ejemplo n.º 21
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            using (device = new CanvasDevice())
            {
                try
                {
                    GenerateTileImage(TileTemplateType.TileSquare150x150Image, 150, 150);
                    GenerateTileImage(TileTemplateType.TileWide310x150Image, 310, 150);
                }
                catch (Exception e)
                {
                    if (device.IsDeviceLost(e.HResult))
                    {
                        // When the device is lost we don't attempt to retry, and instead just wait for
                        // the next time the task runs.
                        return;
                    }

                    // Any other errors we bubble up
                    throw;
                }
            }

            UpdateLiveTiles();
            DeleteOldLiveTileImageFiles();
            LiveTileUpdater.SetLatestTileImagesInSettings(tiles.Values);
        }
Ejemplo n.º 22
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferal = taskInstance.GetDeferral();
            if (taskInstance.TriggerDetails is RawNotification)
            {
                var details = taskInstance.TriggerDetails as RawNotification;
                var arguments = details.Content.Split(':');

                if (arguments.Count() > 0)
                {

                    switch (arguments[0])
                    {
                        case "new_items":
                            if (arguments.Count() > 1)
                            {
                                XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
                                XmlElement badgeElement = (XmlElement)badgeXml.SelectSingleNode("/badge");
                                badgeElement.SetAttribute("value", arguments[1]);
                                BadgeNotification badge = new BadgeNotification(badgeXml);
                                BadgeUpdateManager.CreateBadgeUpdaterForApplication().Update(badge);
                            }
                            break;
                    }
                }
            }


            

            


            deferal.Complete();
        }
Ejemplo n.º 23
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     deferral = taskInstance.GetDeferral();
     InitGPIO();
     timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(500));
     
 }
Ejemplo n.º 24
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();

            IReadOnlyList<GeofenceStateChangeReport> reports = GeofenceMonitor.Current.ReadReports();

            foreach (var report in reports)
            {
                if ((report.NewState != GeofenceState.None) &&
                    (report.NewState != GeofenceState.Removed))
                {
                    await StatusFile.AddStatusEntry(
                        report.Geofence.Id, 
                        report.NewState == GeofenceState.Entered ? EntryType.EnteredZone : EntryType.ExitedZone);
                }
            }

            XmlDocument template = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
            
            NotificationTemplateHelper.CompleteToastOrTileTemplate(
                template,
                new string[] 
                {
                    "One or more of our fences has been crossed"
                },
                null);

            ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();

            notifier.Show(new ToastNotification(template));

            deferral.Complete();
        }
        private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
        {
            _cancelRequested = true;
            _cancelReason = reason;

            Debug.WriteLine($"Background '{sender.Task.Name}' Cancel Requested...");
        }
Ejemplo n.º 26
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // simple example with a Toast, to enable this go to manifest file
            // and mark App as TastCapable - it won't work without this
            // The Task will start but there will be no Toast.
            //ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
            //XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
            //XmlNodeList textElements = toastXml.GetElementsByTagName("text");
            //textElements[0].AppendChild(toastXml.CreateTextNode("My first Task - Yeah"));
            //textElements[1].AppendChild(toastXml.CreateTextNode("I'm a message from your background task!"));
            //ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));




            var deferral = taskInstance.GetDeferral();
            RawNotification raw = taskInstance.TriggerDetails as RawNotification;
            if (raw != null)
            {
                Debug.WriteLine(
                  string.Format("XXXXXXXXXXXXXReceived from cloud:XXXXXXXXXX [{0}]",
                  raw.Content));
            } 

            deferral.Complete();
        }
Ejemplo n.º 27
0
        /// <remarks>
        /// If you start any asynchronous methods here, prevent the task
        /// from closing prematurely by using BackgroundTaskDeferral as
        /// described in http://aka.ms/backgroundtaskdeferral
        /// </remarks>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // This deferral should have an instance reference, if it doesn't... the GC will
            // come some day, see that this method is not active anymore and the local variable
            // should be removed. Which results in the application being closed.
            _deferral = taskInstance.GetDeferral();
            var restRouteHandler = new RestRouteHandler();

            restRouteHandler.RegisterController<AsyncControllerSample>();
            restRouteHandler.RegisterController<FromContentControllerSample>();
            restRouteHandler.RegisterController<PerCallControllerSample>();
            restRouteHandler.RegisterController<SimpleParameterControllerSample>();
            restRouteHandler.RegisterController<SingletonControllerSample>();
            restRouteHandler.RegisterController<ThrowExceptionControllerSample>();
            restRouteHandler.RegisterController<WithResponseContentControllerSample>();

            var configuration = new HttpServerConfiguration()
                .ListenOnPort(8800)
                .RegisterRoute("api", restRouteHandler)
                .RegisterRoute(new StaticFileRouteHandler(@"Restup.DemoStaticFiles\Web"))
                .EnableCors(); // allow cors requests on all origins
            //  .EnableCors(x => x.AddAllowedOrigin("http://specificserver:<listen-port>"));

            var httpServer = new HttpServer(configuration);
            _httpServer = httpServer;
            
            await httpServer.StartServerAsync();

            // Dont release deferral, otherwise app will stop
        }
Ejemplo n.º 28
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Check the task cost
            var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
            if (cost == BackgroundWorkCostValue.High)
            {
                return;
            }

            // Get the cancel token
            var cancel = new System.Threading.CancellationTokenSource();
            taskInstance.Canceled += (s, e) =>
            {
                cancel.Cancel();
                cancel.Dispose();
            };

            // Get deferral
            var deferral = taskInstance.GetDeferral();
            try
            {
                // Update Tile with the new xml
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(TileUpdaterTask.w10TileXml);

                TileNotification tileNotification = new TileNotification(xmldoc);
                TileUpdater tileUpdator = TileUpdateManager.CreateTileUpdaterForApplication();
                tileUpdator.Update(tileNotification);
            }
            finally
            {
                deferral.Complete();
            }
        }
Ejemplo n.º 29
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // 
            // TODO: Insert code to perform background work
            //
            // If you start any asynchronous methods here, prevent the task
            // from closing prematurely by using BackgroundTaskDeferral as
            // described in http://aka.ms/backgroundtaskdeferral
            //
            var deferral = taskInstance.GetDeferral();
            var settings = new I2cConnectionSettings(I2C_ADDRESS);
            settings.BusSpeed = I2cBusSpeed.FastMode;
            var aqs = I2cDevice.GetDeviceSelector();                     /* Get a selector string that will return all I2C controllers on the system */
            var dis = await DeviceInformation.FindAllAsync(aqs);            /* Find the I2C bus controller devices with our selector string             */
            _dht11 = await I2cDevice.FromIdAsync(dis[0].Id, settings);    /* Create an I2cDevice with our selected bus controller and I2C settings    */
            await begin();

            while (true)
            {
                var temp = await readTemperature();
                var hum = await readHumidity();
                Debug.WriteLine($"{temp} C & {hum}% humidity");
                await Task.Delay(2000);
            }

            deferral.Complete();
        }
Ejemplo n.º 30
0
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     if (this.deferral != null)
     {
         this.deferral.Complete();
     }
 }
Ejemplo n.º 31
0
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     Close();
 }
Ejemplo n.º 32
0
 public abstract void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason);
Ejemplo n.º 33
0
 public abstract Task RunAsyncInternal(IBackgroundTaskInstance taskInstance);
Ejemplo n.º 34
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            backgroundTaskInstance = taskInstance;

            var details = taskInstance.TriggerDetails as BluetoothLEAdvertisementWatcherTriggerDetails;

            if (details != null)
            {
                // If the background watcher stopped unexpectedly, an error will be available here.
                var error = details.Error;

                // The Advertisements property is a list of all advertisement events received
                // since the last task triggered. The list of advertisements here might be valid even if
                // the Error status is not Success since advertisements are stored until this task is triggered
                IReadOnlyList <BluetoothLEAdvertisementReceivedEventArgs> advertisements = details.Advertisements;

                // The signal strength filter configuration of the trigger is returned such that further
                // processing can be performed here using these values if necessary. They are read-only here.
                var rssiFilter = details.SignalStrengthFilter;

                // In this example, the background task simply constructs a message communicated
                // to the App. For more interesting applications, a notification can be sent from here instead.
                //string eventMessage = "";
                //eventMessage += string.Format("ErrorStatus: {0}, EventCount: {1}, HighDBm: {2}, LowDBm: {3}, Timeout: {4}, Sampling: {5}",
                //    error.ToString(),
                //    advertisements.Count.ToString(),
                //    rssiFilter.InRangeThresholdInDBm.ToString(),
                //    rssiFilter.OutOfRangeThresholdInDBm.ToString(),
                //    rssiFilter.OutOfRangeTimeout.GetValueOrDefault().TotalMilliseconds.ToString(),
                //    rssiFilter.SamplingInterval.GetValueOrDefault().TotalMilliseconds.ToString());

                //// Advertisements can contain multiple events that were aggregated, each represented by
                //// a BluetoothLEAdvertisementReceivedEventArgs object.
                //foreach (var eventArgs in advertisements)
                //{
                //    // Check if there are any manufacturer-specific sections.
                //    // If there is, print the raw data of the first manufacturer section (if there are multiple).
                //    string manufacturerDataString = "";
                //    var manufacturerSections = eventArgs.Advertisement.ManufacturerData;
                //    if (manufacturerSections.Count > 0)
                //    {
                //        var manufacturerData = manufacturerSections[0];
                //        var data = new byte[manufacturerData.Data.Length];
                //        using (var reader = DataReader.FromBuffer(manufacturerData.Data))
                //        {
                //            reader.ReadBytes(data);
                //        }
                //        // Print the company ID + the raw data in hex format.
                //        manufacturerDataString = string.Format("0x{0}: {1}",
                //            manufacturerData.CompanyId.ToString("X"),
                //            BitConverter.ToString(data));
                //    }
                //    eventMessage += string.Format("\n[{0}] [{1}]: Rssi={2}dBm, localName={3}, manufacturerData=[{4}]",
                //        eventArgs.Timestamp.ToString("hh\\:mm\\:ss\\.fff"),
                //        eventArgs.AdvertisementType.ToString(),
                //        eventArgs.RawSignalStrengthInDBm.ToString(),
                //        eventArgs.Advertisement.LocalName,
                //        manufacturerDataString);
                //}

                //// Store the message in a local settings indexed by this task's name so that the foreground App
                //// can display this message.
                //ApplicationData.Current.LocalSettings.Values[taskInstance.Task.Name] = eventMessage;
            }
        }
Ejemplo n.º 35
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;
            TimeSpan      imageUpdateDue;
            TimeSpan      imageUpdatePeriod;

            this.logging.LogEvent("Application starting");

            // Log the Application build, OS version information etc.
            LoggingFields startupInformation = new LoggingFields();

            startupInformation.AddString("Timezone", TimeZoneSettings.CurrentTimeZoneDisplayName);
            startupInformation.AddString("OSVersion", Environment.OSVersion.VersionString);
            startupInformation.AddString("MachineName", Environment.MachineName);

            // This is from the application manifest
            Package        package   = Package.Current;
            PackageId      packageId = package.Id;
            PackageVersion version   = packageId.Version;

            startupInformation.AddString("ApplicationVersion", string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"));

            try
            {
                // see if the configuration file is present if not copy minimal sample one from application directory
                if (localFolder.TryGetItemAsync(ConfigurationFilename).AsTask().Result == null)
                {
                    StorageFile templateConfigurationfile = Package.Current.InstalledLocation.GetFileAsync(ConfigurationFilename).AsTask().Result;
                    templateConfigurationfile.CopyAsync(localFolder, ConfigurationFilename).AsTask();
                }

                IConfiguration configuration = new ConfigurationBuilder().AddJsonFile(Path.Combine(localFolder.Path, ConfigurationFilename), false, true).Build();

                this.interruptPinNumber = int.Parse(configuration.GetSection("InterruptPinNumber").Value);
                startupInformation.AddInt32("Interrupt pin", this.interruptPinNumber);

                this.interruptTriggerOn = (GpioPinEdge)Enum.Parse(typeof(GpioPinEdge), configuration.GetSection("interruptTriggerOn").Value);
                startupInformation.AddString("Interrupt Trigger on", this.interruptTriggerOn.ToString());

                this.displayPinNumber = int.Parse(configuration.GetSection("DisplayPinNumber").Value);
                startupInformation.AddInt32("Display pin", this.interruptPinNumber);

                this.azureIoTHubConnectionString = configuration.GetSection("AzureIoTHubConnectionString").Value;
                startupInformation.AddString("AzureIoTHubConnectionString", this.azureIoTHubConnectionString);

                this.transportType = (TransportType)Enum.Parse(typeof(TransportType), configuration.GetSection("TransportType").Value);
                startupInformation.AddString("TransportType", this.transportType.ToString());
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("JSON configuration file load or settings retrieval failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            #region AzureIoT Hub connection string creation
            try
            {
                this.azureIoTHubClient = DeviceClient.CreateFromConnectionString(this.azureIoTHubConnectionString, this.transportType);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("AzureIOT Hub DeviceClient.CreateFromConnectionString failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Report device and application properties to AzureIoT Hub
            try
            {
                TwinCollection reportedProperties = new TwinCollection();

                // This is from the OS
                reportedProperties["Timezone"]    = TimeZoneSettings.CurrentTimeZoneDisplayName;
                reportedProperties["OSVersion"]   = Environment.OSVersion.VersionString;
                reportedProperties["MachineName"] = Environment.MachineName;

                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

                // Unique identifier from the hardware
                SystemIdentificationInfo systemIdentificationInfo = SystemIdentification.GetSystemIdForPublisher();
                using (DataReader reader = DataReader.FromBuffer(systemIdentificationInfo.Id))
                {
                    byte[] bytes = new byte[systemIdentificationInfo.Id.Length];
                    reader.ReadBytes(bytes);
                    reportedProperties["SystemId"] = BitConverter.ToString(bytes);
                }

                this.azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client UpdateReportedPropertiesAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Retrieve device twin settings
            try
            {
                LoggingFields configurationInformation = new LoggingFields();

                Twin deviceTwin = this.azureIoTHubClient.GetTwinAsync().GetAwaiter().GetResult();

                if (!deviceTwin.Properties.Desired.Contains("ImageUpdateDue") || !TimeSpan.TryParse(deviceTwin.Properties.Desired["ImageUpdateDue"].value.ToString(), out imageUpdateDue))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ImageUpdateDue setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddTimeSpan("ImageUpdateDue", imageUpdateDue);

                if (!deviceTwin.Properties.Desired.Contains("ImageUpdatePeriod") || !TimeSpan.TryParse(deviceTwin.Properties.Desired["ImageUpdatePeriod"].value.ToString(), out imageUpdatePeriod))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ImageUpdatePeriod setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddTimeSpan("ImageUpdatePeriod", imageUpdatePeriod);

                if (!deviceTwin.Properties.Desired.Contains("ModelType") || (!Enum.TryParse(deviceTwin.Properties.Desired["ModelType"].value.ToString(), out modelType)))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ModelType setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddString("ModelType", modelType.ToString());

                if (!deviceTwin.Properties.Desired.Contains("ModelPublishedName") || (string.IsNullOrWhiteSpace(deviceTwin.Properties.Desired["ModelPublishedName"].value.ToString())))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ModelPublishedName setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                modelPublishedName = deviceTwin.Properties.Desired["ModelPublishedName"].value.ToString();
                configurationInformation.AddString("ModelPublishedName", modelPublishedName);

                if (!deviceTwin.Properties.Desired.Contains("ProjectID") || (!Guid.TryParse(deviceTwin.Properties.Desired["ProjectID"].value.ToString(), out projectId)))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ProjectId setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddGuid("ProjectID", projectId);

                if (!deviceTwin.Properties.Desired.Contains("ProbabilityThreshold") || (!Double.TryParse(deviceTwin.Properties.Desired["ProbabilityThreshold"].value.ToString(), out probabilityThreshold)))
                {
                    this.logging.LogMessage("DeviceTwin.Properties ProbabilityThreshold setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddDouble("ProbabilityThreshold", probabilityThreshold);

                if (!deviceTwin.Properties.Desired.Contains("AzureCognitiveServicesEndpoint") || (string.IsNullOrWhiteSpace(deviceTwin.Properties.Desired["AzureCognitiveServicesEndpoint"].value.ToString())))
                {
                    this.logging.LogMessage("DeviceTwin.Properties AzureCognitiveServicesEndpoint setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                azureCognitiveServicesEndpoint = deviceTwin.Properties.Desired["AzureCognitiveServicesEndpoint"].value.ToString();
                configurationInformation.AddString("AzureCognitiveServicesEndpoint", modelPublishedName);

                if (!deviceTwin.Properties.Desired.Contains("AzureCognitiveServicesSubscriptionKey") || (string.IsNullOrWhiteSpace(deviceTwin.Properties.Desired["AzureCognitiveServicesSubscriptionKey"].value.ToString())))
                {
                    this.logging.LogMessage("DeviceTwin.Properties AzureCognitiveServicesSubscriptionKey setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                azureCognitiveServicesSubscriptionKey = deviceTwin.Properties.Desired["AzureCognitiveServicesSubscriptionKey"].value.ToString();
                configurationInformation.AddString("AzureCognitiveServicesSubscriptionKey", azureCognitiveServicesSubscriptionKey);

                if (!deviceTwin.Properties.Desired.Contains("DebounceTimeout") || !TimeSpan.TryParse(deviceTwin.Properties.Desired["DebounceTimeout"].value.ToString(), out debounceTimeout))
                {
                    this.logging.LogMessage("DeviceTwin.Properties DebounceTimeout setting missing or invalid format", LoggingLevel.Warning);
                    return;
                }
                configurationInformation.AddTimeSpan("DebounceTimeout", debounceTimeout);

                this.logging.LogEvent("Configuration settings", configurationInformation);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client GetTwinAsync failed or property missing/invalid" + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            try
            {
                this.customVisionClient = new CustomVisionPredictionClient(new System.Net.Http.DelegatingHandler[] { })
                {
                    ApiKey   = this.azureCognitiveServicesSubscriptionKey,
                    Endpoint = this.azureCognitiveServicesEndpoint,
                };
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure Cognitive Services Custom Vision Client configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            try
            {
                this.mediaCapture = new MediaCapture();
                this.mediaCapture.InitializeAsync().AsTask().Wait();
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Camera configuration failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            this.displayOffTimer = new Timer(this.TimerCallback, null, Timeout.Infinite, Timeout.Infinite);

            #region Wire up interupt handler for image capture request
            if (this.interruptPinNumber != 0)
            {
                try
                {
                    GpioController gpioController = GpioController.GetDefault();
                    this.interruptGpioPin = gpioController.OpenPin(this.interruptPinNumber);
                    this.interruptGpioPin.SetDriveMode(GpioPinDriveMode.InputPullUp);
                    this.interruptGpioPin.ValueChanged += this.InterruptGpioPin_ValueChanged;

                    this.displayGpioPin = gpioController.OpenPin(this.displayPinNumber);
                    this.displayGpioPin.SetDriveMode(GpioPinDriveMode.Output);
                    this.displayGpioPin.Write(GpioPinValue.Low);
                }
                catch (Exception ex)
                {
                    this.logging.LogMessage("Digital input configuration failed " + ex.Message, LoggingLevel.Error);
                    return;
                }
            }
            #endregion

            #region Wire up command handler for image capture request
            try
            {
                this.azureIoTHubClient.SetMethodHandlerAsync("ImageCapture", this.ImageUpdateHandler, null);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client ImageCapture SetMethodHandlerAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            #region Wire up command handler for device reboot request
            try
            {
                this.azureIoTHubClient.SetMethodHandlerAsync("DeviceReboot", this.DeviceRebootAsync, null);
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("Azure IoT Hub client DeviceReboot SetMethodHandlerAsync failed " + ex.Message, LoggingLevel.Error);
                return;
            }
            #endregion

            if ((imageUpdateDue != TimeSpan.MinValue) || (imageUpdatePeriod != TimeSpan.MinValue))
            {
                this.imageUpdatetimer = new Timer(this.ImageUpdateTimerCallback, null, imageUpdateDue, imageUpdatePeriod);
            }

            this.logging.LogEvent("Application started", startupInformation);

            // enable task to continue running in background
            this.backgroundTaskDeferral = taskInstance.GetDeferral();
        }
Ejemplo n.º 36
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     // TaskManager.Register(taskInstance);
     Debug.WriteLine($"CrossDeviceAppService#Run called: {taskInstance.InstanceId}");
 }
Ejemplo n.º 37
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral        = taskInstance.GetDeferral();
            taskInstance.Canceled += TaskInstance_Canceled;
            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            if (triggerDetails != null && triggerDetails.Name == "GeneralQueryVoiceCommandService")
            {
                try
                {
                    voiceCommandServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                    voiceCommandServiceConnection.VoiceCommandCompleted += VoiceCommandServiceConnection_VoiceCommandCompleted;
                    VoiceCommand voiceCommand = await voiceCommandServiceConnection.GetVoiceCommandAsync();

                    switch (voiceCommand.CommandName)
                    {
                    case "On":
                        await Class1.showProgressScreen(voiceCommandServiceConnection, "正在打开" + voiceCommand.Properties["rooms"][0] + "的灯");

                        var OnRoom = voiceCommand.Properties["rooms"][0];
                        switch (OnRoom)
                        {
                        case "卧室":
                            helper1.SendMessagesToRasp("1-100-50", ipAddress);
                            helper1.ReportSuccess(voiceCommandServiceConnection);
                            break;

                        case "厨房":
                            helper1.SendMessagesToRasp("2-100-50", ipAddress);
                            helper1.ReportSuccess(voiceCommandServiceConnection);
                            break;

                        default:
                            helper1.ReportSuccess(voiceCommandServiceConnection);
                            break;
                        }
                        break;

                    case "Off":
                        await Class1.showProgressScreen(voiceCommandServiceConnection, "正在关闭" + voiceCommand.Properties["rooms"][0] + "的灯");

                        var OffRoom = voiceCommand.Properties["rooms"][0];
                        switch (OffRoom)
                        {
                        case "卧室":
                            helper1.SendMessagesToRasp("1-0-50", ipAddress);
                            break;

                        case "厨房":
                            helper1.SendMessagesToRasp("2-0-50", ipAddress);
                            break;

                        default:
                            break;
                        }
                        helper1.ReportSuccess(voiceCommandServiceConnection);
                        break;

                    case "Brighter":
                        await Class1.showProgressScreen(voiceCommandServiceConnection, "正在增加" + voiceCommand.Properties["rooms"][0] + "的亮度");

                        var BrighterRoom = voiceCommand.Properties["rooms"][0];
                        switch (BrighterRoom)
                        {
                        case "卧室":
                            helper1.SendMessagesToRasp("1-210-50", ipAddress);
                            helper1.ReportSuccess(voiceCommandServiceConnection);
                            break;

                        case "厨房":
                            helper1.SendMessagesToRasp("2-210-50", ipAddress);
                            helper1.ReportSuccess(voiceCommandServiceConnection);
                            break;

                        default:
                            helper1.ReportSuccess(voiceCommandServiceConnection);
                            break;
                        }
                        break;

                    case "Darker":
                        await Class1.showProgressScreen(voiceCommandServiceConnection, "正在降低" + voiceCommand.Properties["rooms"][0] + "的亮度");

                        var DarkerRoom = voiceCommand.Properties["rooms"][0];
                        switch (DarkerRoom)
                        {
                        case "卧室":
                            helper1.SendMessagesToRasp("1-211-50", ipAddress);
                            helper1.ReportSuccess(voiceCommandServiceConnection);
                            break;

                        case "厨房":
                            helper1.SendMessagesToRasp("2-211-50", ipAddress);
                            helper1.ReportSuccess(voiceCommandServiceConnection);
                            break;

                        default:
                            helper1.ReportSuccess(voiceCommandServiceConnection);
                            break;
                        }
                        break;

                    default:
                        helper1.ReportSuccess(voiceCommandServiceConnection);
                        break;
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Background task entrypoint. Voice Commands using the <VoiceCommandService Target="...">
        /// tag will invoke this when they are recognized by Cortana, passing along details of the
        /// invocation.
        ///
        /// Background tasks must respond to activation by Cortana within 0.5 seconds, and must
        /// report progress to Cortana every 5 seconds (unless Cortana is waiting for user
        /// input). There is no execution time limit on the background task managed by Cortana,
        /// but developers should use plmdebug (https://msdn.microsoft.com/en-us/library/windows/hardware/jj680085%28v=vs.85%29.aspx)
        /// on the Cortana app package in order to prevent Cortana timing out the task during
        /// debugging.
        ///
        /// Cortana dismisses its UI if it loses focus. This will cause it to terminate the background
        /// task, even if the background task is being debugged. Use of Remote Debugging is recommended
        /// in order to debug background task behaviors. In order to debug background tasks, open the
        /// project properties for the app package (not the background task project), and enable
        /// Debug -> "Do not launch, but debug my code when it starts". Alternatively, add a long
        /// initial progress screen, and attach to the background task process while it executes.
        /// </summary>
        /// <param name="taskInstance">Connection to the hosting background service process.</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();

            // Register to receive an event if Cortana dismisses the background task. This will
            // occur if the task takes too long to respond, or if Cortana's UI is dismissed.
            // Any pending operations should be cancelled or waited on to clean up where possible.
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            // Load localized resources for strings sent to Cortana to be displayed to the user.
            cortanaResourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");

            // Select the system language, which is what Cortana should be running as.
            cortanaContext = ResourceContext.GetForViewIndependentUse();

            var lang = Windows.Media.SpeechRecognition.SpeechRecognizer.SystemSpeechLanguage.LanguageTag;

            cortanaContext.Languages = new string[] { Windows.Media.SpeechRecognition.SpeechRecognizer.SystemSpeechLanguage.LanguageTag };

            // Get the currently used system date format
            dateFormatInfo = CultureInfo.CurrentCulture.DateTimeFormat;

            // This should match the uap:AppService and VoiceCommandService references from the
            // package manifest and VCD files, respectively. Make sure we've been launched by
            // a Cortana Voice Command.
            if (triggerDetails != null && triggerDetails.Name == "AdventureWorksVoiceCommandService")
            {
                try
                {
                    voiceServiceConnection =
                        VoiceCommandServiceConnection.FromAppServiceTriggerDetails(
                            triggerDetails);

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                    // Depending on the operation (defined in AdventureWorks:AdventureWorksCommands.xml)
                    // perform the appropriate command.
                    switch (voiceCommand.CommandName)
                    {
                    case "whenIsTripToDestination":
                        var destination = voiceCommand.Properties["destination"][0];
                        await SendCompletionMessageForDestination(destination);

                        break;

                    case "cancelTripToDestination":
                        var cancelDestination = voiceCommand.Properties["destination"][0];
                        await SendCompletionMessageForCancellation(cancelDestination);

                        break;

                    default:
                        // As with app activation VCDs, we need to handle the possibility that
                        // an app update may remove a voice command that is still registered.
                        // This can happen if the user hasn't run an app since an update.
                        LaunchAppInForeground();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
            }
        }
Ejemplo n.º 39
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral deferral = taskInstance?.GetDeferral();

            //BlynkLogManager.BlynkLogger = new ConsoleBlynkLogger( ConsoleBlynkLogger.LogLevels.LogExceptions
            //		| ConsoleBlynkLogger.LogLevels.LogWarnings
            //		| ConsoleBlynkLogger.LogLevels.LogInformation );

            var connection = new BlynkConnection("blynk-cloud.com", 8442, "-secret here-");

            if (connection.Connect())
            {
                InitializePins();

                connection.AnalogPinNotification.PinWriteNotification = pin => {
                    //Console.WriteLine( "Analog pin received A{0} : {1}", pin.PinNumber, pin.Value );
                    analogPinList[pin.PinNumber].Value = pin.Value;
                };

                connection.DigitalPinNotification.PinWriteNotification = pin => {
                    //Console.WriteLine( "Digital pin received D{0} : {1}", pin.PinNumber, pin.Value );
                    digitalPinList[pin.PinNumber].Value = pin.Value;
                };

                connection.AnalogPinNotification.PinReadRequest = pinNumber => {
                    //Console.WriteLine( "Analog pin A{0} requested", pinNumber );
                    var result = analogPinList[pinNumber];
                    result.Value = ( short )((result.Value + 1) % 16);
                    return(result);
                };

                connection.DigitalPinNotification.PinReadRequest = pinNumber => {
                    //Console.WriteLine( "Digital pin D{0} requested", pinNumber );
                    var result = digitalPinList[pinNumber];
                    result.Value = !result.Value;
                    return(result);
                };

                connection.VirtualPinNotification.PinReadRequest = pinNumber => {
                    //Console.WriteLine( "Virtual pin V{0} requested", pinNumber );
                    var result = virtualPinList[pinNumber];
                    result.Values.Clear();
                    result.Values.Add("255");
                    return(result);
                };

                //connection.PinModeNotification = ( pinNumber, pinMode ) => Console.WriteLine( "PinMode {0} : {1}", pinNumber, pinMode );

                //connection.ResponseReceivedNotification = ( code ) => Console.WriteLine( "Response : {0}", code );

                //Console.WriteLine( "hit a key to exit" );
                //Console.ReadKey();

                //connection.Disconnect();
            }
            else
            {
                deferral?.Complete();
            }

            //Console.WriteLine( "exiting" );
            //System.Threading.Thread.Sleep( 2000 );
        }
Ejemplo n.º 40
0
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     CompleteDeferral();
 }
Ejemplo n.º 41
0
 private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) =>
 _taskDeferral?.Complete();
Ejemplo n.º 42
0
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     _bootstrapper.Dispose();
 }
Ejemplo n.º 43
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");
 }
Ejemplo n.º 44
0
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     // Maybe do something...
 }
Ejemplo n.º 45
0
 private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     _cancelRequested = true;
     _cancelReason    = reason;
     Debug.WriteLine("Background " + sender.Task.Name + " Cancel Requested...");
 }
Ejemplo n.º 46
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral Deferral = taskInstance.GetDeferral();

            taskInstance.Canceled += TaskInstance_Canceled;

            try
            {
                await ClearUselessLogTask(Cancellation.Token).ConfigureAwait(true);

                using (SqliteConnection Connection = GetSQLConnection())
                {
                    await ClearAddressBarHistory(Connection).ConfigureAwait(true);
                    await UpdateSQLiteDataBase(Connection).ConfigureAwait(true);
                }

                //The following code is used to update the globalization problem of the ContextMenu in the old version
                if (!ApplicationData.Current.LocalSettings.Values.ContainsKey("GlobalizationStringForContextMenu"))
                {
                    if (ApplicationData.Current.LocalSettings.Values["LanguageOverride"] is int LanguageIndex)
                    {
                        switch (LanguageIndex)
                        {
                        case 0:
                        {
                            ApplicationData.Current.LocalSettings.Values["GlobalizationStringForContextMenu"] = "使用RX文件管理器打开";
                            break;
                        }

                        case 1:
                        {
                            ApplicationData.Current.LocalSettings.Values["GlobalizationStringForContextMenu"] = "Open in RX-Explorer";
                            break;
                        }

                        case 2:
                        {
                            ApplicationData.Current.LocalSettings.Values["GlobalizationStringForContextMenu"] = "Ouvrir dans RX-Explorer";
                            break;
                        }

                        case 3:
                        {
                            ApplicationData.Current.LocalSettings.Values["GlobalizationStringForContextMenu"] = "使用RX文件管理器打開";
                            break;
                        }
                        }
                    }
                }

                //To-Do: Do more things as needed when users update the app to newer version
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"An exception threw in MaintenanceTask, message: {ex.Message}");
            }
            finally
            {
                taskInstance.Canceled -= TaskInstance_Canceled;
                Cancellation?.Dispose();
                Cancellation = null;
                Deferral.Complete();
            }
        }
Ejemplo n.º 47
0
 public void SubscribeToEvents(IBackgroundTaskInstance taskInstance)
 {
     taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
 }
Ejemplo n.º 48
0
 private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     // Relinquish our task deferral
     taskDeferral.Complete();
 }
Ejemplo n.º 49
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
 }
Ejemplo n.º 50
0
 private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     appServiceDeferral?.Complete();
 }
Ejemplo n.º 51
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     deferral = taskInstance.GetDeferral();
     InitGPIO();
     timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(500));
 }
Ejemplo n.º 52
0
        public Task RunAsync(IBackgroundTaskInstance taskInstance)
        {
            SubscribeToEvents(taskInstance);

            return(RunAsyncInternal(taskInstance));
        }
Ejemplo n.º 53
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            System.Diagnostics.Debug.WriteLine("Hello From Quick actions bg");
            _deferal = taskInstance.GetDeferral();
            taskInstance.Canceled       += TaskInstance_Canceled;
            taskInstance.Task.Completed += Task_Completed;
            var details = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;

            if (details != null)
            {
                try
                {
                    string         arguments = details.Argument;
                    var            userInput = details.UserInput;
                    string         title     = (string)userInput["title"];
                    string         detail    = (string)userInput["detail"];
                    var            notify    = (byte)int.Parse(userInput["notification"].ToString());
                    var            Time      = int.Parse(userInput["snoozeTime"].ToString());
                    DateTimeOffset now       = DateTimeOffset.Now;

                    if (Time == 15)
                    {
                        DateTime nulll = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
                        now = now.AddMinutes(15);
                    }
                    else if (Time == 60)
                    {
                        DateTime nulll = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
                        now.AddHours(1);
                    }
                    else if (Time == 140)
                    {
                        DateTime nulll = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
                        now.AddHours(4);
                    }
                    else if (Time == 160)
                    {
                        DateTime nulll = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
                        now.AddHours(8);
                    }
                    else if (Time == 190)
                    {
                        DateTime nulll = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
                        now.AddDays(1);
                    }
                    DateTime pocker = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);

                    var todo = new Todo()
                    {
                        Subject   = title,
                        Detail    = detail,
                        StartTime = pocker,
                        Notify    = notify,
                        Status    = 2
                    };

                    _service.AddTodo(todo);
                }
                catch (Exception ex) { }
                try
                {
                    Update();
                }
                catch
                {
                }
            }
            _deferal.Complete();
        }
Ejemplo n.º 54
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var work = new Action <CancellationToken>(async(ct) => await Platform.Current.TimedBackgroundWorkAsync(ct));

            Platform.Current.ExecuteBackgroundWork(taskInstance, work);
        }
Ejemplo n.º 55
0
 private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     //Clean up and get ready to exit
 }
Ejemplo n.º 56
0
 private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     System.Diagnostics.Debug.WriteLine("Task cancelled, clean up");
     _serviceDeferral?.Complete();
 }
Ejemplo n.º 57
0
        public static void Start(IBackgroundTaskInstance instance)
        {
            Stage2Notifications backgroundActivity = new Stage2Notifications();

            backgroundActivity.Run(instance);
        }
Ejemplo n.º 58
0
 private void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) => _deferal.Complete();
 void TaskInstance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     // システムに完了を通知する
     _appServiceDeferral?.Complete();
 }
Ejemplo n.º 60
0
 private void Instance_Canceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     _cancelRequested = true;
 }