Beispiel #1
0
        /// <inheritdoc />
        /// <summary>
        /// The entry point of a background task.
        /// </summary>
        /// <param name="taskInstance">The current background task instance.</param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // Get the deferral to prevent the task from closing prematurely
            _deferral = taskInstance.GetDeferral();

            // Setup our onCanceled callback and progress
            _taskInstance           = taskInstance;
            _taskInstance.Canceled += OnCanceled;
            _taskInstance.Progress  = 0;

            // Store a setting so that the app knows that the task is running.
            LocalSettings.Values["IsBackgroundTaskActive"] = true;

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

            _songTitleTimer =
                ThreadPoolTimer.CreatePeriodicTimer(SongTitleTimerCallback, TimeSpan.FromMilliseconds(500));

            _timer = new Timer(TimerCallback, null, 500, 500);

            _listener = UserNotificationListener.Current;

            _notificationAppsFile = await _localFolder.GetFileAsync("notificationApps");

            await Logger.Logger.CreateLogFile();

            _oldData = await ReadNotificationApps();

            _id = 0;

            try
            {
                var details = (RfcommConnectionTriggerDetails)taskInstance.TriggerDetails;
                if (details != null)
                {
                    _socket       = details.Socket;
                    _remoteDevice = details.RemoteDevice;
                    LocalSettings.Values["RemoteDeviceName"] = _remoteDevice.Name;

                    _writer = new DataWriter(_socket.OutputStream);
                    _reader = new DataReader(_socket.InputStream);

                    Logger.Logger.Info("Connected to " + _remoteDevice.Name + "(" + _remoteDevice.BluetoothAddress + ")");

                    await UpdateNotifications();
                }
                else
                {
                    LocalSettings.Values["BackgroundTaskStatus"] = "Trigger details returned null";
                    _deferral.Complete();
                }

                Logger.Logger.Info("Rfcomm Server Task instance");

                await ReceiveDataAsync();
            }
            catch (Exception ex)
            {
                _reader = null;
                _writer = null;
                _socket = null;
                _deferral.Complete();

                Debug.WriteLine("Exception occurred while initializing the connection, hr = " + ex.HResult.ToString("X"));
            }
        }
Beispiel #2
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 #3
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();

            ArelAPI.Connector API = new ArelAPI.Connector();

            Boolean canUpdate = true;
            Boolean isOnline  = await API.IsOnlineAsync();

            if (!isOnline) //Si le token n'est plus valide, on le rafraîchit avec le refreshToken
            {
                bool isReLogged = await API.RenewAccessTokenAsync();

                if (!isReLogged) //Si on peut rafraîchir le jeton, on continue, sinon on notifie l'utilisateur qu'il doit ré-entrer ses logins
                {
                    Show(new ToastContent()
                    {
                        Scenario = ToastScenario.Default,

                        Visual = new ToastVisual()
                        {
                            TitleText = new ToastText()
                            {
                                Text = "AREL - Synchronisation Planning"
                            },
                            BodyTextLine1 = new ToastText()
                            {
                                Text = "Vos identifiants ont expirés."
                            },
                            BodyTextLine2 = new ToastText()
                            {
                                Text = "Reconnectez-vous pour maintenir la synchronisation."
                            }
                        },
                    });

                    canUpdate = false;
                }
            }

            //On appelle la fonction de màj du calendrier windows qui est dans Planning.xaml.cs
            if (canUpdate)
            {
                API.UpdateWindowsCalendar(DateTime.Now.ToString("yyyy-MM-dd"),
                                          DateTime.Now.AddDays(14).ToString("yyyy-MM-dd"),
                                          API.GetUserFullName(ArelAPI.DataStorage.getData("user"), "Mon Planning AREL"));
            }

            //On re-enregistre la tâche si le paramètre est présent
            if (bool.Parse(ArelAPI.DataStorage.getData("backgroundTask")))
            {
                var         builder       = new BackgroundTaskBuilder();
                TimeTrigger hourlyTrigger = new TimeTrigger(120, false); //On rafraîchit le planning toutes les 2 heures.

                builder.Name           = "ARELSyncPlanningTask";
                builder.TaskEntryPoint = "SyncTask.ARELPlanningBackgroundTask";
                builder.SetTrigger(hourlyTrigger);
                builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));

                builder.Register();
            }

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

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

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

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

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

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

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

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

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

                    voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                    VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

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

                        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)
        {
            // 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();
            taskInstance.Canceled += TaskInstance_Canceled;

            // this is one way to handle unobserved task exceptions but not the best
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            // configure logging first

            // init IoC
            // see: http://intellitect.com/net-core-dependency-injection/#ActivatorUtilities
            // and https://stackify.com/net-core-dependency-injection/
            // and http://derpturkey.com/vnext-dependency-injection-overview/
            var container = new ServiceCollection();

            // https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging?tabs=aspnetcore2x#tabpanel_J929VbWwYc_aspnetcore2x
            container.AddLogging(builder =>
            {
                builder.AddDebug();
                builder.AddRest();
                builder.SetMinimumLevel(LogLevel.Trace);
                //builder.AddFilter<DebugLoggerProvider>("Default", LogLevel.Trace);
                //builder.AddFilter("IoTHs.Plugin.AzureIoTHub", LogLevel.Debug);
            });

            container.AddSingleton <IPluginRegistry, PluginRegistry>();

            container.AddSingleton <IMessageQueue>(new MessageQueue());
            container.AddSingleton <ChannelValueCache>();
            container.AddSingleton <DeviceConfigurationProvider>();
            container.AddTransient <CoreApp>();
            container.AddSingleton <FunctionsEngine>();
            container.AddSingleton <IApiAuthenticationService, ApiAuthenticationService>();

            container.AddSingleton <IAzureIoTHubPlugin, AzureIoTHubPlugin>();
#if ABUS
            container.AddTransient <SecVestPlugin>();
#endif
            container.AddTransient <EtaTouchPlugin>();
#if TWILIO
            container.AddTransient <TwilioPlugin>();
#endif
            container.AddTransient <HomeMaticPlugin>();
#if MQTTBROKER
            container.AddTransient <MqttBrokerPlugin>();
#endif

            // container available globally
            var locator = container.BuildServiceProvider();
            ServiceLocator.SetLocatorProvider(() => locator);

            // init device registry and add devices
            _pluginRegistry = locator.GetService <IPluginRegistry>();
            _pluginRegistry.RegisterPluginType <IAzureIoTHubPlugin>();
#if ABUS
            _pluginRegistry.RegisterPluginType <SecVestPlugin>();
#endif
            _pluginRegistry.RegisterPluginType <EtaTouchPlugin>();
#if TWILIO
            _pluginRegistry.RegisterPluginType <TwilioPlugin>();
#endif
            _pluginRegistry.RegisterPluginType <HomeMaticPlugin>();
#if MQTTBROKER
            _pluginRegistry.RegisterPluginType <MqttBrokerPlugin>();
#endif

            _log = locator.GetService <ILoggerFactory>().CreateLogger <StartupTask>();
            _log.LogInformation("Starting");
            // send package version to iot hub for tracking device software version
            var package   = Windows.ApplicationModel.Package.Current;
            var packageId = package.Id;
            var version   = packageId.Version;
            _log.LogInformation("Package version: " + version.Major + "." + version.Minor + "." + version.Build);

            _log.LogTrace("Launching CoreApp");
            _log.LogTrace("Local data folder: " + Windows.Storage.ApplicationData.Current.LocalFolder.Path);

            try
            {
                _coreApp = locator.GetService <CoreApp>();
                await _coreApp.RunAsync();
            }
            catch (Exception ex)
            {
                _log.LogError(ex, "CoreApp Run crashed");
                throw;
            }

            // The message Loop Worker runs in the background and checks for specific messages
            // which tell the CoreApp to either reboot the device or exit the app, which should
            // restart of the app
            _log.LogTrace("Launching MessageLoopWorker");
            MessageLoopWorker();

            // Dont release deferral, otherwise app will stop
        }
Beispiel #6
0
 public Task RunAsync(IBackgroundTaskInstance taskInstance)
 {
     _deferral = taskInstance?.GetDeferral() ?? throw new ArgumentNullException(nameof(taskInstance));
     return(RunAsync());
 }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();


            // How to use the ADS1015 and MCP3002 ADC/Converters

            AdcProviderManager adcManager = new AdcProviderManager();

            adcManager.Providers.Add(new ADS1015(ADS1015.Gain.Volt33));                            // Load up ADS1015 4 Channel ADC Converter
            adcManager.Providers.Add(new MCP3002());                                               // Load up MCP3002 2 Channel ADC Converter

            IReadOnlyList <AdcController> adcControllers = await adcManager.GetControllersAsync(); // load ADCs


            //use the ADCs create above
            Ldr      light = new Ldr(adcControllers[0].OpenChannel(0));      // create new light sensor using the ADS1015 ADC provider
            MCP9700A temp  = new MCP9700A(adcControllers[1].OpenChannel(0)); // create temperature sensor using MCP3002 ADC Provider

            var lightLevel = light.ReadValue;                                // read light level from the first ADC ADS1015
            var lightRatio = light.ReadRatio;

            var celsius    = temp.Temperature.DegreesCelsius;    // read temp in celsius
            var fahrenheit = temp.Temperature.DegreesFahrenheit; // read temp in celsius


            BMP280 tempAndPressure = new BMP280();

            var degreesCelsius    = tempAndPressure.Temperature.DegreesCelsius; // read temp in celsius - plenty of other units
            var degreesFahrenheit = tempAndPressure.Temperature.DegreesFahrenheit;

            var bars         = tempAndPressure.Pressure.Bars;         // read air pressure in bars - plenty of other units
            var hectopascals = tempAndPressure.Pressure.Hectopascals; // read air pressure in Hectopascals
            var Atmospheres  = tempAndPressure.Pressure.Atmospheres;


            // LED demo

            Led led = new Led(4);   // open led on pin 4

            led.On();               // turn on
            await Task.Delay(1000); // wait for 1 second

            led.Off();              // turn off

            // relay Demo
            Relay relay = new Relay(6);

            relay.On();             // turn relay on
            await Task.Delay(1000); // wait for 1 second

            led.Off();              // turn relay off


            // motor demo
            Motor leftMotor  = new Motor(22, 24);
            Motor rightMotor = new Motor(12, 25);

            //now do a tight circle
            leftMotor.Forward();
            rightMotor.Backward();
            await Task.Delay(5000);  // wait for 5 second

            leftMotor.Stop();
            rightMotor.Stop();
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            DeviceRegistrationResult result;

            try
            {
                bme280Sensor = new BME280(0x76);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"BME280 Initialisation failed:{ex.Message}");

                return;
            }

            try
            {
                using (var security = new SecurityProviderTpmHsm(RegistrationId))
                    using (var transport = new ProvisioningTransportHandlerHttp())
                    {
                        string base64EK = Convert.ToBase64String(security.GetEndorsementKey());

                        ProvisioningDeviceClient provClient = ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, IdScope, security, transport);

                        result = provClient.RegisterAsync().ConfigureAwait(false).GetAwaiter().GetResult();

                        IAuthenticationMethod auth = new DeviceAuthenticationWithTpm(result.DeviceId, security);

                        azureIoTHubClient = DeviceClient.Create(result.AssignedHub, auth, TransportType.Mqtt);
                    }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"DeviceClient.Create with TPM info failed:{ex.Message}");
                return;
            }

            try
            {
                azureIoTHubClient.SetMethodHandlerAsync("Restart", RestartAsync, null);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device method handler configuration failed:{ex.Message}");
                return;
            }

            try
            {
                TwinCollection reportedProperties;
                reportedProperties = new TwinCollection();

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

                // This is from the application manifest
                Package        package   = Package.Current;
                PackageId      packageId = package.Id;
                PackageVersion version   = packageId.Version;
                reportedProperties["ApplicationDisplayName"] = package.DisplayName;
                reportedProperties["ApplicationName"]        = packageId.Name;
                reportedProperties["ApplicationVersion"]     = string.Format($"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}");

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

                azureIoTHubClient.UpdateReportedPropertiesAsync(reportedProperties).Wait();
            }
            catch (Exception ex)
            {
                Debug.Print($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                deviceTwin = azureIoTHubClient.GetTwinAsync().Result;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Azure IoT Hub device twin configuration retrieval failed:{ex.Message}");
                return;
            }

            try
            {
                if (deviceTwin.Properties.Desired.Contains("TimerDue"))
                {
                    timerDue = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerDue"].ToString());
                }

                if (deviceTwin.Properties.Desired.Contains("TimerPeriod"))
                {
                    timerPeriod = TimeSpan.Parse(deviceTwin.Properties.Desired["TimerPeriod"].ToString());
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Sensor due or period configuration retrieval failed using default:{ex.Message}");
                return;
            }

            bme280InputPollingTimer = new Timer(SensorUpdateTimerCallback, null, timerDue, timerPeriod);

            //enable task to continue running in background
            backgroundTaskDeferral = taskInstance.GetDeferral();
        }
Beispiel #9
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            this.deferral = taskInstance.GetDeferral();

            this.Initialize();
        }
Beispiel #10
0
 /// <summary>
 /// Запускает фоновую задачу.
 /// </summary>
 /// <param name="taskInstance">Экземпляр фоновой задачи.</param>
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     _deferral = taskInstance.GetDeferral();
     StartUpdate();
 }
    public async void Run(IBackgroundTaskInstance taskInstance)
    {
        var cancellationTokenSource = new System.Threading.CancellationTokenSource();

        taskInstance.Canceled += TaskInstance_Canceled;
        _defferal              = taskInstance.GetDeferral();
Beispiel #12
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     _deferral              = taskInstance.GetDeferral();
     taskInstance.Canceled += TaskInstance_Canceled;
 }
        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;
            }
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            try {
                BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
                Debug.WriteLine("[UnifiedUpdateTask] launched at " + DateTime.Now);
#if DEBUG
                var start = DateTime.Now;
#endif



                bool   goRemote = false;
                string key      = "last_successful_remote_task";
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    if (DataAccess.getLocalSettings()[key] == null)
                    {
                        goRemote = true;
                    }
                    else
                    {
                        var delta = DateTime.Now - DateTime.Parse(DataAccess.getLocalSettings()[key].ToString());
                        if (delta.TotalHours >= remoteIntervalHours())
                        {
                            goRemote = true;
                        }
                    }
                }

                if (goRemote)
                {
                    Debug.WriteLine("[UnifiedUpdateTask] remote");
                    try {
                        await DataAccess.getAllDeadlines(forceRemote : true); //hope this can finish in 30 seconds
                    } catch (Exception) { }
                }

                try{
                    await Notification.update();
                } catch (Exception) { }
                try {
                    await Appointment.updateDeadlines();
                } catch (Exception) { }
                try {
                    if (goRemote)
                    {
                        await Appointment.updateLectures();
                    }
                } catch (Exception) { }


                deferral.Complete();

                if (goRemote)
                {
                    DataAccess.setLocalSettings(key, DateTime.Now.ToString());
                }

                Debug.WriteLine("[UnifiedUpdateTask] finished at" + DateTime.Now);
#if DEBUG
                Debug.WriteLine("[UnifiedUpdateTask] seconds elapsed " + (DateTime.Now - start).TotalSeconds);
#endif
            } catch (Exception) { }
        }
Beispiel #15
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Deferral = taskInstance.GetDeferral();

            Controller.Start(5000, new Logger());
        }
Beispiel #16
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 == "SeleniumBotVoiceService")
            {
                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.
                    switch (voiceCommand.CommandName)
                    {
                    /*
                     * case "whenIsTripToDestination":
                     *      var destination = voiceCommand.Properties["destination"][0];
                     *      await SendCompletionMessageForDestination(destination);
                     *      break;
                     * case "cancelTripToDestination":
                     *      var cancelDestination = voiceCommand.Properties["destination"][0];
                     *      await SendCompletionMessageForCancellation(cancelDestination);
                     *      break;
                     */
                    case "openBrowser":
                    {
                        var message = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = "opened edge",

                            SpokenMessage = "opened edge"
                        };

                        await ShowProgressScreen("launching Edge");

                        await control.OpenBrowser();

                        var response = VoiceCommandResponse.CreateResponse(message);

                        await voiceServiceConnection.ReportSuccessAsync(response);
                    }

                    break;

                    case "closeBrowser":
                    {
                        var message2 = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = "closed edge",

                            SpokenMessage = "closed edge"
                        };

                        await ShowProgressScreen("closing edge");

                        await control.CloseBrowser();

                        var response2 = VoiceCommandResponse.CreateResponse(message2);

                        await voiceServiceConnection.ReportSuccessAsync(response2);
                    }

                    break;

                    case "navTo":
                    {
                        var arg = voiceCommand.Properties["wildcardArgs"][0];

                        if (arg == null)
                        {
                            await ShowProgressScreen($"arg can't be null");

                            break;
                        }

                        await ShowProgressScreen($"navigating to {arg}");

                        await control.Nav(new Lib.DTOs.Nav()
                            {
                                urlOrName = arg
                            });

                        var message2 = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = "navigated",

                            SpokenMessage = "navigated"
                        };

                        var response2 = VoiceCommandResponse.CreateResponse(message2);

                        await voiceServiceConnection.ReportSuccessAsync(response2);
                    }

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

                    await ShowProgressScreen("error, " + ex.Message);
                }
            }
        }
Beispiel #17
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();

            StringBuilder sbToastContent = new StringBuilder();

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

                var bCanContinue = false;

                switch (status)
                {
                case AppServiceConnectionStatus.Success:
                    // The new connection opened successfully
                    sbToastContent.AppendLine("Connection established.");
                    bCanContinue = true;
                    break;

                case AppServiceConnectionStatus.AppNotInstalled:
                    sbToastContent.AppendLine("The app AppServicesProvider is not installed. Deploy AppServicesProvider to this device and try again.");
                    break;

                case AppServiceConnectionStatus.AppUnavailable:
                    sbToastContent.AppendLine("The app AppServicesProvider is not available. This could be because it is currently being updated or was installed to a removable device that is no longer available.");
                    break;

                case AppServiceConnectionStatus.AppServiceUnavailable:
                    sbToastContent.AppendLine("The app AppServicesProvider is installed but it does not provide the app service");
                    break;

                default:
                case AppServiceConnectionStatus.Unknown:
                    sbToastContent.AppendLine("An unknown error occurred while we were trying to open an AppServiceConnection.");
                    break;
                }

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

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

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

                        case AppServiceResponseStatus.ResourceLimitsExceeded:
                            sbToastContent.AppendLine("The service exceeded the resources allocated to it and had to be terminated.");
                            break;

                        default:
                        case AppServiceResponseStatus.Unknown:
                            sbToastContent.AppendLine("An unknown error occurred while we were trying to send a message to the service.");
                            break;
                        }
                    }
                }
                else
                {
                    sbToastContent.AppendLine("App Service is unavailable");
                }
            }

            // Send local Toast notification

            PopToast(sbToastContent.ToString());

            _deferral.Complete();
        }
Beispiel #18
0
 private void AppServiceConnection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args)
 {
     _backgroundTaskDeferral?.Complete();
     _backgroundTaskDeferral = null;
     _appServiceConnection   = null;
 }
Beispiel #19
0
 private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
 {
     serviceDeferral?.Complete();
     serviceDeferral = null;
 }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();

            // helper to let Opc.Ua Utils find the localFolder in the environment
            StorageFolder localFolder = ApplicationData.Current.LocalFolder;

            Utils.DefaultLocalFolder = localFolder.Path;

            ApplicationInstance application = new ApplicationInstance();

            application.ApplicationName   = "Opc.Ua.Sample.BackgroundServer";
            application.ApplicationType   = ApplicationType.Server;
            application.ConfigSectionName = application.ApplicationName;

            string applicationConfigurationFile           = localFolder.Path + String.Format(@"\{0}.Config.xml", application.ApplicationName);
            bool   applicationConfigurationLoadedFromFile = false;

            try
            {
                await application.LoadApplicationConfiguration(applicationConfigurationFile, true);

                // check if the configuration is valid for a server application.
                await application.ApplicationConfiguration.Validate(ApplicationType.Server);

                applicationConfigurationLoadedFromFile = true;
            }
            catch (Exception ex)
            {
                Utils.Trace("Exception:" + ex.Message);
            }

            if (!applicationConfigurationLoadedFromFile)
            {
                // Set configuartion parameters
                application.ApplicationConfiguration = new ApplicationConfiguration();


                //  Enable tracing
                application.ApplicationConfiguration.TraceConfiguration = new TraceConfiguration();
                application.ApplicationConfiguration.TraceConfiguration.OutputFilePath = localFolder.Path + @"\logs\Opc.Ua.Sample.BackgroundServer.log.txt";
                application.ApplicationConfiguration.TraceConfiguration.DeleteOnLoad   = true;
                application.ApplicationConfiguration.TraceConfiguration.TraceMasks     = 523;
                application.ApplicationConfiguration.TraceConfiguration.ApplySettings();

                // application information.
                application.ApplicationConfiguration.ApplicationName = application.ApplicationName;
                application.ApplicationConfiguration.ApplicationUri  = String.Format("urn:{0}:OPCFoundation:Sample:BackgroundServer", System.Net.Dns.GetHostName());
                application.ApplicationConfiguration.ProductUri      = "http://opcfoundation.org/UA/Sample/BackgroundServer";
                application.ApplicationConfiguration.ApplicationType = ApplicationType.Server;

                application.ApplicationConfiguration.SecurityConfiguration = new SecurityConfiguration();
                application.ApplicationConfiguration.SecurityConfiguration.ApplicationCertificate              = new CertificateIdentifier();
                application.ApplicationConfiguration.SecurityConfiguration.ApplicationCertificate.StorePath    = localFolder.Path + @"\pki\own";
                application.ApplicationConfiguration.SecurityConfiguration.ApplicationCertificate.SubjectName  = application.ApplicationName;
                application.ApplicationConfiguration.SecurityConfiguration.TrustedPeerCertificates.StorePath   = localFolder.Path + @"\pki\trusted";
                application.ApplicationConfiguration.SecurityConfiguration.TrustedIssuerCertificates.StorePath = localFolder.Path + @"\pki\issuer";
                application.ApplicationConfiguration.SecurityConfiguration.RejectedCertificateStore            = new CertificateStoreIdentifier();
                application.ApplicationConfiguration.SecurityConfiguration.RejectedCertificateStore.StorePath  = localFolder.Path + @"\pki\rejected";
                application.ApplicationConfiguration.SecurityConfiguration.AutoAcceptUntrustedCertificates     = true;

                // server configuration data
                application.ApplicationConfiguration.ServerConfiguration = new ServerConfiguration();
                application.ApplicationConfiguration.ServerConfiguration.BaseAddresses.Add(String.Format("opc.tcp://{0}:51210/UA/Sample/BackgroundServer", System.Net.Dns.GetHostName()));
                application.ApplicationConfiguration.ServerConfiguration.BaseAddresses.Add(String.Format("https://{0}:51212/UA/Sample/BackgroundServer", System.Net.Dns.GetHostName()));

                System.Net.IPAddress[] addresses = await System.Net.Dns.GetHostAddressesAsync(System.Net.Dns.GetHostName());

                foreach (var address in addresses)
                {
                    if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        continue;
                    }
                    if (System.Net.IPAddress.IsLoopback(address))
                    {
                        continue;
                    }

                    application.ApplicationConfiguration.ServerConfiguration.AlternateBaseAddresses.Add(String.Format("opc.tcp://{0}:51210/UA/Sample/BackgroundServer", address.ToString()));
                    application.ApplicationConfiguration.ServerConfiguration.AlternateBaseAddresses.Add(String.Format("https://{0}:51212/UA/Sample/BackgroundServer", address.ToString()));
                }

                application.ApplicationConfiguration.ServerConfiguration.DiagnosticsEnabled = true;

                //  endpoint's security policies to expose
                application.ApplicationConfiguration.ServerConfiguration.SecurityPolicies = new ServerSecurityPolicyCollection();
                application.ApplicationConfiguration.ServerConfiguration.SecurityPolicies.Add(new ServerSecurityPolicy()
                {
                    SecurityLevel     = 1,
                    SecurityMode      = MessageSecurityMode.None,
                    SecurityPolicyUri = "http://opcfoundation.org/UA/SecurityPolicy#None"
                });
                application.ApplicationConfiguration.ServerConfiguration.SecurityPolicies.Add(new ServerSecurityPolicy()
                {
                    SecurityLevel     = 2,
                    SecurityMode      = MessageSecurityMode.Sign,
                    SecurityPolicyUri = "http://opcfoundation.org/UA/SecurityPolicy#Basic256"
                });
                application.ApplicationConfiguration.ServerConfiguration.SecurityPolicies.Add(new ServerSecurityPolicy()
                {
                    SecurityLevel     = 3,
                    SecurityMode      = MessageSecurityMode.SignAndEncrypt,
                    SecurityPolicyUri = "http://opcfoundation.org/UA/SecurityPolicy#Basic128Rsa15"
                });
                application.ApplicationConfiguration.ServerConfiguration.SecurityPolicies.Add(new ServerSecurityPolicy()
                {
                    SecurityLevel     = 3,
                    SecurityMode      = MessageSecurityMode.SignAndEncrypt,
                    SecurityPolicyUri = "http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256"
                });


                //  endpoint user token policies to expose
                application.ApplicationConfiguration.ServerConfiguration.UserTokenPolicies = new UserTokenPolicyCollection();
                application.ApplicationConfiguration.ServerConfiguration.UserTokenPolicies.Add(new UserTokenPolicy()
                {
                    TokenType = UserTokenType.Anonymous
                });
                application.ApplicationConfiguration.ServerConfiguration.UserTokenPolicies.Add(new UserTokenPolicy()
                {
                    TokenType = UserTokenType.UserName
                });

                application.ApplicationConfiguration.DisableHiResClock = true;
            }

            // Allow the current window to activate since the stack initialization below can take some time
            // and the app can be terminated by the runtime if this takes too long

            //  await Task.Delay(1);

            try
            {
                if (!applicationConfigurationLoadedFromFile)
                {
                    // check if the configuration is valid for a server application.
                    await application.ApplicationConfiguration.Validate(ApplicationType.Server);
                }

                // check the application certificate.
                await application.CheckApplicationInstanceCertificate(false, 0);

                if (!application.ApplicationConfiguration.SecurityConfiguration.AutoAcceptUntrustedCertificates)
                {
                    application.ApplicationConfiguration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation);
                }

                if (!applicationConfigurationLoadedFromFile)
                {
                    application.ApplicationConfiguration.SaveToFile(applicationConfigurationFile);
                }

                // start the server.
                await application.Start(new Opc.Ua.Sample.BackgroundServer.BackgroundServer());
            }
            catch (Exception ex)
            {
                Utils.Trace("Exception:" + ex.Message);
                deferral.Complete();
            }
        }
 //--------------------------------------------------------Constructor:----------------------------------------------------------------\\
 #region --Constructors--
 /// <summary>
 /// Basic Constructor
 /// </summary>
 /// <history>
 /// 20/09/2017 Created [Fabian Sauter]
 /// </history>
 public BackgroundSocketHandler()
 {
     count    = 0;
     deferral = null;
 }
        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var requestDeferral = args.GetDeferral();

            try
            {
                Debug.WriteLine("A request received");
                if (args.Request.Message.ContainsKey("Receiver"))
                {
                    string receiver = args.Request.Message["Receiver"] as string;

                    Debug.WriteLine($"Receiver is {receiver}");

                    Dictionary <string, object> reqMessage = new Dictionary <string, object>();

                    foreach (var item in args.Request.Message)
                    {
                        reqMessage.Add(item.Key, item.Value);
                    }

                    if (receiver == "ServerIPFinder")
                    {
                        await FileTransfer.ServerIPFinder.ReceiveRequest(reqMessage);
                    }
                    else if (receiver == "FileReceiver")
                    {
                        await FileTransfer.FileReceiver.ReceiveRequest(reqMessage, DecideDownloadFolder);
                    }
                    else if (receiver == "TextReceiver")
                    {
                        await TextTransfer.TextReceiver.ReceiveRequest(reqMessage);
                    }
                    else if (receiver == "CloudClipboardHandler")
                    {
                        CloudClipboardHandler.ReceiveRequest(reqMessage);

                        _appServiceconnection.Dispose();
                        _deferral?.Complete();
                        _deferral = null;
                    }
                    else if (receiver == "System")
                    {
                        if (args.Request.Message.ContainsKey("FinishService"))
                        {
                            if (_deferral != null)
                            {
                                System.Diagnostics.Debug.WriteLine("Let's say goodbye");

                                while (waitingNumSemaphore > 0)
                                {
                                    await Task.Delay(100);
                                }

                                System.Diagnostics.Debug.WriteLine("Goodbye");
                                _appServiceconnection.Dispose();
                                _deferral?.Complete();
                                _deferral = null;
                            }
                        }
                    }
                }
            }
            finally
            {
                requestDeferral?.Complete();
            }
        }
        private async void MessageLoopWorker()
        {
            _log.LogTrace("MessageLoopWorker");
            IMessageQueue queue = null;

            do
            {
                if (ServiceLocator.Current != null)
                {
                    try
                    {
                        queue = ServiceLocator.Current.GetService <IMessageQueue>();
                    }
                    catch
                    {
                        /// ignore, might be too early
                    }
                }
            } while (queue == null);
            do
            {
                if (queue.TryDeque("management", out QueueMessage message))
                {
                    try
                    {
                        if (message.Key == "reboot")
                        {
                            _log.LogInformation("Rebooting");
                            await Task.Delay(5000);

                            ShutdownManager.BeginShutdown(ShutdownKind.Restart, TimeSpan.Zero);
                        }
                        else if (message.Key == "shutdown")
                        {
                            _log.LogInformation("Shutting down");
                            await Task.Delay(5000);

                            ShutdownManager.BeginShutdown(ShutdownKind.Shutdown, TimeSpan.Zero);
                        }
                        else if (message.Key == "exit")
                        {
                            _log.LogInformation("Exiting");
                            await Task.Delay(5000);

                            if (_deferral != null)
                            {
                                _deferral.Complete();
                                _deferral = null;
                                return;
                            }
                        }
                        if (message.Key == "restart")
                        {
                            _log.LogInformation("Restarting");
                            try
                            {
                                await _coreApp.ShutdownAsync();
                            }
                            catch (Exception ex)
                            {
                                _log.LogError(ex, "CoreApp Shutdown unsuccessful. Restarting...");
                                if (_deferral != null)
                                {
                                    _deferral.Complete();
                                    _deferral = null;
                                    return;
                                }
                                throw;
                            }
                            try
                            {
                                _coreApp = ServiceLocator.Current.GetService <CoreApp>();
                                await _coreApp.RunAsync();
                            }
                            catch (Exception ex)
                            {
                                _log.LogError(ex, "CoreApp Run crashed");
                                throw;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.LogError(ex, "MessageLoopWorker");
                    }
                }
                await Task.Delay(IoTHsConstants.MessageLoopDelay);
            } while (true);
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();

            var localSettingsValues = ApplicationData.Current.LocalSettings.Values;

            WinSecureStorageBase.StoragePassword = "******";

            //Octokit
            var client = new GitHubClient(new ProductHeaderValue("gitit"));

            if (CrossSecureStorage.Current.HasKey("OAuthToken"))
            {
                client.Credentials = new Credentials(CrossSecureStorage.Current.GetValue("OAuthToken"));
                var notificationRequest = new NotificationsRequest
                {
                    Since =
                        DateTimeOffset.Now.Subtract(new TimeSpan(0,
                                                                 int.Parse(localSettingsValues["BackgroundTaskTime"].ToString()), 0))
                };
                var notifications = await client.Activity.Notifications.GetAllForCurrent(notificationRequest);

                foreach (var notification in notifications)
                {
                    _toastTitle   = $"{notification.Subject.Title}";
                    _toastContent = $"in {notification.Repository.FullName} ({Convert.ToDateTime(notification.UpdatedAt).Humanize()})";

                    #region Toast-Notification Payload
                    //Reference: https://blogs.msdn.microsoft.com/tiles_and_toasts/2015/07/08/quickstart-sending-a-local-toast-notification-and-handling-activations-from-it-windows-10/

                    //Body of toast
                    var toastVisual = new ToastVisual()
                    {
                        BindingGeneric = new ToastBindingGeneric()
                        {
                            Children =
                            {
                                new AdaptiveText()
                                {
                                    Text = _toastTitle
                                },
                                new AdaptiveText()
                                {
                                    Text = _toastContent
                                },
                            }
                        }
                    };

                    //Interactive buttons to Toast
                    var toastActions = new ToastActionsCustom()
                    {
                        Buttons =
                        {
                            new ToastButton("Mark As Read", new QueryString()
                            {
                                { "action",                 "markAsRead"    },
                                { "notificationId",         notification.Id }
                            }.ToString())
                            {
                                ActivationType = ToastActivationType.Background
                            }
                        }
                    };

                    var toastContent = new ToastContent()
                    {
                        Visual  = toastVisual,
                        Actions = toastActions,

                        Launch = new QueryString()
                        {
                            { "notificationId", notification.Id }
                        }.ToString()
                    };

                    #endregion

                    #region Tile Payload

                    // https://blogs.msdn.microsoft.com/tiles_and_toasts/2015/06/30/adaptive-tile-templates-schema-and-documentation/

                    var tileContent = new TileContent()
                    {
                        Visual = new TileVisual()
                        {
                            Branding   = TileBranding.NameAndLogo,
                            TileMedium = new TileBinding()
                            {
                                Content = new TileBindingContentAdaptive()
                                {
                                    Children =
                                    {
                                        new AdaptiveGroup()
                                        {
                                            Children =
                                            {
                                                new AdaptiveSubgroup()
                                                {
                                                    Children =
                                                    {
                                                        new AdaptiveText()
                                                        {
                                                            Text      = _toastTitle,
                                                            HintWrap  = true,
                                                            HintStyle = AdaptiveTextStyle.Body
                                                        },
                                                        new AdaptiveText()
                                                        {
                                                            Text      = _toastContent,
                                                            HintWrap  = true,
                                                            HintStyle = AdaptiveTextStyle.CaptionSubtle
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            },
                            TileWide = new TileBinding()
                            {
                                Content = new TileBindingContentAdaptive()
                                {
                                    Children =
                                    {
                                        CreateGroup(_toastTitle, _toastContent)
                                    }
                                }
                            },
                            TileLarge = new TileBinding()
                            {
                                Content = new TileBindingContentAdaptive()
                                {
                                    Children =
                                    {
                                        CreateGroup(_toastTitle, _toastContent)
                                    }
                                }
                            }
                        }
                    };

                    #endregion

                    var toast = new ToastNotification(toastContent.GetXml())
                    {
                        Tag = "1"
                    };
                    ToastNotificationManager.CreateToastNotifier().Show(toast);

                    // Update tile
                    var tileNotification = new TileNotification(tileContent.GetXml());
                    TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
                }
            }
            _deferral.Complete();
        }
Beispiel #25
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral deferral = taskInstance.GetDeferral();

            try
            {
                Geolocator  geolocator = new Geolocator();
                Geoposition position   = await geolocator.GetGeopositionAsync();

                //////////////////////////////////////////////////////////////////////////
#if DEBUG
                XmlDocument toastXml          = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
                XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
                toastTextElements[0].AppendChild(toastXml.CreateTextNode(position.Coordinate.Point.Position.Latitude + "|" + position.Coordinate.Point.Position.Longitude));
                ToastNotification toastNotification = new ToastNotification(toastXml);
                ToastNotificationManager.CreateToastNotifier().Show(toastNotification);
#endif
                //////////////////////////////////////////////////////////////////////////

                ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
                LimitedQueue <GPSInfo>   queue;
                if (settings.Values.ContainsKey("Queue") == true)
                {
                    string queueString = (string)settings.Values["Queue"];
                    queue = SerializerUtility.Deserialize <LimitedQueue <GPSInfo> >(queueString);
                }
                else
                {
                    queue = new LimitedQueue <GPSInfo>(20);
                }

                queue.Push(new GPSInfo()
                {
                    Latitude = position.Coordinate.Point.Position.Latitude, Longitude = position.Coordinate.Point.Position.Longitude, PositionSource = position.Coordinate.PositionSource.ToString()
                });

                try
                {
                    string deviceUniqueId = UniqueIdUtility.GetUniqueId();

                    GPSInfo[] gpsInfoList     = queue.Retrive();
                    string    gpsInfoListJson = SerializerUtility.Serialize <GPSInfo[]>(gpsInfoList);

                    KeyValuePair <string, string>[] postData = new KeyValuePair <string, string> [2];
                    postData[0] = new KeyValuePair <string, string>("deviceUniqueId", deviceUniqueId);
                    postData[1] = new KeyValuePair <string, string>("gpsInfoList", gpsInfoListJson);

                    await HttpUtility.GetHttpResponse(ConfigUtility.GetValue("SendPositionAPI"), postData);

                    queue.Clear();
                }
                finally
                {
                    string queueString = SerializerUtility.Serialize <LimitedQueue <GPSInfo> >(queue);
                    settings.Values["Queue"] = queueString;
                }
            }
            catch (Exception ex)
            {
            }

            deferral.Complete();
        }
        //AuthenticationContext authContext = new AuthenticationContext(_authority, new FileCache());
        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 == "D365VoiceCommandService")
            {
                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();

                    string recordName, recordId, entityName, query;
                    Record changeRecord = new Record();

                    // Depending on the operation (defined in Dynamics365Commands.xml)
                    // perform the appropriate command.
                    switch (voiceCommand.CommandName)
                    {
                    case "createRecord":
                        ConnectToCRM();
                        entityName = voiceCommand.Properties["entityname"][0];
                        recordName = this.SemanticInterpretation("recordname", voiceCommand.SpeechRecognitionResult);
                        await CreateRecord(entityName, recordName);

                        break;

                    case "showAllUsers":
                        ConnectToCRM();
                        await GetFullNameSystemUsers();

                        break;

                    case "deleteRecord":
                        ConnectToCRM();
                        entityName = voiceCommand.Properties["entityname"][0];
                        changeRecord.recordName = this.SemanticInterpretation("recordname", voiceCommand.SpeechRecognitionResult);
                        query = GetQuery(entityName, changeRecord.recordName);
                        changeRecord.recordId = await RetrieveMultiple(query, entityName);
                        await Delete(entityName, changeRecord);

                        break;

                    case "updateRecord":
                        ConnectToCRM();
                        recordName = this.SemanticInterpretation("opportunityname", voiceCommand.SpeechRecognitionResult);
                        string fieldDisplayName = voiceCommand.Properties["fieldname"][0];
                        string fieldValue       = this.SemanticInterpretation("fieldvalue", voiceCommand.SpeechRecognitionResult);
                        query    = "opportunities?$select=name,opportunityid&$filter=name eq '" + recordName + "'";
                        recordId = await RetrieveMultiple(query, "Opportunity");

                        string schemaName = GetSchemaName(fieldDisplayName);
                        await Update(recordId, recordName, schemaName, fieldValue);

                        break;

                    case "showOpportunities":
                        var statusOpportunity = voiceCommand.Properties["status"][0];
                        ConnectToCRM();
                        await GetOpportunities(statusOpportunity);

                        break;

                    case "closeOpportunity":
                        var    status          = voiceCommand.Properties["status"][0];
                        string opportunityName = this.SemanticInterpretation("opportunityname", voiceCommand.SpeechRecognitionResult);
                        ConnectToCRM();
                        //recordId = await RetrieveMultiple(opportunityName);
                        //if (string.IsNullOrEmpty(recordId))
                        //    ShowException("No record found...");
                        //else
                        await CloseOpportunity(opportunityName, status);

                        break;

                    default:
                        break;
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Error Occurred: " + ex.ToString());
                }
            }
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            deferral = taskInstance.GetDeferral();

            _main.Initialise();
        }
        protected override async void OnRun(IBackgroundTaskInstance taskInstance)
        {
            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 "graphParams":
                    await ShowProgressScreen("Working on it...");

                    var    modelnumber = voiceCommand.Properties["modelnumber"][0];
                    double lambda      = 0;
                    double mu          = 0;
                    int    model       = Models.Point.GetNumberByModel(Models.Point.GetModelByNumber(modelnumber));

                    if (GetAllParameters(model, voiceCommand, ref lambda, ref mu))
                    {
                        bool allowed     = false;
                        bool unsupported = false;
                        if (model.Equals(1) || model.Equals(2))
                        {
                            var responseMessage = new VoiceCommandUserMessage()
                            {
                                DisplayMessage = String.Format("Get likelihood results for the model {0} with λ={1} and μ={2}?", modelnumber, lambda, mu),
                                SpokenMessage  = String.Format("Do you want me to get likelihood results for the model {0} with these input data?", modelnumber)
                            };
                            var repeatMessage = new VoiceCommandUserMessage()
                            {
                                DisplayMessage = String.Format("Do you still want me to get likelihood results for the model {0} with λ={1} and μ={2}?", modelnumber, lambda, mu),
                                SpokenMessage  = String.Format("Do you still want me to get likelihood results for the model {0} with these input data?", modelnumber)
                            };

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

                                allowed = confirmation.Confirmed;
                            }
                            catch
                            { }
                        }
                        else
                        {
                            unsupported = true;
                        }

                        if (allowed)
                        {
                            await ShowProgressScreen("Calculating...");

                            List <VoiceCommandContentTile> resultContentTiles = GetLikelihoodForSelectedModel(lambda, mu, model);
                            userMessage = new VoiceCommandUserMessage()
                            {
                                DisplayMessage = String.Format("Here is your likelihood results for the model {0}", modelnumber),
                                SpokenMessage  = "Done and Done! Here is your results"
                            };
                            response = VoiceCommandResponse.CreateResponse(userMessage, resultContentTiles);
                            response.AppLaunchArgument = modelnumber;
                            await voiceServiceConnection.ReportSuccessAsync(response);
                        }
                        else if (unsupported)
                        {
                            userMessage = new VoiceCommandUserMessage()
                            {
                                DisplayMessage = String.Format("Model {0} is not supported now", modelnumber),
                                SpokenMessage  = "Sorry, this model is not supported now"
                            };
                            response = VoiceCommandResponse.CreateResponse(userMessage);
                            response.AppLaunchArgument = modelnumber;
                            await voiceServiceConnection.ReportFailureAsync(response);
                        }
                        else
                        {
                            userMessage = new VoiceCommandUserMessage()
                            {
                                DisplayMessage = "Okay then",
                                SpokenMessage  = "Okay, then"
                            };
                            response = VoiceCommandResponse.CreateResponse(userMessage);
                            await voiceServiceConnection.ReportSuccessAsync(response);
                        }
                    }
                    else
                    {
                        userMessage = new VoiceCommandUserMessage()
                        {
                            DisplayMessage = "The arguments is incorrect",
                            SpokenMessage  = "Sorry, it seems the arguments is incorrect"
                        };
                        response = VoiceCommandResponse.CreateResponse(userMessage);
                        response.AppLaunchArgument = "";
                        await voiceServiceConnection.ReportFailureAsync(response);
                    }
                    break;

                default:
                    LaunchAppInForeground();
                    break;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                if (serviceDeferral != null)
                {
                    //Complete the service deferral
                    serviceDeferral.Complete();
                }
            }
        }
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     _deferral   = taskInstance.GetDeferral();
     _httpClient = new HttpClient();
     _timer      = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(Timer_Tick), TimeSpan.FromMilliseconds(500));
 }
Beispiel #30
0
 public void Run(IBackgroundTaskInstance taskInstance)
 {
     deferral = taskInstance.GetDeferral();
     timer    = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(1 * 1000));
 }