//
        // 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();
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();
            var controller = new LightwaveUwpController("255.255.255.255");
            await controller.Register();

            var homeNetwork = new HomeNetwork();

            homeNetwork.AddDevice("Phone", "192.168.1.116", DeviceType.AndroidPhone, 1);
            //homeNetwork.AddDevice("iPad", "192.168.1.72", DeviceType.iPad, 300);
            //homeNetwork.AddDevice("xbox", "192.168.1.200", DeviceType.XboxOne, 300);

            var runTo = DateTime.Now.AddMinutes(15);

            try
            {
                while (true)
                {
                    Debug.WriteLine($"Checking network...");
                    await homeNetwork.UpdateStatusOfAllDevicesAsync();
                    Debug.WriteLine(string.Empty);

                    var phone = homeNetwork.GetDeviceByName("Phone");
                    //var iPad = homeNetwork.GetDeviceByName("iPad");
                    //var xbox = homeNetwork.GetDeviceByName("xbox");

                    if (!_phoneConnected && phone.Connected())
                    {
                        _phoneConnected = phone.Connected();
                        Debug.WriteLine("Phone Joined the network");
                        await controller.TurnOn(3, 1);
                    }
                    else if (_phoneConnected && !phone.Connected())
                    {
                        _phoneConnected = phone.Connected();
                        Debug.WriteLine("Phone left the network");
                        await controller.TurnOff(3, 1);
                    }

                    //if (!_iPadConnected && iPad.Connected())
                    //{
                    //    _iPadConnected = iPad.Connected();
                    //    Debug.WriteLine("iPad Joined the network");
                    //}
                    //else if (_iPadConnected && !iPad.Connected())
                    //{
                    //    _iPadConnected = iPad.Connected();
                    //    Debug.WriteLine("iPad left the network");
                    //}

                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error checking network: {e.Message}");
            }

            deferral.Complete();
        }
 public async void Run(IBackgroundTaskInstance taskInstance)
 {
     taskInstance.Canceled += OnCanceled;
     var defferal = taskInstance.GetDeferral();
     TileHelper.UpdateTile(HomeSensorHelper.GetSensorData());
     defferal.Complete(); 
 }
        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;
            }
        }
        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();
        }
        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();
        }
 public async void Run(IBackgroundTaskInstance taskInstance)
 {
     var deferral = taskInstance.GetDeferral();
     var updater = new LiveTileScheduler();
     await updater.CreateSchedule();
     deferral.Complete();
 }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            System.Diagnostics.Debug.WriteLine("WE are @ Background");
            _deferral = taskInstance.GetDeferral();
            _taskInstance = taskInstance;
            _taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

            GattCharacteristicNotificationTriggerDetails details = (GattCharacteristicNotificationTriggerDetails)taskInstance.TriggerDetails;

            //get the characteristics data and get heartbeat value out from it
            byte[] ReceivedData = new byte[details.Value.Length];
            DataReader.FromBuffer(details.Value).ReadBytes(ReceivedData);

            HeartbeatMeasurement tmpMeasurement = HeartbeatMeasurement.GetHeartbeatMeasurementFromData(ReceivedData);

            System.Diagnostics.Debug.WriteLine("Background heartbeast values: " + tmpMeasurement.HeartbeatValue);

            // send heartbeat values via progress callback
            _taskInstance.Progress = tmpMeasurement.HeartbeatValue;

            //update the value to the Tile
            LiveTile.UpdateSecondaryTile("" + tmpMeasurement.HeartbeatValue);
            
            //Check if we are within the limits, and alert by starting the app if we are not
            alertType alert = await checkHeartbeatLevels(tmpMeasurement.HeartbeatValue);

            _deferral.Complete();
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var defferal = taskInstance.GetDeferral();

            var taskHelper = new TaskHelper();

            var signalingTask = taskHelper.GetTask(nameof(SignalingTask));

            var connOwner = new ConnectionOwner
            {
                OwnerId = signalingTask.TaskId.ToString()
            };

            Hub.Instance.SignalingSocketService.ConnectToSignalingServer(connOwner);

            Hub.Instance.SignalingClient.Register(new Registration
            {
                Name = RegistrationSettings.Name,
                UserId = RegistrationSettings.UserId,
                Domain = RegistrationSettings.Domain,
                PushNotificationChannelURI = RegistrationSettings.PushNotificationChannelURI
            });

            defferal.Complete();
        }
Beispiel #10
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            DataService ds = new DataService();
            var quote = await ds.GetQuoteOfTheDayAsync();

            //Create the Large Tile
            var largeTile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideText09);
            largeTile.GetElementsByTagName("text")[0].InnerText = quote.Author;
            largeTile.GetElementsByTagName("text")[1].InnerText = quote.Content;

            //Create a Small Tile
            var smallTile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareText04);
            smallTile.GetElementsByTagName("text")[0].InnerText = quote.Content;

            //Merge the two updates into one <visual> XML node
            var newNode = largeTile.ImportNode(smallTile.GetElementsByTagName("binding").Item(0), true);
            largeTile.GetElementsByTagName("visual").Item(0).AppendChild(newNode);

            TileNotification notification = new TileNotification(largeTile);
            TileUpdateManager.CreateTileUpdaterForApplication().Update(notification);

            deferral.Complete();
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();

            // Get the background task details
            ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
            string taskName = taskInstance.Task.Name;


            Debug.WriteLine("Background " + taskName + " starting...");
            taskInstance.Canceled += TaskInstanceCanceled;


            // Store the content received from the notification so it can be retrieved from the UI.
            RawNotification notification = (RawNotification)taskInstance.TriggerDetails;

            ApplicationDataContainer container = ApplicationData.Current.LocalSettings;
            container.Values["RawMessage"] = notification.Content.ToString();

            //SendToastNotification(notification.Content);

            Debug.WriteLine("Background " + taskName + " completed!");

            _deferral.Complete();
        }
Beispiel #12
0
        /// <summary>
        /// Hệ thống gọi đến hàm này khi association backgroundtask được bật
        /// </summary>
        /// <param name="taskInstance"> hệ thống tự tạo và truyền vào đây</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //System.Diagnostics.Debug.WriteLine("background run");
            taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(BackgroundTaskCanceled);
            taskInstance.Task.Completed += new BackgroundTaskCompletedEventHandler(BackgroundTaskCompleted);
            _backgroundstarted.Set();//
            _deferral = taskInstance.GetDeferral();

            //Playlist = new BackgroundPlaylist();
            _smtc = initSMTC();


            this._foregroundState = this.initForegroundState();

            BackgroundMediaPlayer.Current.CurrentStateChanged += BackgroundMediaPlayer_CurrentStateChanged;
            //Playlist = await BackgroundPlaylist.LoadBackgroundPlaylist("playlist.xml");
            Playlist = new BackgroundPlaylist();
            Playlist.ListPathsource = await BackgroundPlaylist.LoadCurrentPlaylist(Constant.CurrentPlaylist);
            
            if (_foregroundState != eForegroundState.Suspended)
            {
                ValueSet message = new ValueSet();
                message.Add(Constant.BackgroundTaskStarted, "");
                BackgroundMediaPlayer.SendMessageToForeground(message);
            }  
            Playlist.TrackChanged += Playlist_TrackChanged;
            BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground;
            BackgroundMediaPlayer.Current.MediaEnded +=Current_MediaEnded;
            ApplicationSettingHelper.SaveSettingsValue(Constant.BackgroundTaskState, Constant.BackgroundTaskRunning);
            isbackgroundtaskrunning = true;
            _loopState = eLoopState.None;
        }
Beispiel #13
0
        //TemperatureSensors tempSensors;

        public void Run(IBackgroundTaskInstance taskInstance)
        {
            //if (!_started)
            //{
            //    tempSensors = new TemperatureSensors();
            //    tempSensors.InitSensors();
            //    _started = true;
            //}
            
            // Associate a cancellation handler with the background task. 
            taskInstance.Canceled += TaskInstance_Canceled;

            // Get the deferral object from the task instance
            serviceDeferral = taskInstance.GetDeferral();

            var appService = taskInstance.TriggerDetails as AppServiceTriggerDetails;
            if (appService != null && appService.Name == "App2AppComService")
            {
                appServiceConnection = appService.AppServiceConnection;
                appServiceConnection.RequestReceived += AppServiceConnection_RequestReceived; ;
            }

            // just run init, maybe don't need the above...
            Initialize();
        }
        /// <summary>
        /// Performs the work of a background task. The system calls this method when the associated
        /// background task has been triggered.
        /// </summary>
        /// <param name="taskInstance">
        /// An interface to an instance of the background task. The system creates this instance when the
        /// task has been triggered to run.
        /// </param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background Audio Task " + taskInstance.Task.Name + " starting");

            this.systemMediaTransportControl = SystemMediaTransportControls.GetForCurrentView();
            this.systemMediaTransportControl.IsEnabled = true;
            this.systemMediaTransportControl.IsPauseEnabled = true;
            this.systemMediaTransportControl.IsPlayEnabled = true;
            this.systemMediaTransportControl.IsNextEnabled = true;
            this.systemMediaTransportControl.IsPreviousEnabled = true;

            // Wire up system media control events
            this.systemMediaTransportControl.ButtonPressed += this.OnSystemMediaTransportControlButtonPressed;
            this.systemMediaTransportControl.PropertyChanged += this.OnSystemMediaTransportControlPropertyChanged;

            // Wire up background task events
            taskInstance.Canceled += this.OnTaskCanceled;
            taskInstance.Task.Completed += this.OnTaskcompleted;

            // Initialize message channel 
            BackgroundMediaPlayer.MessageReceivedFromForeground += this.OnMessageReceivedFromForeground;

            // Notify foreground that we have started playing
            BackgroundMediaPlayer.SendMessageToForeground(new ValueSet() { { "BackgroundTaskStarted", "" } });
            this.backgroundTaskStarted.Set();
            this.backgroundTaskRunning = true;

            this.deferral = taskInstance.GetDeferral();
        }
Beispiel #15
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();
            }
        }
        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 ConnectTheDots Settings
            localSettings.ServicebusNamespace = "iotbuildlab-ns";
            localSettings.EventHubName = "ehdevices";
            localSettings.KeyName = "D1";
            localSettings.Key = "iQFNbyWTYRBwypMtPmpfJVz+NBgR32YHrQC0ZSvId20=";
            localSettings.DisplayName = GetHostName();
            localSettings.Organization = "IoT Build Lab";
            localSettings.Location = "USA";

            SaveSettings();

            // Initialize WeatherShield
            await shield.BeginAsync();

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

            // Start the server
            server = new HttpServer(port);
            var asyncAction = ThreadPool.RunAsync((w) => { server.StartServer(shield, weatherData); });

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

            // Create a timer-initiated ThreadPool task to renew SAS token regularly
            SasTokenRenewTimer = ThreadPoolTimer.CreatePeriodicTimer(RenewSasToken, TimeSpan.FromMinutes(15));
        }
        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();
        }
Beispiel #18
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;
    }
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     var backgroundTaskDeferral = taskInstance.GetDeferral();
     try { UpdateTile(); }
     catch (Exception ex) { Debug.WriteLine(ex); }
     finally { backgroundTaskDeferral.Complete(); }
 }
Beispiel #20
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();
        }
 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();
     }
 }
Beispiel #22
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();
        }
Beispiel #23
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();

            Initialize();
            Start();
        }
Beispiel #24
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
        }
Beispiel #25
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;
            }
        }
        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();
        }
        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;
            }
        }
Beispiel #28
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     deferral = taskInstance.GetDeferral();
     InitGPIO();
     timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(500));
     
 }
Beispiel #29
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();
            }
        }
Beispiel #30
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();
        }
Beispiel #31
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance?.GetDeferral();

            try
            {
                var result = await _bingWallpaperService.GetAsync(0, 1, _bingoWallpaperSettings.SelectedArea);

                var image = result?.Images.FirstOrDefault();
                if (image != null)
                {
                    var copyright = image.Copyright;
                    var text      = Regex.Replace(copyright, @"\(©.*", string.Empty).Trim();
                    _tileService.UpdatePrimaryTile(image, text);

                    if (_bingoWallpaperSettings.IsAutoUpdateWallpaper || _bingoWallpaperSettings.IsAutoUpdateLockScreen)
                    {
                        using (var client = new HttpClient())
                        {
                            var bytes = await client.GetByteArrayAsync(_bingWallpaperService.GetUrl(image, _bingoWallpaperSettings.SelectedWallpaperSize));

                            if (bytes != null && bytes.Length > 0)
                            {
                                if (_bingoWallpaperSettings.IsAutoUpdateWallpaper)
                                {
                                    await _systemSettingService.SetWallpaperAsync(bytes);
                                }
                                if (_bingoWallpaperSettings.IsAutoUpdateLockScreen)
                                {
                                    await _systemSettingService.SetLockScreenAsync(bytes);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }
            finally
            {
                deferral?.Complete();
            }
        }
Beispiel #32
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            Deferral = taskInstance.GetDeferral();

            taskInstance.Canceled += TaskInstance_Canceled;

            AppServiceConnection IncomeConnection = (taskInstance.TriggerDetails as AppServiceTriggerDetails).AppServiceConnection;

            IncomeConnection.RequestReceived += Connection_RequestReceived;

            AppServiceResponse Response = await IncomeConnection.SendMessageAsync(new ValueSet { { "ExecuteType", "Identity" } });

            if (Response.Status == AppServiceResponseStatus.Success)
            {
                if (Response.Message.TryGetValue("Identity", out object Identity))
                {
                    switch (Convert.ToString(Identity))
                    {
                    case "FullTrustProcess":
                    {
                        lock (Locker)
                        {
                            if (Response.Message.TryGetValue("PreviousExplorerId", out object PreviousExplorerId))
                            {
                                if (ServiceAndClientConnections.FirstOrDefault((Pair) => Pair.ClientProcessId == Convert.ToString(PreviousExplorerId)) is ServerAndClientPair ConnectionPair)
                                {
                                    if (ConnectionPair.Server != null)
                                    {
                                        ConnectionPair.Server.Dispose();
                                    }

                                    ConnectionPair.Server = IncomeConnection;
                                }
                                else
                                {
                                    throw new InvalidDataException("Could not find PreviousExplorerId in ServiceAndClientConnections");
                                }
                            }
                            else
                            {
                                if (ServiceAndClientConnections.FirstOrDefault((Pair) => Pair.Server == null) is ServerAndClientPair ConnectionPair)
                                {
                                    ConnectionPair.Server = IncomeConnection;
                                }
                                else
                                {
                                    ServiceAndClientConnections.Add(new ServerAndClientPair(IncomeConnection, null, string.Empty));
                                }
                            }
                        }

                        break;
                    }

                    case "UWP":
                    {
                        lock (Locker)
                        {
                            if (Response.Message.TryGetValue("ProcessId", out object ProcessId))
                            {
                                if (ServiceAndClientConnections.FirstOrDefault((Pair) => Pair.Client == null) is ServerAndClientPair ConnectionPair)
                                {
                                    ConnectionPair.Client          = IncomeConnection;
                                    ConnectionPair.ClientProcessId = Convert.ToString(ProcessId);
                                }
                                else
                                {
                                    ServiceAndClientConnections.Add(new ServerAndClientPair(null, IncomeConnection, Convert.ToString(ProcessId)));
                                }
                            }
                            else
                            {
                                throw new InvalidDataException("Must contains ProcessId in response");
                            }
                        }

                        break;
                    }
                    }
                }
            }
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();

            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();

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

            if (triggerDetails != null && triggerDetails.Name == "VoiceCommandService")
            {
                Debug.WriteLine(triggerDetails.Name);
                try
                {
                    voiceServiceConnection =
                        VoiceCommandServiceConnection.FromAppServiceTriggerDetails(
                            triggerDetails);

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    // GetVoiceCommandAsync establishes initial connection to Cortana, and must be called prior to any
                    // messages sent to Cortana. Attempting to use ReportSuccessAsync, ReportProgressAsync, etc
                    // prior to calling this will produce undefined behavior.
                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                    // Depending on the operation (defined in AdventureWorks:AdventureWorksCommands.xml)
                    // perform the appropriate command.
                    Debug.WriteLine(voiceCommand.CommandName);


                    switch (voiceCommand.CommandName)
                    {
                    case "PowerOnOff":
                        //await ReportStatus(voiceCommand.Properties["device"][0]);
                        var PowerTarget = voiceCommand.Properties["target"][0];
                        var onoff       = voiceCommand.Properties["onoff"][0];
                        await SendCompletionMessageForPowerOnOff(PowerTarget, onoff);

                        break;

                    case "reportStatus":
                        var ReportTarget = voiceCommand.Properties["target"][0];
                        await SendCompletionMessageForReport(ReportTarget);

                        break;

                    case "reportAppointment":
                        var AppointmentTarget = voiceCommand.Properties["Days"][0];
                        await SendCompletionMessageForAppointmentReport(AppointmentTarget);

                        break;

                    case "SetTemperature":
                        var Temperature = voiceCommand.SpeechRecognitionResult.SemanticInterpretation.Properties["TemperatureNumber"].FirstOrDefault().ToString();
                        await SendCompletionMessageForSetTemperature(Temperature);

                        break;

                    case "StartFan":
                        //var startmin = voiceCommand.SpeechRecognitionResult.SemanticInterpretation.Properties["TemperatureNumber"].FirstOrDefault().ToString();
                        var startmin = voiceCommand.Properties["fanstartminutes"][0];
                        await SendCompletionMessageForFan(false, startmin);

                        break;

                    case "StopFan":
                        await SendCompletionMessageForFan(true, string.Empty);

                        break;

                    case "AskNest":
                        var NestTarget = voiceCommand.Properties["NestDevice"][0];
                        await SendCompletionMessageForAskNest(NestTarget);

                        break;

                    default:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
                finally
                {
                    if (this.serviceDeferral != null)
                    {
                        // Complete the service deferral.
                        this.serviceDeferral.Complete();
                    }
                }
            }
        }
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     _deferral              = taskInstance.GetDeferral();
     taskInstance.Canceled += OnTaskCancelled;
     BackgroundMediaPlayer.MessageReceivedFromBackground += OnBackgroundMessageReceived;
 }
Beispiel #35
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral_ = taskInstance.GetDeferral();
            Debug.WriteLine("NotifyTask started");
            try
            {
                var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("UserSession.dat", CreationCollisionOption.OpenIfExists);

                var r = await FileIO.ReadTextAsync(file);

                if (string.IsNullOrEmpty(r))
                {
                    return;
                }
                if (r.Length < 100)
                {
                    return;
                }
                string User = "******"; string Pass = "******";
                InstaApi = InstaApiBuilder.CreateBuilder()
                           .SetUser(new UserSessionData {
                    UserName = User, Password = Pass
                })
                           .UseLogger(new DebugLogger(LogLevel.Exceptions))
                           .Build();
                InstaApi.LoadStateDataFromStream(r);
                if (!InstaApi.IsUserAuthenticated)
                {
                    await InstaApi.LoginAsync();
                }
                if (!InstaApi.IsUserAuthenticated)
                {
                    return;
                }
                var activities = await InstaApi.GetRecentActivityAsync(PaginationParameters.MaxPagesToLoad(1));

                Notifies = await Load();

                if (Notifies == null)
                {
                    Notifies = new NotifyList();
                }
                if (activities.Succeeded)
                {
                    const int MAX = 9;
                    int       ix  = 0;
                    foreach (var item in activities.Value.Items)
                    {
                        var text = item.Text;
                        if (item.Text.Contains(" "))
                        {
                            text = text.Substring(text.IndexOf(" ") + 1);
                            text = text.TrimStart();
                        }
                        if (!Notifies.IsExists(text))
                        {
                            try
                            {
                                var n = new NotifyClass
                                {
                                    IsShowing      = false,
                                    ProfileId      = item.ProfileId,
                                    ProfilePicture = item.ProfileImage,
                                    Text           = text,
                                    TimeStamp      = item.TimeStamp.ToString(),
                                    Type           = item.Type,
                                };

                                if (item.InlineFollow == null)
                                {
                                    var user = await InstaApi.GetUserInfoByIdAsync(item.ProfileId);

                                    if (user.Succeeded)
                                    {
                                        n.Username = user.Value.Username;
                                    }
                                }
                                else
                                {
                                    n.Username       = item.InlineFollow.User.UserName;
                                    n.IsFollowingYou = item.InlineFollow.IsFollowing;
                                }
                                Notifies.Add(n);
                            }
                            catch { }
                        }
                        ix++;
                        if (ix > MAX)
                        {
                            break;
                        }
                    }
                    var list = Notifies;
                    list.Reverse();
                    for (int i = 0; i < list.Count; i++)
                    {
                        var item = list[i];
                        if (!string.IsNullOrEmpty(item.Username))
                        {
                            if (!item.IsShowing)
                            {
                                NotifyHelper.CreateNotifyAction($"@{item.Username}",
                                                                item.Text,
                                                                item.ProfilePicture);
                                Notifies[i].IsShowing = true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Notify ex: " + ex.Message);
                Debug.WriteLine("Source: " + ex.Source);
                Debug.WriteLine("StackTrace: " + ex.StackTrace);
            }
            await Save();

            await Task.Delay(1000);

            deferral_.Complete();
        }
Beispiel #36
0
 public Task RunAsync(IBackgroundTaskInstance taskInstance)
 {
     _deferral = taskInstance?.GetDeferral() ?? throw new ArgumentNullException(nameof(taskInstance));
     return(RunAsync());
 }
Beispiel #37
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            bool isLoad = false;
            PasswordCredential credential = null;
            var vault          = new PasswordVault();
            var credentialList = vault.FindAllByResource("ZSCY");

            if (credentialList.Count == 1)
            {
                credentialList[0].RetrievePassword();
                credential = credentialList[0];
            }
            try
            {
                var list = DatabaseMethod.ToModel();

                BackgroundTaskDeferral deferral1 = taskInstance.GetDeferral();
                if (list.Count > 0)
                {
                    //上传上次未上传的
                    foreach (var item in list)
                    {
                        if (item.Id == null)
                        {
                            string content = "";
                            isLoad = true;
                            MyRemind tempRemind = new MyRemind();
                            tempRemind        = JsonConvert.DeserializeObject <MyRemind>(item.json);
                            tempRemind.IdNum  = credential.Password;
                            tempRemind.StuNum = credential.UserName;
                            content           = await NetWork.httpRequest(@"http://hongyan.cqupt.edu.cn/cyxbsMobile/index.php/Home/Person/addTransaction", NetWork.addRemind(tempRemind));

                            Debug.WriteLine(content);

                            AddRemindReturn tempReturn = JsonConvert.DeserializeObject <AddRemindReturn>(content);
                            if (tempReturn.Status == 200)
                            {
                                string id = tempReturn.Id;
                                tempRemind.Id     = id;
                                tempRemind.IdNum  = null;
                                tempRemind.StuNum = null;
                                DatabaseMethod.EditDatabase(item.Num, id, JsonConvert.SerializeObject(tempRemind), item.Id_system);
                            }
                        }
                    }
                }

                deferral1.Complete();
                BackgroundTaskDeferral deferral2 = taskInstance.GetDeferral();
                if (isLoad)
                {
                }
                else
                {
                    RemindHelp.SyncRemind();
                }

                deferral2.Complete();
            }
            catch (Exception)
            {
                throw;
            }
        }
        private ApplicationDataContainer appSetting = ApplicationData.Current.LocalSettings; //本地存储
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            if (bool.Parse(appSetting.Values["isUseingBackgroundTask"].ToString()))
            {
                Debug.WriteLine("开始吐司通知后台任务");
                var vault          = new Windows.Security.Credentials.PasswordVault();
                var credentialList = vault.FindAllByResource(resourceName);
                credentialList[0].RetrievePassword();
                stuNum = credentialList[0].UserName;
                idNum  = credentialList[0].Password;
                try
                {
                    string letterstatus             = "";
                    BackgroundTaskDeferral deferral = taskInstance.GetDeferral();  //获取 BackgroundTaskDeferral 对象,表示后台任务延期
                    List <KeyValuePair <String, String> > paramList = new List <KeyValuePair <String, String> >();
                    paramList.Add(new KeyValuePair <string, string>("stuNum", stuNum));
                    paramList.Add(new KeyValuePair <string, string>("idNum", idNum));
                    paramList.Add(new KeyValuePair <string, string>("page", "0"));
                    paramList.Add(new KeyValuePair <string, string>("size", "15"));
                    letterstatus = await NetWork.getHttpWebRequest("cyxbsMobile/index.php/Home/Article/aboutme", paramList);

                    Debug.WriteLine("letterstatus" + letterstatus);
                    if (letterstatus != "")
                    {
                        string         aboutme           = "";
                        IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
                        try
                        {
                            IStorageFile storageFileRE = await applicationFolder.GetFileAsync("aboutme.txt");

                            IRandomAccessStream accessStream = await storageFileRE.OpenReadAsync();

                            using (StreamReader streamReader = new StreamReader(accessStream.AsStreamForRead((int)accessStream.Size)))
                            {
                                aboutme = streamReader.ReadToEnd();
                            }
                            Debug.WriteLine("aboutme:" + aboutme);
                            if (aboutme != letterstatus)
                            {
                                JObject obj = JObject.Parse(letterstatus);
                                if (Int32.Parse(obj["status"].ToString()) == 200)
                                {
                                    JArray jArray = (JArray)JsonConvert.DeserializeObject(obj["data"].ToString());
                                    if (jArray[0]["type"].ToString() == "praise")
                                    {
                                        Utils.Toast(jArray[0]["nickname"].ToString() + "赞了你~~\n你可能还有有新的消息,快来看看吧");
                                    }
                                    else if (jArray[0]["type"].ToString() == "remark")
                                    {
                                        Utils.actionsToast(jArray[0]["nickname"].ToString() + " 评论了 " + "\"" + jArray[0]["article_content"].ToString() + "\"", "\"" + jArray[0]["content"].ToString() + "\"", jArray[0]["article_id"].ToString() + "+" + jArray[0]["stunum"] + "+" + jArray[0]["nickname"]);
                                        //if (jArray[0]["content"].ToString().Length > 20)
                                        //{
                                        //    Utils.Toast(jArray[0]["nickname"].ToString() + "评论了你~\n" + "\"" + jArray[0]["content"].ToString().Substring(0, 20) + "\"" + "\n你可能还有有新的消息,快来看看吧");
                                        //}
                                        //else
                                        //{
                                        //    Utils.Toast(jArray[0]["nickname"].ToString() + "评论了你~\n" + "\"" + jArray[0]["content"].ToString() + "\"" + "\n你可能还有有新的消息,快来看看吧");
                                        //}
                                    }
                                    else
                                    {
                                        Utils.Toast("你可能有新的消息,快来看看吧");
                                    }
                                }
                                IStorageFile storageFileWR = await applicationFolder.CreateFileAsync("aboutme.txt", CreationCollisionOption.ReplaceExisting);

                                await FileIO.WriteTextAsync(storageFileWR, letterstatus);
                            }
                        }
                        catch (FileNotFoundException)
                        {
                            IStorageFile storageFileWR = await applicationFolder.CreateFileAsync("aboutme.txt", CreationCollisionOption.ReplaceExisting);

                            await FileIO.WriteTextAsync(storageFileWR, letterstatus);
                        }
                    }
                    deferral.Complete(); //所有的异步调用完成之后,释放延期,表示后台任务的完成
                    Debug.WriteLine("吐司通知后台任务结束");
                }
                catch (Exception)
                {
                    Debug.WriteLine("吐司通知后台任务异常");
                }
            }
        }
Beispiel #39
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral Deferral = taskInstance.GetDeferral();

            taskInstance.Canceled += TaskInstance_Canceled;

            try
            {
                await ClearUselessLogTask(Cancellation.Token);
                await UpdateSQLiteDatabaseTask();

                //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;
                        }

                        case 4:
                        {
                            ApplicationData.Current.LocalSettings.Values["GlobalizationStringForContextMenu"] = "Abrir con RX-Explorer";
                            break;
                        }

                        case 5:
                        {
                            ApplicationData.Current.LocalSettings.Values["GlobalizationStringForContextMenu"] = "Öffnen Sie im RX-Explorer";
                            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();
            }
        }
Beispiel #40
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     //Needed for running continuous background tasks in Windows IoT
     deferral = taskInstance.GetDeferral();
     RunBot();
 }
Beispiel #41
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     deferral = taskInstance.GetDeferral();
     InitGPIO();
     timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(3000));
 }
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     deferral = taskInstance.GetDeferral();
     ShowToast("Perform maintenance in the background");
     DoLongRunningMaintenance();
 }
Beispiel #43
0
        protected async override void OnRun(IBackgroundTaskInstance taskInstance)
        {
            this.serviceDeferral   = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            VoiceCommandUserMessage userMessage;
            VoiceCommandResponse    response;

            try
            {
                voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                voiceServiceConnection.VoiceCommandCompleted += VoiceCommandCompleted;
                VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                switch (voiceCommand.CommandName)
                {
                case "next":

                    var appointment = (await DataSource.GetInstance().GetAppointmentsAsync()).FirstOrDefault();
                    if (appointment != null)
                    {
                        var tiles = new List <VoiceCommandContentTile>();
                        var tile  = new VoiceCommandContentTile();

                        tile.ContentTileType = VoiceCommandContentTileType.TitleWith280x140IconAndText;

                        tiles.Add(tile);
                        tile.Image = await MapService.GetStaticRoute(280, 140, DataSource.GetCurrentLocation(), appointment.Location);

                        userMessage = new VoiceCommandUserMessage()
                        {
                            SpokenMessage  = "Your next appointment is the " + appointment.FamilyName + " family. It looks like you are 20 minutes away, should I let them know?",
                            DisplayMessage = "Your next appointment is the " + appointment.FamilyName + " family."
                        };

                        var repromptMessage = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = "Should I let the " + appointment.FamilyName + " family know of your arrival?",
                            SpokenMessage  = "Should I let the " + appointment.FamilyName + " family know of your arrival?"
                        };

                        response = VoiceCommandResponse.CreateResponseForPrompt(userMessage, repromptMessage, tiles);
                        var userResponse = await voiceServiceConnection.RequestConfirmationAsync(response);

                        string secondResponse;
                        if (userResponse.Confirmed)
                        {
                            secondResponse = "Great, I'll take care of it!";
                        }
                        else
                        {
                            secondResponse = "OK, no problem!";
                        }

                        //userMessage = new VoiceCommandUserMessage()
                        //{
                        //    DisplayMessage = secondResponse + "Should I start navigation?",
                        //    SpokenMessage = secondResponse + "Should I start navigation?",
                        //};

                        //repromptMessage = new VoiceCommandUserMessage()
                        //{
                        //    DisplayMessage = "Should I start navigation?",
                        //    SpokenMessage = "Should I start navigation?",
                        //};

                        //response = VoiceCommandResponse.CreateResponseForPrompt(userMessage, repromptMessage, tiles);
                        //var userResponse = await voiceServiceConnection.RequestConfirmationAsync(response);

                        ////await Task.Delay(1000);


                        userMessage = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = secondResponse + " Safe driving!",
                            SpokenMessage  = secondResponse + " Safe driving!",
                        };

                        response = VoiceCommandResponse.CreateResponse(userMessage, tiles);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                    else
                    {
                        userMessage = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = "All done for today!",
                            SpokenMessage  = "You don't have any appointments for the rest of the day!"
                        };

                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }



                    break;

                case "what":

                    var appointments = (await DataSource.GetInstance().GetAppointmentsAsync()).Take(3);
                    if (appointments != null & appointments.Count() > 0)
                    {
                        var tiles = new List <VoiceCommandContentTile>();

                        foreach (var app in appointments)
                        {
                            var tile = new VoiceCommandContentTile();

                            tile.ContentTileType = VoiceCommandContentTileType.TitleWith68x68IconAndText;

                            tile.TextLine1 = app.FamilyName;
                            tile.TextLine2 = app.Address;
                            tile.Title     = app.Time.ToString("hh:mm");
                            tile.Image     = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/house.png"));

                            tiles.Add(tile);
                        }

                        userMessage = new VoiceCommandUserMessage()
                        {
                            SpokenMessage  = "Here are your next " + appointments.Count() + " appointments",
                            DisplayMessage = "Here are your next " + appointments.Count() + " appointments",
                        };

                        response = VoiceCommandResponse.CreateResponse(userMessage, tiles);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                    else
                    {
                        userMessage = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = "All done for today!",
                            SpokenMessage  = "You don't have any appointments for the rest of the day!"
                        };

                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }



                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                if (this.serviceDeferral != null)
                {
                    //Complete the service deferral
                    this.serviceDeferral.Complete();
                }
            }
        }
Beispiel #44
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();

            // 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 == "ListenAppVoiceCommandService")
            {
                try
                {
                    voiceServiceConnection =
                        VoiceCommandServiceConnection.FromAppServiceTriggerDetails(
                            triggerDetails);

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    // GetVoiceCommandAsync establishes initial connection to Cortana, and must be called prior to any
                    // messages sent to Cortana. Attempting to use ReportSuccessAsync, ReportProgressAsync, etc
                    // prior to calling this will produce undefined behavior.
                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                    // Depending on the operation (defined in ListenApp:ListenAppCommands.xml)
                    // perform the appropriate command.
                    switch (voiceCommand.CommandName)
                    {
                    case "changingStateOfLights":
                        var room  = voiceCommand.Properties["room"][0];
                        var state = voiceCommand.Properties["state"][0].Equals("on");
                        await SendCompletionMessageChangingState(room, state);

                        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());
                }
            }
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            var client = DigitServiceBuilder.Get();

            try
            {
                RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
                await client.LogAsync($"Received push {notification.Content}");

                var opts = new DigitBLEOptions();


                var content = JsonConvert.DeserializeObject <PushPayload>(notification.Content);
                switch (content.Action)
                {
                case PushActions.MeasureBattery:
                    if (opts.IsConfigured)
                    {
                        var bleClient      = new DigitBLEClient(opts);
                        var batteryService = new BatteryService(bleClient, client);
                        await batteryService.AddBatteryMeasurement();
                    }
                    else
                    {
                        await client.LogAsync($"Push error: no device configured.", 3);
                    }
                    break;

                case PushActions.SendTime:
                    if (opts.IsConfigured)
                    {
                        var bleClient = new DigitBLEClient(opts);
                        try
                        {
                            await bleClient.SetTime(DateTime.Now);
                        }
                        catch (DigitBLEExpcetion e)
                        {
                            await client.LogAsync($"Could not send time: {e.Message}", 3);
                        }
                    }
                    else
                    {
                        await client.LogAsync($"Push error: no device configured.", 3);
                    }
                    break;

                case PushActions.SendLocation:
                    var locationService = new LocationService(client);
                    await locationService.SendCurrentLocation();

                    break;

                default: break;
                }
            }
            catch (Exception e)
            {
                await client.LogAsync($"Unhandled background exception: {e.Message}", 3);
            }
            _deferral.Complete();
        }
Beispiel #46
0
        /// <summary>
        /// Performs the work of a background task.
        /// The system calls this method when the associated background task has been triggered.
        /// </summary>
        /// <param name="taskInstance">An interface to an instance of the background task</param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            taskInstance.GetDeferral();

            Update(taskInstance);
        }
Beispiel #47
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();

            await InitializeDeviceClientAsync();
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;

            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();
                }

                // Load the settings from configuration file exit application if missing or invalid
                StorageFile file = localFolder.GetFileAsync(ConfigurationFilename).AsTask().Result;

                applicationSettings = (JsonConvert.DeserializeObject <ApplicationSettings>(FileIO.ReadTextAsync(file).AsTask().Result));
            }
            catch (Exception ex)
            {
                this.logging.LogMessage("JSON configuration file load failed " + ex.Message, LoggingLevel.Error);
                return;
            }

            // Log the Application build, shield information etc.
            LoggingFields appllicationBuildInformation = new LoggingFields();

#if DRAGINO
            appllicationBuildInformation.AddString("Shield", "DraginoLoRaGPSHat");
#endif
#if ELECROW
            appllicationBuildInformation.AddString("Shield", "ElecrowRFM95IoTBoard");
#endif
#if M2M
            appllicationBuildInformation.AddString("Shield", "M2M1ChannelLoRaWanGatewayShield");
#endif
#if ELECTRONIC_TRICKS
            appllicationBuildInformation.AddString("Shield", "ElectronicTricksLoRaLoRaWANShield");
#endif
#if UPUTRONICS_RPIZERO_CS0
            appllicationBuildInformation.AddString("Shield", "UputronicsPiZeroLoRaExpansionBoardCS0");
#endif
#if UPUTRONICS_RPIZERO_CS1
            appllicationBuildInformation.AddString("Shield", "UputronicsPiZeroLoRaExpansionBoardCS1");
#endif
#if UPUTRONICS_RPIPLUS_CS0
            appllicationBuildInformation.AddString("Shield", "UputronicsPiPlusLoRaExpansionBoardCS0");
#endif
#if UPUTRONICS_RPIPLUS_CS1
            appllicationBuildInformation.AddString("Shield", "UputronicsPiPlusLoRaExpansionBoardCS1");
#endif
#if ADAFRUIT_RADIO_BONNET
            appllicationBuildInformation.AddString("Shield", "AdafruitRadioBonnet");
#endif
            appllicationBuildInformation.AddString("Timezone", TimeZoneSettings.CurrentTimeZoneDisplayName);
            appllicationBuildInformation.AddString("OSVersion", Environment.OSVersion.VersionString);
            appllicationBuildInformation.AddString("MachineName", Environment.MachineName);

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

            appllicationBuildInformation.AddString("ApplicationVersion", string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"));
            this.logging.LogEvent("Application starting", appllicationBuildInformation, LoggingLevel.Information);

            // Configure the AdaFruit API client
            LoggingFields adaFruitIOSettings = new LoggingFields();
            if (!string.IsNullOrEmpty(this.applicationSettings.AdaFruitIOBaseUrl))
            {
                this.adaFruitIOClient.BaseUrl = this.applicationSettings.AdaFruitIOBaseUrl;
                adaFruitIOSettings.AddString("BaseURL", this.applicationSettings.AdaFruitIOBaseUrl);
            }

            this.adaFruitIOClient.ApiKey = this.applicationSettings.AdaFruitIOApiKey;

            adaFruitIOSettings.AddString("APIKey", this.applicationSettings.AdaFruitIOApiKey);
            adaFruitIOSettings.AddString("UserName", this.applicationSettings.AdaFruitIOUserName);
            adaFruitIOSettings.AddString("GroupName", this.applicationSettings.AdaFruitIOGroupName);
            this.logging.LogEvent("AdaFruit.IO configuration", adaFruitIOSettings, LoggingLevel.Information);

            rfm9XDevice.OnReceive  += Rfm9XDevice_OnReceive;
            rfm9XDevice.OnTransmit += Rfm9XDevice_OnTransmit;

            rfm9XDevice.Initialise(this.applicationSettings.Frequency,
                                   rxDoneignoreIfCrcMissing: true,
                                   rxDoneignoreIfCrcInvalid: true,
                                   paBoost: this.applicationSettings.PABoost, maxPower: this.applicationSettings.MaxPower, outputPower: this.applicationSettings.OutputPower,
                                   ocpOn: this.applicationSettings.OCPOn, ocpTrim: this.applicationSettings.OCPTrim,
                                   lnaGain: this.applicationSettings.LnaGain, lnaBoost: this.applicationSettings.LNABoost,
                                   bandwidth: this.applicationSettings.Bandwidth, codingRate: this.applicationSettings.CodingRate, implicitHeaderModeOn: this.applicationSettings.ImplicitHeaderModeOn,
                                   spreadingFactor: this.applicationSettings.SpreadingFactor,
                                   rxPayloadCrcOn: true,
                                   symbolTimeout: this.applicationSettings.SymbolTimeout,
                                   preambleLength: this.applicationSettings.PreambleLength,
                                   payloadLength: this.applicationSettings.PayloadLength,
                                   payloadMaxLength: this.applicationSettings.PayloadMaxLength,
                                   freqHoppingPeriod: this.applicationSettings.FreqHoppingPeriod,
                                   lowDataRateOptimize: this.applicationSettings.LowDataRateOptimize,
                                   ppmCorrection: this.applicationSettings.PpmCorrection,

                                   detectionOptimize: this.applicationSettings.DetectionOptimize,
                                   invertIQ: this.applicationSettings.InvertIQ,
                                   detectionThreshold: this.applicationSettings.DetectionThreshold,
                                   syncWord: this.applicationSettings.SyncWord
                                   );

                        #if DEBUG
            rfm9XDevice.RegisterDump();
                        #endif

            rfm9XDevice.Receive(Encoding.UTF8.GetBytes(this.applicationSettings.Address));

            LoggingFields loRaSettings = new LoggingFields();
            loRaSettings.AddString("Address", this.applicationSettings.Address);
            loRaSettings.AddDouble("Frequency", this.applicationSettings.Frequency);
            loRaSettings.AddBoolean("PABoost", this.applicationSettings.PABoost);

            loRaSettings.AddUInt8("MaxPower", this.applicationSettings.MaxPower);
            loRaSettings.AddUInt8("OutputPower", this.applicationSettings.OutputPower);
            loRaSettings.AddBoolean("OCPOn", this.applicationSettings.OCPOn);
            loRaSettings.AddUInt8("OCPTrim", this.applicationSettings.OCPTrim);

            loRaSettings.AddString("LnaGain", this.applicationSettings.LnaGain.ToString());
            loRaSettings.AddBoolean("lnaBoost", this.applicationSettings.LNABoost);

            loRaSettings.AddString("codingRate", this.applicationSettings.CodingRate.ToString());
            loRaSettings.AddString("implicitHeaderModeOn", applicationSettings.ImplicitHeaderModeOn.ToString());
            loRaSettings.AddString("spreadingFactor", this.applicationSettings.SpreadingFactor.ToString());
            loRaSettings.AddBoolean("rxPayloadCrcOn", true);

            loRaSettings.AddUInt8("symbolTimeout", this.applicationSettings.SymbolTimeout);
            loRaSettings.AddUInt8("preambleLength", this.applicationSettings.PreambleLength);
            loRaSettings.AddUInt8("payloadLength", this.applicationSettings.PayloadLength);

            loRaSettings.AddUInt8("payloadMaxLength", this.applicationSettings.PayloadMaxLength);
            loRaSettings.AddUInt8("freqHoppingPeriod", this.applicationSettings.FreqHoppingPeriod);
            loRaSettings.AddBoolean("lowDataRateOptimize", this.applicationSettings.LowDataRateOptimize);
            loRaSettings.AddUInt8("ppmCorrection", this.applicationSettings.PpmCorrection);

            loRaSettings.AddString("detectionOptimize", this.applicationSettings.DetectionOptimize.ToString());
            loRaSettings.AddBoolean("invertIQ", this.applicationSettings.InvertIQ);
            loRaSettings.AddString("detectionThreshold", this.applicationSettings.DetectionThreshold.ToString());
            loRaSettings.AddUInt8("SyncWord", this.applicationSettings.SyncWord);

            this.logging.LogEvent("LoRa configuration", loRaSettings, LoggingLevel.Information);

            this.deferral = taskInstance.GetDeferral();
        }
Beispiel #49
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Fug me");
            // Take a service deferral so the service isn&#39;t terminated.
            serviceDeferral = taskInstance.GetDeferral();

            taskInstance.Canceled       += TaskInstance_Canceled;
            taskInstance.Task.Completed += Task_Completed;

            var triggerDetails =
                taskInstance.TriggerDetails as AppServiceTriggerDetails;

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

                    voiceServiceConnection.VoiceCommandCompleted +=
                        VoiceCommandCompleted;

                    var voiceCommand = await
                                       voiceServiceConnection.GetVoiceCommandAsync();

                    switch (voiceCommand.CommandName)
                    {
                    case "ToDoFetcher":
                    {
                        SendCompletionMessageFortodolist();
                        break;
                    }

                    case "TodoCounter":
                    {
                        taskcounter();
                        break;
                    }

                    case "addtask":
                    {
                        LaunchAppInForeground();
                        break;
                    }

                    //   As a last resort, launch the app in the foreground.
                    default:
                        LaunchAppInForeground();
                        break;
                    }
                }
                finally
                {
                    if (serviceDeferral != null)
                    {
                        // Complete the service deferral.
                        serviceDeferral.Complete();
                    }
                }
            }
        }
Beispiel #50
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;

            // 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 == "CortanaTodoVoiceService")
            {
                try
                {
                    // Get the connection
                    voiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);

                    // Subscribe to commands completed
                    voiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    // Get the command
                    VoiceCommand voiceCommand = await voiceConnection.GetVoiceCommandAsync();

                    Debug.WriteLine(string.Format("Command Name: {0}", voiceCommand.CommandName));
                    Debug.WriteLine(string.Format("Result.Text: {0}", voiceCommand.SpeechRecognitionResult.Text));
                    foreach (var rule in voiceCommand.SpeechRecognitionResult.RulePath)
                    {
                        Debug.WriteLine(string.Format("Rule: {0}", rule));
                    }
                    foreach (var prop in voiceCommand.Properties)
                    {
                        foreach (var value in prop.Value)
                        {
                            Debug.WriteLine(string.Format("Prop: {0} Val: {1}", prop.Key, value));
                        }
                    }
                    foreach (var prop in voiceCommand.SpeechRecognitionResult.SemanticInterpretation.Properties)
                    {
                        foreach (var value in prop.Value)
                        {
                            Debug.WriteLine(string.Format("S-Prop: {0} Val: {1}", prop.Key, value));
                        }
                    }

                    // Depending on the operation (defined in VoiceCommands.xml)
                    // perform the appropriate command.
                    string listName = null;
                    string itemName = null;
                    switch (voiceCommand.CommandName)
                    {
                    case "addToList":
                        listName = voiceCommand.Properties["listName"].FirstOrDefault();
                        itemName = voiceCommand.Properties["itemName"].FirstOrDefault();
                        await HandleAddToListAsync(listName, itemName);

                        break;

                    case "addNewList":
                        listName = voiceCommand.Properties["listNameNL"].FirstOrDefault();
                        await HandleNewListAsync(listName);

                        break;

                    case "markItemComplete":
                        listName = voiceCommand.Properties["listName"].FirstOrDefault();
                        itemName = voiceCommand.Properties["itemName"].FirstOrDefault();
                        await HandleMarkItemCompleteAsync(listName, itemName);

                        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.
                        await RequestAppLaunchAsync();

                        break;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
            }
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            HttpClient httpClient = new HttpClient();
            //Add a user-agent header to the GET request.
            var headers = httpClient.DefaultRequestHeaders;
            //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
            //especially if the header value is coming from user input.
            string header = "ie";

            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }
            header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
            if (!headers.UserAgent.TryParseAdd(header))
            {
                throw new Exception("Invalid header value: " + header);
            }
            Uri requestUri = new Uri("http://www.google.com");
            //Send the GET request asynchronously and retrieve the response as a string.
            HttpResponseMessage httpResponse = new HttpResponseMessage();
            string httpResponseBody          = "";

            try
            {
                //Send the GET request
                httpResponse = await httpClient.GetAsync(requestUri);

                httpResponse.EnsureSuccessStatusCode();
                httpResponseBody = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
            if (httpResponseBody.Contains("172.16.0.30"))
            {
                var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
                try
                {
                    if (localSettings.Values.ContainsKey("CyberRoam_UserName"))
                    {
                        username = localSettings.Values["CyberRoam_UserName"].ToString();
                    }
                    if (localSettings.Values.ContainsKey("CyberRoam_Password"))
                    {
                        password = localSettings.Values["CyberRoam_Password"].ToString();
                    }
                    //Create an HTTP client object
                    httpClient = new HttpClient();
                    //Add a user-agent header to the GET request.
                    headers = httpClient.DefaultRequestHeaders;
                    //The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
                    //especially if the header value is coming from user input.
                    header = "ie";
                    if (!headers.UserAgent.TryParseAdd(header))
                    {
                        throw new Exception("Invalid header value: " + header);
                    }
                    header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
                    if (!headers.UserAgent.TryParseAdd(header))
                    {
                        throw new Exception("Invalid header value: " + header);
                    }
                    List <KeyValuePair <string, string> > content = new List <KeyValuePair <string, string> >();
                    content.Add(new KeyValuePair <string, string>("mode", "191"));
                    content.Add(new KeyValuePair <string, string>("username", username));
                    content.Add(new KeyValuePair <string, string>("password", password));
                    content.Add(new KeyValuePair <string, string>("a", (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond) + ""));
                    content.Add(new KeyValuePair <string, string>("producttype", "0"));
                    requestUri = new Uri(loginURL);
                    //Send the GET request asynchronously and retrieve the response as a string.
                    httpResponse     = new HttpResponseMessage();
                    httpResponseBody = "";
                    //Send the GET request
                    httpResponse = await httpClient.PostAsync(requestUri, new HttpFormUrlEncodedContent(content));

                    httpResponse.EnsureSuccessStatusCode();
                    httpResponseBody = await httpResponse.Content.ReadAsStringAsync();

                    if (httpResponseBody.Contains("You have successfully logged in"))
                    {
                        var toastTemplate     = ToastTemplateType.ToastImageAndText01;
                        var toastXml          = ToastNotificationManager.GetTemplateContent(toastTemplate);
                        var toastTextElements = toastXml.GetElementsByTagName("text");
                        toastTextElements[0].AppendChild(toastXml.CreateTextNode("CyberConnect Logged you to Cyberroam."));
                        var toast = new ToastNotification(toastXml);
                        ToastNotificationManager.CreateToastNotifier().Show(toast);
                    }
                }
                catch (Exception e)
                {
                }
            }
            _deferral.Complete();
        }
Beispiel #52
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();

            StartApp();
        }
Beispiel #53
0
        /// <summary>
        /// Main thread for communication with pebble on a background task.
        ///
        /// Reading the state of the process is possible via the local settings BackgroundIsRunning. Synchronization via
        /// Mutex is not possible due to heavy use of await statements. The mutex will be abandoned and releasing gives
        /// an exception.
        /// </summary>
        /// <param name="taskInstance"></param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            var def = taskInstance.GetDeferral();

            var localSettings = ApplicationData.Current.LocalSettings;

            Handler = -1;
            localSettings.Values[Constants.BackgroundCommunicatieError] = (int)BCState.OK;

            try
            {
                System.Diagnostics.Debug.WriteLine("Start BackgroundCommunication");

                //Connect
                _pc     = PebbleConnector.GetInstance();
                Handler = await _pc.Connect(-1);

                if (_pc.IsConnected)
                {
                    AddToLog("Connection made with Pebble Time");

                    Log = new ObservableCollection <string>();
                    Log.CollectionChanged += Log_CollectionChanged;

                    _pc.Pebble.Log = Log;
                    _pc.StartReceivingMessages();
                    _pc.disconnectEventHandler           += _pc_disconnectEventHandler;
                    _pc.Pebble._protocol.MessageReceived += AppMessageReceived;

                    bool Continue = true;

                    //initialise settings

                    while (Continue)
                    {
                        try
                        {
                            localSettings.Values[Constants.BackgroundCommunicatieIsRunning] = true;

                            if (_pc.IsConnected)
                            {
                                await PaceHandler();

                                await TennisHandler();

                                //await Wipe();

                                await Synchronize();

                                await Select();

                                await Launch();

                                await AddItem();

                                await PebbleKitExecution();
                            }
                            else
                            {
                                await Reconnect();
                            }
                        }
                        catch (Exception e)
                        {
                            System.Diagnostics.Debug.WriteLine(e.Message + e.StackTrace);
                        }

                        await ProcessDelay();

                        //Check if continue
                        Continue = ((int)localSettings.Values[Constants.BackgroundCommunicatieContinue] != 0);
                    }

                    await PaceHandlerCleanup();

                    localSettings.Values[Constants.BackgroundTennis] = false;
                    localSettings.Values[Constants.BackgroundPace]   = false;

                    _pc.Pebble._protocol.MessageReceived -= AppMessageReceived;
                }
                else
                {
                    AddToLog("Connection with Pebble Time Failed.");
                    localSettings.Values[Constants.BackgroundCommunicatieError] = (int)BCState.ConnectionFailed;

                    if (_pc.LastError.Length > 0)
                    {
                        AddToLog(_pc.LastError);
                    }
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception BackgroundCommunication: " + e.Message);
                localSettings.Values[Constants.BackgroundCommunicatieError] = (int)BCState.ExceptionOccurred;
            }
            finally
            {
                localSettings.Values[Constants.BackgroundCommunicatieIsRunning] = false;

                //Disconnect
                if (_pc.IsConnected)
                {
                    _pc.Disconnect(Handler);

                    AddToLog("Disconnected from Pebble Time");
                }
            }

            System.Diagnostics.Debug.WriteLine("End BackgroundCommunication");

            def.Complete();
        }
Beispiel #54
0
 public void RunAsync(IBackgroundTaskInstance taskInstance)
 {
     _deferral = taskInstance.GetDeferral();
     Task.Factory.StartNew(this.Initialize, TaskCreationOptions.RunContinuationsAsynchronously);
 }
Beispiel #55
0
        protected override async void OnRun(IBackgroundTaskInstance taskInstance)
        {
            this.serviceDeferral   = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;


            VoiceCommandResponse response;

            try
            {
                voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                voiceServiceConnection.VoiceCommandCompleted += VoiceCommandCompleted;
                VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                VoiceCommandUserMessage userMessage = new VoiceCommandUserMessage();

                List <VoiceCommandContentTile> contentTiles;

                switch (voiceCommand.CommandName)
                {
                case "what":

                    _todoItemRepository = TODOAdaptiveUISample.Repositories.TodoItemFileRepository.GetInstance();
                    var data = await _todoItemRepository.RefreshTodoItemsAsync();

                    contentTiles = new List <VoiceCommandContentTile>();

                    userMessage.SpokenMessage = "Your Top To Do's are: ";

                    foreach (var item in data.Where(x => x.IsComplete == false).OrderBy(x => x.DueDate).Take((int)VoiceCommandResponse.MaxSupportedVoiceCommandContentTiles))
                    {
                        var tile = new VoiceCommandContentTile();
                        tile.ContentTileType = VoiceCommandContentTileType.TitleWithText;
                        tile.Title           = item.Title;
                        //tile.TextLine1 = item.Details;
                        contentTiles.Add(tile);

                        userMessage.SpokenMessage += item.Title + ", ";
                    }

                    userMessage.DisplayMessage = "Here are the top " + contentTiles.Count + " To Do's";



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

                    break;


                case "new":
                    var todo = voiceCommand.Properties["todo"][0];

                    var responseMessage = new VoiceCommandUserMessage()
                    {
                        DisplayMessage = String.Format("Add \"{0}\" to your To Do's?", todo),
                        SpokenMessage  = String.Format("Do you want me to add \"{0}\" to your To Do's?", todo)
                    };

                    var repeatMessage = new VoiceCommandUserMessage()
                    {
                        DisplayMessage = String.Format("Are you sure you want me to add \"{0}\" to your To Do's?", todo),
                        SpokenMessage  = String.Format("Are you sure you want me to add \"{0}\" to your To Do's?", todo)
                    };

                    bool confirmed = false;
                    response = VoiceCommandResponse.CreateResponseForPrompt(responseMessage, repeatMessage);
                    try
                    {
                        var confirmation = await voiceServiceConnection.RequestConfirmationAsync(response);

                        confirmed = confirmation.Confirmed;
                    }
                    catch
                    {
                    }
                    if (confirmed)
                    {
                        _todoItemRepository = TODOAdaptiveUISample.Repositories.TodoItemFileRepository.GetInstance();
                        var i = _todoItemRepository.Factory(title: todo);
                        await _todoItemRepository.InsertTodoItem(i);

                        var todos = await _todoItemRepository.RefreshTodoItemsAsync();

                        contentTiles = new List <VoiceCommandContentTile>();

                        foreach (var itm in todos.Where(x => x.IsComplete == false).OrderBy(x => x.DueDate).Take((int)VoiceCommandResponse.MaxSupportedVoiceCommandContentTiles))
                        {
                            var tile = new VoiceCommandContentTile();
                            tile.ContentTileType = VoiceCommandContentTileType.TitleWithText;
                            tile.Title           = itm.Title;
                            contentTiles.Add(tile);
                        }

                        userMessage.SpokenMessage  = "Done and Done! Here are your top To Do's";
                        userMessage.DisplayMessage = "Here are your top " + contentTiles.Count + " To Do's";

                        response = VoiceCommandResponse.CreateResponse(userMessage, contentTiles);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }
                    else
                    {
                        userMessage.DisplayMessage = userMessage.SpokenMessage = "OK then";
                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }



                    break;
                }
            }
            catch (Exception ex)
            {
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }
            finally
            {
                if (this.serviceDeferral != null)
                {
                    //Complete the service deferral
                    this.serviceDeferral.Complete();
                }
            }
        }
Beispiel #56
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
#if !DEBUG
            // Check if the app is alread in the foreground and if so, don't run the agent
            if (AgentSync.IsApplicationLaunched())
            {
                return;
            }
#endif
            // Get a deferral, to prevent the task from closing prematurely
            // while asynchronous code is still running.
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            // Initialize the app
            await Platform.Current.AppInitializingAsync(InitializationModes.Background);

            Platform.Current.Logger.Log(LogLevels.Information, "Starting background task '{0}'...", taskInstance.Task.Name);

            CancellationTokenSource cts = new CancellationTokenSource();

            taskInstance.Canceled += (sender, reason) =>
            {
                Platform.Current.Logger.Log(LogLevels.Warning, "Background task '{0}' is being cancelled due to '{1}'...", taskInstance.Task.Name, reason);

                // Store info on why this task was cancelled
                _info.CancelReason = reason.ToString();
                _info.EndTime      = DateTime.UtcNow;

                // Cancel/dispose the token
                cts?.Cancel();
                cts?.Dispose();
            };

            try
            {
                // Execute the background work
                _info.StartTime = DateTime.UtcNow;
                await Platform.Current.TimedBackgroundWorkAsync(BackgroundWorkCost.CurrentBackgroundWorkCost, cts.Token);

                // Task ran without error
                _info.RunSuccessfully = true;
                Platform.Current.Logger.Log(LogLevels.Information, "Completed execution of background task '{0}'!", taskInstance.Task.Name);
            }
            catch (OperationCanceledException)
            {
                // Task was aborted via the cancelation token
                Platform.Current.Logger.Log(LogLevels.Warning, "Background task '{0}' had an OperationCanceledException with reason '{1}'.", taskInstance.Task.Name, _info.CancelReason);
            }
            catch (Exception ex)
            {
                // Task threw an exception, store/log the error details
                _info.ExceptionDetails = ex.ToString();
                Platform.Current.Logger.LogErrorFatal(ex, "Background task '{0}' failed with exception to run to completion: {1}", taskInstance.Task.Name, ex.Message);
            }
            finally
            {
                _info.EndTime = DateTime.UtcNow;

                // Store the task status information
                Platform.Current.Storage.SaveSetting("TASK_" + taskInstance.Task.Name, _info, Windows.Storage.ApplicationData.Current.LocalSettings);

                // Shutdown the task
                Platform.Current.AppSuspending();
                deferral.Complete();
            }
        }
Beispiel #57
0
        /// <summary>
        /// Starter baggrundstask, der kan loaded nyheder til finansstyring.
        /// </summary>
        /// <param name="taskInstance">Instans af baggrundstasken.</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            lock (SyncRoot)
            {
                if (_isLoading)
                {
                    return;
                }
                _isLoading = true;
            }

            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            try
            {
                WindowsRuntimeResourceManager.PatchResourceManagers();

                ConfigurationProvider configurationProvider = new ConfigurationProvider();

                IDictionary <string, object> finansstyringConfiguration = configurationProvider.Settings
                                                                          .Where(m => FinansstyringKonfigurationRepository.Keys.Contains(m.Key))
                                                                          .ToDictionary(m => m.Key, m => m.Value);
                IFinansstyringKonfigurationRepository finansstyringKonfigurationRepository = new FinansstyringKonfigurationRepository();
                finansstyringKonfigurationRepository.KonfigurationerAdd(finansstyringConfiguration);

                IEnumerable <INyhedModel> finansstyringsnyheder;
                try
                {
                    IFinansstyringRepository finansstyringRepository = new FinansstyringRepository(finansstyringKonfigurationRepository);
                    finansstyringsnyheder = await FinansstyringsnyhederGetAsync(finansstyringRepository);
                }
                catch (IntranetGuiOfflineRepositoryException)
                {
                    ILocaleDataStorage localeDataStorage = new LocaleDataStorage(finansstyringKonfigurationRepository.LokalDataFil, finansstyringKonfigurationRepository.SynkroniseringDataFil, FinansstyringRepositoryLocale.XmlSchema);
                    localeDataStorage.OnHasLocaleData      += LocaleDataStorageHelper.HasLocaleDataEventHandler;
                    localeDataStorage.OnCreateReaderStream += LocaleDataStorageHelper.CreateReaderStreamEventHandler;
                    localeDataStorage.OnCreateWriterStream += LocaleDataStorageHelper.CreateWriterStreamEventHandler;

                    IFinansstyringRepository finansstyringRepository = new FinansstyringRepositoryLocale(finansstyringKonfigurationRepository, localeDataStorage);

                    Task <IEnumerable <INyhedModel> > finansstyringsnyhederGetTask = FinansstyringsnyhederGetAsync(finansstyringRepository);
                    finansstyringsnyhederGetTask.Wait();
                    finansstyringsnyheder = finansstyringsnyhederGetTask.Result;
                }

                UpdateTile(finansstyringsnyheder);
            }
            catch (AggregateException aggregateException)
            {
                aggregateException.Handle(ex =>
                {
                    Logger.LogError(ex);
                    return(true);
                });
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
            finally
            {
                lock (SyncRoot)
                {
                    _isLoading = false;
                }
                deferral.Complete();
            }
        }
Beispiel #58
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();

            StorageFolder folder = ApplicationData.Current.LocalFolder;

            //StorageFile logsFile = await folder.CreateFileAsync("BGtask.txt", CreationCollisionOption.OpenIfExists);
            //string txt = "[RUN]: " + DateTime.Now.ToString() + Environment.NewLine;
            //await FileIO.WriteTextAsync(logsFile, txt);

            // This event is signaled when the operation completes
            opCompletedEvent = new ManualResetEvent(false);
            SecondaryAuthenticationFactorAuthentication.AuthenticationStageChanged += OnStageChanged;
            //ShowToastNotification("BG Task Hit!");


            if (taskInstance.TriggerDetails is DeviceWatcherTriggerDetails)
            {
                DeviceWatcherTriggerDetails triggerDetails = (DeviceWatcherTriggerDetails)taskInstance.TriggerDetails;

                foreach (DeviceWatcherEvent e in triggerDetails.DeviceWatcherEvents)
                {
                    switch (e.Kind)
                    {
                    case DeviceWatcherEventKind.Add:
                        Debug.WriteLine("[RUN] Add: " + e.DeviceInformation.Id);
                        deferral = taskInstance.GetDeferral();
                        try
                        {
                            SecondaryAuthenticationFactorAuthenticationStageInfo authStageInfo = await SecondaryAuthenticationFactorAuthentication.GetAuthenticationStageInfoAsync();

                            SecondaryAuthenticationFactorAuthenticationStage stage = authStageInfo.Stage;
                            //Debugger.Break();
                            if ((authStageInfo.Stage == SecondaryAuthenticationFactorAuthenticationStage.WaitingForUserConfirmation) ||
                                (authStageInfo.Stage == SecondaryAuthenticationFactorAuthenticationStage.CollectingCredential))
                            {
                                System.Diagnostics.Debug.WriteLine("[RUN] Perform Auth / plug trigger");
                                Task  t = PerformAuthentication();
                                await t;
                            }
                            //Debugger.Break();
                            if (e.DeviceInformation.Name.Contains("Ledger"))
                            {
                                Task  t = writeConnectedRegisteredDevices();
                                await t;
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                        finally
                        {
                            deferral.Complete();
                        }
                        break;

                    //case DeviceWatcherEventKind.Update:
                    //    Debug.WriteLine("[RUN] Update: " + e.DeviceInformationUpdate.Id);
                    //    deferral = taskInstance.GetDeferral();
                    //
                    //    try
                    //    {
                    //        Task i = writeConnectedRegisteredDevices();
                    //        await i;
                    //    }
                    //    catch (Exception ex)
                    //    {
                    //        Debugger.Break();
                    //    }
                    //    finally
                    //    {
                    //        deferral.Complete();
                    //    }
                    //    break;

                    case DeviceWatcherEventKind.Remove:
                        Debug.WriteLine("[RUN] Remove: " + e.DeviceInformationUpdate.Id);
                        deferral = taskInstance.GetDeferral();
                        try
                        {
                            List <dLock> pluggedRegisteredDeviceListBeforeRemove = await readConnectedRegisteredDevices();

                            List <Tuple <string, bool, bool> > pluggedRegisteredDeviceListBeforeRemove_tuple = new List <Tuple <string, bool, bool> >();
                            foreach (dLock device in pluggedRegisteredDeviceListBeforeRemove)
                            {
                                Tuple <string, bool, bool> newElem = new Tuple <string, bool, bool>(device.DeviceId, device.isDlockEnabled, device.isUsedForLastLogin);
                                pluggedRegisteredDeviceListBeforeRemove_tuple.Add(newElem);
                            }

                            IReadOnlyList <SecondaryAuthenticationFactorInfo> registeredDeviceList_removeEvent = await SecondaryAuthenticationFactorRegistration.FindAllRegisteredDeviceInfoAsync(
                                SecondaryAuthenticationFactorDeviceFindScope.User);

                            List <SecondaryAuthenticationFactorInfo> pluggedRegisteredDeviceListAfterRemove = await getConnectedRegisteredDeviceList(registeredDeviceList_removeEvent);

                            foreach (SecondaryAuthenticationFactorInfo deviceToCheck in pluggedRegisteredDeviceListAfterRemove)
                            {
                                foreach (dLock device in pluggedRegisteredDeviceListBeforeRemove)
                                {
                                    if (deviceToCheck.DeviceId == device.DeviceId)
                                    {
                                        var t = pluggedRegisteredDeviceListBeforeRemove_tuple.FirstOrDefault(i => i.Item1 == device.DeviceId);
                                        if (t != null)
                                        {
                                            // delete
                                            pluggedRegisteredDeviceListBeforeRemove_tuple.Remove(t);
                                        }
                                    }
                                }
                            }

                            bool   lockDevice = true;
                            string deviceId   = "";
                            for (int i = 0; i < pluggedRegisteredDeviceListBeforeRemove_tuple.Count(); i++)
                            {
                                deviceId = pluggedRegisteredDeviceListBeforeRemove_tuple[i].Item1;
                                if ((!pluggedRegisteredDeviceListBeforeRemove_tuple[i].Item2) || (!pluggedRegisteredDeviceListBeforeRemove_tuple[i].Item3))
                                {
                                    lockDevice = false;
                                }
                            }
                            if (lockDevice)
                            {
                                Task  t = LockDevice(deviceId);
                                await t;
                            }
                            await writeConnectedRegisteredDevices();
                        }
                        catch (Exception ex)
                        {
                        }
                        finally
                        {
                            deferral.Complete();
                        }
                        break;
                    }
                }
            }
            else
            {
                Debug.WriteLine("[RUN] Unknown trigger");
                deferral = taskInstance.GetDeferral();
                //try
                //{
                //    Task t = writeConnectedRegisteredDevices();
                //    await t;
                //}
                //catch (ConnectedRegisteredDevicesListTxtFileEmpty Ex)
                //{

                //}
                //finally
                //{
                //    deferral.Complete();
                //}
            }
            // Wait until the operation completes
            opCompletedEvent.WaitOne();

            deferral.Complete();
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            Defferal = taskInstance?.GetDeferral();

            //var details = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;
            //if (details != null)
            //{
            //    await Launcher.LaunchUriAsync(new Uri(details.Argument));
            //    Defferal.Complete();
            //    return;
            //}

            try
            {
                if (taskInstance != null) //we are already running -> started on demand
                {
                    ResourceLocator.RegisterBase();
                    ResourceLocator.RegisterAppDataServiceAdapter(new ApplicationDataServiceService());
                    ResourceLocator.RegisterPasswordVaultAdapter(new PasswordVaultProvider());
                    ResourceLocator.RegisterMessageDialogAdapter(new MessageDialogProvider());
                    ResourceLocator.RegisterHttpContextAdapter(new MalHttpContextProvider());
                    ResourceLocator.RegisterDataCacheAdapter(new Adapters.DataCache(null));
                    Credentials.Init();
                }
            }
            catch (Exception)
            {
                //app is running so we don't check, checks are conducted in runtime manually
                //Defferal?.Complete();
                //return;
            }


            List <MalNotification> notifications = new List <MalNotification>();

            try
            {
                if (
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.FriendRequestAcceptDeny) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.NewRelatedAnime) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.BlogComment) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.ClubMessages) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.ForumQuoute) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.FriendRequest) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.NowAiring) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.ProfileComment) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.Payment) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.UserMentions) ||
                    Settings.EnabledNotificationTypes.HasFlag(MalNotificationsTypes.WatchedTopics))
                {
                    notifications.AddRange(await MalNotificationsQuery.GetNotifications());
                    notifications =
                        notifications.Where(
                            notification =>
                            !notification.IsRead &&
                            (Settings.EnabledNotificationTypes & notification.Type) == notification.Type).ToList();
                }
            }
            catch (Exception)
            {
                //http exec error
            }


            if ((Settings.EnabledNotificationTypes & MalNotificationsTypes.Messages) == MalNotificationsTypes.Messages)
            {
                try
                {
                    var msgs = await AccountMessagesManager.GetMessagesAsync(1);

                    foreach (var malMessageModel in msgs)
                    {
                        if (!malMessageModel.IsRead)
                        {
                            notifications.Add(new MalNotification(malMessageModel)); //I'm assuming that Ids are unique
                        }
                    }
                }
                catch (Exception)
                {
                    //no messages
                }
            }

            bool watchedTopicsUpdated = false;

            foreach (var watchedTopic in ResourceLocator.HandyDataStorage.WatchedTopics.StoredItems)
            {
                if (!watchedTopic.OnCooldown)
                {
                    var count = await new ForumTopicMessageCountQuery(watchedTopic.Id).GetMessageCount(true);
                    if (count == null)
                    {
                        continue;
                    }

                    if (count > watchedTopic.LastCheckedReplyCount)
                    {
                        var notif = new MalNotification(watchedTopic);
                        var diff  = count - watchedTopic.LastCheckedReplyCount;
                        if (diff == 1)
                        {
                            notif.Content += " There is one new reply.";
                        }
                        else
                        {
                            notif.Content += $" There are {diff} new replies.";
                        }

                        notifications.Add(notif);

                        watchedTopic.OnCooldown            = true;
                        watchedTopic.LastCheckedReplyCount = count.Value;
                        watchedTopicsUpdated = true;
                    }
                }
            }
            if (watchedTopicsUpdated)
            {
                ResourceLocator.HandyDataStorage.WatchedTopics.SaveData();
            }

            if (!notifications.Any())
            {
                Defferal?.Complete();
                return;
            }

            var allTriggeredNotifications = (string)(ApplicationData.Current.LocalSettings.Values[nameof(RoamingDataTypes.ReadNotifications)] ?? string.Empty);
            var triggeredNotifications    = allTriggeredNotifications.Split(';').ToList();
            var triggeredAny = false;

            //trigger new notifications
            foreach (var notification in notifications)
            {
                if (triggeredNotifications.Contains(notification.Id))
                {
                    continue;
                }

                triggeredNotifications.Add(notification.Id);
                triggeredAny = true;
                ScheduleToast(notification);
            }
            //remove old triggered entries
            var presentNotifications = new List <string>();

            foreach (var triggeredNotification in triggeredNotifications)
            {
                if (notifications.Any(notif => notif.Id == triggeredNotification))
                {
                    presentNotifications.Add(triggeredNotification);
                }
            }

            ApplicationData.Current.LocalSettings.Values[nameof(RoamingDataTypes.ReadNotifications)] = string.Join(";", presentNotifications);

            if (!triggeredAny)
            {
                Defferal?.Complete();
            }
        }
Beispiel #60
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();
            var    userMessage1 = new VoiceCommandUserMessage();
            string book;

            taskInstance.Canceled += OnTaskCanceled;
            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            if (triggerDetails != null)
            {
                try
                {
                    voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;
                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                    switch (voiceCommand.CommandName)
                    {
                    case "bookFromXToY":
                        try
                        {
                            string source      = voiceCommand.SpeechRecognitionResult.SemanticInterpretation.Properties["bookFromX"].FirstOrDefault();
                            string destination = voiceCommand.SpeechRecognitionResult.SemanticInterpretation.Properties["bookFromY"].FirstOrDefault();
                            await SendCompletionMessageForBookFromXtoY(source, destination);
                        }
                        catch
                        {
                            userMessage1 = new VoiceCommandUserMessage();
                            book         = "Please give proper saved places";
                            userMessage1.DisplayMessage = userMessage1.SpokenMessage = book;
                            var response = VoiceCommandResponse.CreateResponse(userMessage1);
                            await voiceServiceConnection.ReportSuccessAsync(response);
                        }
                        break;

                    case "costEstimate":
                        try
                        {
                            string sourceCost      = voiceCommand.SpeechRecognitionResult.SemanticInterpretation.Properties["source"].First();
                            string destinationCost = voiceCommand.SpeechRecognitionResult.SemanticInterpretation.Properties["destination"].First();
                            await SendCompletionMessageForCostEstimate(sourceCost, destinationCost);
                        }
                        catch
                        {
                            userMessage1 = new VoiceCommandUserMessage();
                            book         = "Please give proper source and destination";
                            userMessage1.DisplayMessage = userMessage1.SpokenMessage = book;
                            var response = VoiceCommandResponse.CreateResponse(userMessage1);
                            await voiceServiceConnection.ReportSuccessAsync(response);
                        }
                        break;

                    case "costEstimateCustom":
                        //try
                        //{
                        string     destinationCost1 = voiceCommand.SpeechRecognitionResult.SemanticInterpretation.Properties["destination"].First();
                        string     slat, slng, token;
                        Geolocator locator = new Geolocator();
                        locator.DesiredAccuracyInMeters = 50;
                        var mPosition = await locator.GetGeopositionAsync();

                        slat  = mPosition.Coordinate.Point.Position.Latitude.ToString();
                        slng  = mPosition.Coordinate.Point.Position.Longitude.ToString();
                        token = Windows.Storage.ApplicationData.Current.LocalSettings.Values["Token"].ToString();
                        CabsAPI            api     = new CabsAPI();
                        ReverseGeoResposne current = await api.GetReverseCodingResultlatlng(token, slat + "," + slng);

                        string source1;
                        try
                        {
                            source1 = current.FormattedAddress.Substring(0, current.FormattedAddress.IndexOf(", Hyderabad"));
                        }
                        catch
                        {
                            source1 = current.FormattedAddress;
                        }
                        await SendCompletionMessageForCostEstimate(source1, destinationCost1);


                        //catch (Exception e)
                        //{
                        //    userMessage1 = new VoiceCommandUserMessage();
                        //    book = "please give proper Destination";
                        //    userMessage1.DisplayMessage = userMessage1.SpokenMessage = book;
                        //    var response = VoiceCommandResponse.CreateResponse(userMessage1);
                        //    await voiceServiceConnection.ReportSuccessAsync(response);
                        //}
                        break;

                    case "toCustomLocation":
                        try
                        {
                            string location = voiceCommand.SpeechRecognitionResult.SemanticInterpretation.Properties["location"].FirstOrDefault();
                            await SendCompletionMessageForBookToCustomLocation(location);
                        }
                        catch (Exception e)
                        {
                            userMessage1 = new VoiceCommandUserMessage();
                            book         = "Please give proper Destination";
                            userMessage1.DisplayMessage = userMessage1.SpokenMessage = book;
                            var response = VoiceCommandResponse.CreateResponse(userMessage1);
                            await voiceServiceConnection.ReportSuccessAsync(response);
                        }
                        break;

                    case "bookcheapest":
                        string mSource;
                        IReadOnlyList <string> voicecommandphrase;
                        if (voiceCommand.SpeechRecognitionResult.SemanticInterpretation.Properties.TryGetValue("source", out voicecommandphrase))
                        {
                            mSource = voicecommandphrase.First();
                        }
                        else
                        {
                            mSource = "";
                        }
                        string mDest = voiceCommand.SpeechRecognitionResult.SemanticInterpretation.Properties["destination"].FirstOrDefault();
                        await SendCompletionMessageForBookCheapestFromXtoY(mSource, mDest);

                        break;

                    default:
                        LaunchAppInForeground();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Handling Voice Command failed " + ex.ToString());
                }
            }
        }