Complete() 공개 메소드

public Complete ( ) : void
리턴 void
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            serviceDeferral = taskInstance.GetDeferral();
            taskInstance.Canceled += OnTaskCanceled;

            var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            if (triggerDetails == null)
            {
                serviceDeferral.Complete();
                return;
            }

            try
            {
                voiceServiceConnection = VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
                voiceServiceConnection.VoiceCommandCompleted += OnVoiceCommandCompleted;

                var voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

                //Find the command name witch should match the VCD
                if (voiceCommand.CommandName == "buildit_help")
                {
                    var props = voiceCommand.Properties;
                    await CortanaHelpList();
                }
                await Task.Delay(1000);
                await ShowProgressScreen();
            }
            catch
            {
                Debug.WriteLine("Unable to process voice command");
            }
            serviceDeferral.Complete();
        }
예제 #2
0
        public async void Run( IBackgroundTaskInstance taskInstance )
        {
            Deferral = taskInstance.GetDeferral();

            XParameter[] Params = SavedChannels.Parameters( "channel" );

            if ( Params.Length == 0 )
            {
                Deferral.Complete();
                return;
            }

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

            foreach ( XParameter Param in Params )
            {
                CurrentTask = new XParameter( DateTime.Now.ToFileTime() + "" );
                CurrentTask.SetValue( new XKey[] {
                    new XKey( "name", taskInstance.Task.Name )
                    , new XKey( "start", true )
                    , new XKey( "end", false )
                } );

                PushNotificationChannel channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();

                if ( channel.Uri != Param.GetValue( "uri" ) )
                {
                    await RenewChannel( Param.GetValue( "provider" ), Param.Id, Uri.EscapeDataString( channel.Uri ) );
                }

            }

            Deferral.Complete();
        }
 /// <summary>
 /// Entry point for the background task.
 /// </summary>
 public async void Run(IBackgroundTaskInstance taskInstance)
 {
     var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
     if (null != triggerDetails && triggerDetails.Name == "LightControllerVoiceCommandService")
     {
         _deferral = taskInstance.GetDeferral();
         taskInstance.Canceled += (s, e) => _deferral.Complete();
         if (true != await InitializeAsync(triggerDetails))
         {
             return;
         }
         // These command phrases are coded in the VoiceCommands.xml file.
         switch (_voiceCommand.CommandName)
         {
             case "changeLightsState": await ChangeLightStateAsync(); break;
             case "changeLightsColor": await SelectColorAsync(); break;
             case "changeLightStateByName": await ChangeSpecificLightStateAsync(); break;
             default: await _voiceServiceConnection.RequestAppLaunchAsync(
                 CreateCortanaResponse("Launching HueLightController")); break;
         }
         // keep alive for 1 second to ensure all HTTP requests sent.
         await Task.Delay(1000);
         _deferral.Complete();
     }
 }
        /// <summary>
        /// The entry point of a background task.
        /// </summary>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            backgroundTaskInstance = taskInstance;
            var details = taskInstance.TriggerDetails as BluetoothLEAdvertisementWatcherTriggerDetails;
            if (details != null)
            {
                _deferral = backgroundTaskInstance.GetDeferral();
                taskInstance.Canceled += (s, e) => _deferral.Complete();

                var localStorage = ApplicationData.Current.LocalSettings.Values;
                _bridge = new Bridge(localStorage["bridgeIp"].ToString(), localStorage["userId"].ToString()); 
                try
                {
                    _lights = await _bridge.GetLightsAsync();
                }
                catch (Exception)
                {
                    _deferral.Complete();
                    return; 
                }
                foreach(var item in details.Advertisements)
                {
                    Debug.WriteLine(item.RawSignalStrengthInDBm);
                }

                // -127 is a BTLE magic number that indicates out of range. If we hit this, 
                // turn off the lights. Send the command regardless if they are on/off
                // just to be safe, since it will only be sent once.
                if (details.Advertisements.Any(x => x.RawSignalStrengthInDBm == -127))
                {
                    foreach (Light light in _lights)
                    {
                        light.State.On = false;
                        await Task.Delay(250);
                    }
                }
                // If there is no magic number, we are in range. Toggle any lights reporting
                // as off to on. Do not spam the command to lights arleady on. 
                else
                {
                    foreach (Light light in _lights.Where(x => !x.State.On))
                    {
                        light.State.On = true;
                        await Task.Delay(250);
                    }
                }
                // Wait 1 second before exiting to ensure all HTTP requests have sent.
                await Task.Delay(1000);
                _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)
        {
            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;
            }
        }
예제 #7
0
        //
        // The Run method is the entry point of a background task.
        //
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var details = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;
            if (details != null)
            {
                string arguments = details.Argument;
                var userInput = details.UserInput;
            }
            Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");
            //
            // 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;
            _deferral.Complete();

            // _periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromSeconds(1));
        }
예제 #8
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)
        {
            deferral = taskInstance.GetDeferral();
            Services.IoC.Register();
            var container = Container.Instance;
            logger = container.Resolve<ILogger>();

            taskInstance.Task.Completed += onTaskCompleted;
            taskInstance.Canceled += onTaskCanceled;
            logger.LogMessage("BackgroundUpdater: Task initialized.", LoggingLevel.Information);

            var episodeListManager = container.Resolve<IEpisodeListManager>();
            await episodeListManager.Initialization;
            var oldEpisodeList = EpisodeList.Instance.ToList();
            await episodeListManager.LoadEpisodeListFromServerAsync();
            var diff = EpisodeList.Instance.Except(oldEpisodeList).ToList();
            if (diff.Any())
            {
                var downloadManager = container.Resolve<IDownloadManager>();
                await downloadManager.Initialization;
                foreach (var episode in diff)
                {
                    await downloadManager.DownloadEpisode(episode);
                }
            }

            deferral.Complete();
        }
예제 #10
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            // Create the deferral by requesting it from the task instance
            serviceDeferral = taskInstance.GetDeferral();

            AppServiceTriggerDetails triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;

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

                VoiceCommand voiceCommand = await voiceServiceConnection.GetVoiceCommandAsync();

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

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

                    default:
                        break;
                }
            }

            // Once the asynchronous method(s) are done, close the deferral
            serviceDeferral.Complete();
        }
예제 #11
0
    public void Run(IBackgroundTaskInstance taskInstance)
    {
      Debug.WriteLine("Background " + taskInstance.Task.Name + " Starting...");

      taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);

      _deferral = taskInstance.GetDeferral();

      ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

      var settings = Windows.Storage.ApplicationData.Current.LocalSettings;
      var status = "";
      switch (InternetConnectionProfile.GetNetworkConnectivityLevel())
      {
        case NetworkConnectivityLevel.None:
          status = "無連線";
          break;
        case NetworkConnectivityLevel.LocalAccess:
          status = "本地連線";
          break;
        case NetworkConnectivityLevel.ConstrainedInternetAccess:
          status = "受限的連線";
          break;
        case NetworkConnectivityLevel.InternetAccess:
          status = "網際網路連線";
          break;
      }
      settings.Values["NetworkStatus"] = status;

      _deferral.Complete();
    }
예제 #12
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();

            await WhirlMonData.WhirlPoolAPIClient.GetDataAsync();

            _deferral.Complete();
        }
        /// <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
            this.taskInstance = taskInstance;
            this.taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
            this.taskInstance.Progress = 0;

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

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

            try
            {
                RfcommConnectionTriggerDetails details = (RfcommConnectionTriggerDetails)taskInstance.TriggerDetails;
                if (details != null)
                {
                    socket = details.Socket;
                    remoteDevice = details.RemoteDevice;
                    ApplicationData.Current.LocalSettings.Values["RemoteDeviceName"] = remoteDevice.Name;

                    writer = new DataWriter(socket.OutputStream);
                    reader = new DataReader(socket.InputStream);
                }
                else
                {
                    ApplicationData.Current.LocalSettings.Values["BackgroundTaskStatus"] = "Trigger details returned null";
                    deferral.Complete();
                }

                var result = 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"));
            }
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();

            RunBot().Wait();

            _deferral.Complete();

        }
예제 #15
0
        /// <summary>
        /// ライブタイル更新起動
        /// </summary>
        /// <param name="taskInstance"></param>
        protected async override void OnRun(IBackgroundTaskInstance taskInstance)
        {
            m_deferral = taskInstance.GetDeferral();

            //更新処理開始
            await updateTile();

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

            //1. envoyer requête HTTP au back-end pour vérifier si des mises à jour importantes sont disponibles. Pas illustré ici.
            //2. si c'est le cas, afficher une notification 
            ShowNotification();

            _deferral.Complete();
        }
예제 #17
0
파일: Tasks.cs 프로젝트: peterluo0822/Chat
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // Get defferal
            defferal = taskInstance.GetDeferral();

            try
            {
                var backend = Runtime.Instance;
                if (backend != null)
                    backend.OnBackgroundTaskRunning(taskInstance);
            }
            catch
            {
                if (defferal != null)
                    defferal.Complete();
            }

            if (defferal != null)
                defferal.Complete(); 
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Bluetooth BG running now !!");

            // Get the deferral to prevent the task from closing prematurely
            deferral = taskInstance.GetDeferral();

            // Setup our onCanceled callback and progress
            this.taskInstance = taskInstance;
            this.taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
            this.taskInstance.Progress = 0;

            try
            {
                RfcommConnectionTriggerDetails details = (RfcommConnectionTriggerDetails)taskInstance.TriggerDetails;
                if (details != null)
                {
                    socket = details.Socket;
                    writer = new DataWriter(socket.OutputStream);
                    reader = new DataReader(socket.InputStream);
                }
                else
                {
                    CommonData.TaskExitReason = "Trigger details returned null";
                    deferral.Complete();
                }

                var result = await ReceiveDataAsync();
            }
            catch (Exception ex)
            {
                reader = null;
                writer = null;
                socket = null;

                CommonData.TaskExitReason = "Exception occurred while initializing the connection, hr = " + ex.HResult.ToString("X");
                deferral.Complete();

                Debug.WriteLine("Exception occurred while initializing the connection, hr = " + ex.HResult.ToString("X"));
            }
        }
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();

            var settings = new Settings();

            if (settings.NotificationsEnabled)
                await SendNotificationAsync();

            if (settings.UpdatingLiveTileEnabled)
                await UpdateTileAsync();

            _deferral.Complete();
        }
예제 #20
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            // 
            _deferral = taskInstance.GetDeferral();

            taskInstance.Canceled += TaskInstance_Canceled;

            if (InitGPIO())
            {
                timer = ThreadPoolTimer.CreatePeriodicTimer(Timer_Tick, TimeSpan.FromMilliseconds(500));
            }
            else
            {
                _deferral.Complete();
            }
        }
예제 #21
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                deferral = taskInstance.GetDeferral();

                taskIdString = taskInstance.Task.TaskId.ToString();
                instanceIdString = taskInstance.InstanceId.ToString();

                await RunCoreAsync(taskInstance);
            }
            finally
            {
                deferral.Complete();
            }
        }
        private async void UpdateLiveTile(BackgroundTaskDeferral taskDeferral)
        {
            var someonePresent = await API.GetAsync<SomeonePresent>(API.Actions.CheckIfSomeoneIsPresent);
            var updater = TileUpdateManager.CreateTileUpdaterForApplication();
            updater.EnableNotificationQueue(true);
            updater.Clear();

            XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Text03);

            string titleText = "NuIEEE Room:\n" + (someonePresent.Result.Value ? "Has people working" : "Is empty");
            tileXml.GetElementsByTagName("text")[0].InnerText = titleText;

            updater.Update(new TileNotification(tileXml));

            taskDeferral.Complete();
        }
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            //ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
            // string taskName = taskInstance.Task.Name;

            // Debug.WriteLine("Background " + taskName + " starting...");

            // // Store the content received from the notification so it can be retrieved from the UI.
            //// RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
            //settings.Values["Task"] = "TEST";

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









            var xDoc = new XDocument(
            new XElement("toast",
                new XElement("visual",
                    new XElement("binding", new XAttribute("template", "ToastGeneric"),
                        new XElement("text", "SpartaHack 2016"),
                        new XElement("text", "test")
                        )
                    ),// actions 
                new XElement("actions",
                    new XElement("action", new XAttribute("activationType", "background"),
                        new XAttribute("content", "Yes"), new XAttribute("arguments", "yes")),
                    new XElement("action", new XAttribute("activationType", "background"),
                        new XAttribute("content", "No"), new XAttribute("arguments", "no"))
                    )
                )
            );

            var xmlDoc = new Windows.Data.Xml.Dom.XmlDocument();
            xmlDoc.LoadXml(xDoc.ToString());
            var notifi = ToastNotificationManager.CreateToastNotifier();
            notifi.Show(new ToastNotification(xmlDoc));
            _deferral.Complete();
        }
예제 #24
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            //
            // Associate a cancellation handler with the background task.
            //
            Debug.WriteLine(DateTime.Now.ToString("hh:MM:dd") + "_任务开始...");
            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;

            ShowToast();
            Debug.WriteLine(DateTime.Now.ToString("hh:MM:dd") + "_任务结束...");
            _deferral.Complete();
        }
예제 #25
0
        private BackgroundTaskDeferral deferral; // Used to keep task alive

        #endregion Fields

        #region Methods

        /// <summary>
        /// The Run method is the entry point of a background task. 
        /// </summary>
        /// <param name="taskInstance"></param>
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            Debug.WriteLine("Background Timer Task " + taskInstance.Task.Name + " starting...");

            deferral = taskInstance.GetDeferral(); // This must be retrieved prior to subscribing to events below which use it

            if (BackgroundMediaPlayer.Current.CurrentState == MediaPlayerState.Playing)
            {
                BackgroundMediaPlayer.Current.Pause();

                ApplicationSettingsHelper.SaveSettingsValue(
                    ApplicationSettingsConstants.Position,
                    BackgroundMediaPlayer.Current.Position.ToString()
                );
            }

            deferral.Complete();
        }
        //
        // The Run method is the entry point of a background task.
        //
        public async void Run(IBackgroundTaskInstance taskInstance)
        {

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

            TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true);
            // delete all previous notifications
            var notifier = Windows.UI.Notifications.TileUpdateManager.CreateTileUpdaterForApplication();
            var scheduled = notifier.GetScheduledTileNotifications();

            for (int i = 0, len = scheduled.Count; i < len; i++) 
            {
                    notifier.RemoveFromSchedule(scheduled[i]);
            }

            CalendarDataReader reader = new CalendarDataReader();
            String cityToken = Windows.Storage.ApplicationData.Current.LocalSettings.Values["CityName"] as String;
            DateTime today = DateTime.Today;
            await reader.ReadCalendarYearData(cityToken, today.Year);
            TileUpdateManager.CreateTileUpdaterForApplication().Clear();
            for (int i = 0; i < 31; i++)
            {
                if (i == 0)
                {
                    // to get an immediate update add a tile 3 minutes from now
                    UpdateTile(reader, DateTime.Now.AddMinutes(3));
                }
                else
                {
                    UpdateTile(reader, today.AddDays(i));
                }
            }
            _taskInstance = taskInstance;
            _deferral.Complete();
        }
 BackgroundTaskDeferral _deferral; // Note: defined at class scope so we can mark it complete inside the OnCancel() callback if we choose to support cancellation
 public async void Run(IBackgroundTaskInstance taskInstance)
 {
     _deferral = taskInstance.GetDeferral();
     //
     // TODO: Insert code to start one or more asynchronous methods using the
     //       await keyword, for example:
     //
     // await ExampleMethodAsync();
     //
     //获取第一条博客
     List<Blog> blog = await BlogService.GetSiteHomeArticlesAsync(1, 1);
     var lastBlog = blog.FirstOrDefault();
     if (lastBlog != null)
     {
         //更新磁铁
         TileHelper.UpdateBlogTile(lastBlog.Title, lastBlog.Summary);
     }
     //
     _deferral.Complete();
 }
예제 #28
0
 public async void Run(IBackgroundTaskInstance taskInstance)
 {
     string meAPI = (string)ApplicationData.Current.LocalSettings.Values["meAPI"];
     string access_token = (string)ApplicationData.Current.LocalSettings.Values["Tokens"];
     _deferral = taskInstance.GetDeferral();
     string meAPIResponse = null;
     _taskInstance = taskInstance;
     try
     {
         HttpClient httpClient = new HttpClient();
         httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", access_token);
         httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));
         var httpResponseMessage = await httpClient.GetAsync(new Uri(meAPI));
         // Debug.WriteLine("http response status code : " + httpResponseMessage.StatusCode.ToString());
         string apiResponse = await httpResponseMessage.Content.ReadAsStringAsync();
         meAPIResponse = apiResponse;
     }
     catch (Exception ex)
     {
         // API call failed.                
         meAPIResponse = "fail";
     }
     //string meAPIResponse = await clas.apiCall(access_token, meAPI);
     if (!String.Equals(meAPIResponse, "fail"))
     {
         var applicationData = Windows.Storage.ApplicationData.Current;
         var localFolder = applicationData.LocalFolder;
         //Debug.WriteLine("In writeFile : " + filename);
         try
         {
             //Debug.WriteLine("In try of write.");
             StorageFile sampleFile = await localFolder.CreateFileAsync("meAPIResponse", CreationCollisionOption.ReplaceExisting);
             await FileIO.WriteTextAsync(sampleFile, meAPIResponse);
         }
         catch (System.UnauthorizedAccessException e)
         {
         }               
     }
     _deferral.Complete();
 }
예제 #29
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            if(!Settings.GetTrackingEnabled())
            {
                return;
            }

            _deferral = taskInstance.GetDeferral();

            InitRaygun();
            try
            {
                await Sensor.DoStuff();
            }
            catch (Exception ex)
            {
                RaygunClient.Current.Send(ex);
                throw;
            }

            _deferral.Complete();
        }
예제 #30
0
파일: StartupTask.cs 프로젝트: BeRoces/iot
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            try {
                d = taskInstance.GetDeferral();

                var key = AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(rpiName, deviceKey);
                DeviceClient deviceClient = DeviceClient.Create(iotHubUri, key, TransportType.Http1); 

                Task ts = SendEvents(deviceClient);
                Task tr = ReceiveCommands(deviceClient);

                await Task.WhenAll(ts, tr);
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            finally
            {
                d.Complete();
            }
        }