示例#1
0
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            Loaded += (sender, args) =>
            {
                var periodic = new PeriodicTask("Temp");
                periodic.Description = "A";

                if (ScheduledActionService.Find("Temp") != null)
                {
                    ScheduledActionService.Remove("Temp");
                }
                ScheduledActionService.Add(periodic);

                ScheduledActionService.LaunchForTest("Temp", TimeSpan.FromSeconds(30));
            };
        }
示例#2
0
        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            string toastMessage = "Periodic task running.";

            ShellToast toast = new ShellToast();

            toast.Title   = "Background Agent Sample";
            toast.Content = toastMessage;
            toast.Show();

#if DEBUG_AGENT
            ScheduledActionService.LaunchForTest(
                task.Name, TimeSpan.FromSeconds(30));
#endif

            NotifyComplete();
        }
        private void StartPeriodicAgent()
        {
            PeriodicTask periodicTask = new PeriodicTask("ScheduledTaskAgent1");

            periodicTask.Description = "test";

            // If the agent is already registered with the system,
            if (ScheduledActionService.Find(periodicTask.Name) != null)
            {
                ScheduledActionService.Remove("ScheduledTaskAgent1");
            }

            //only can be called when application is running in foreground
            ScheduledActionService.Add(periodicTask);

            ScheduledActionService.LaunchForTest(periodicTask.Name, TimeSpan.FromSeconds(5.0f));
        }
        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            PeriodicTask cleanupTask;

            cleanupTask = ScheduledActionService.
                          Find("NotificationCleanupTask") as PeriodicTask;
            if (cleanupTask != null)
            {
                if (cleanupTask.LastExitReason != AgentExitReason.Completed &&
                    cleanupTask.LastExitReason != AgentExitReason.None)
                {
                    AgentStatus += string.Format("The background task failed to complete its last execution at {0:g} with an exit reason of {1}. ",
                                                 cleanupTask.LastScheduledTime, cleanupTask.LastExitReason);
                }

                if (!cleanupTask.IsEnabled)
                {
                    AgentStatus += "The background task was disabled by the user. ";
                }

                if (cleanupTask.ExpirationTime < DateTime.Now)
                {
                    AgentStatus = "The background task was expired. ";
                }

                ScheduledActionService.Remove(cleanupTask.Name);
            }

            try
            {
                cleanupTask             = new PeriodicTask("NotificationCleanupTask");
                cleanupTask.Description = "A background agent responsible for removing expired Windows Phone 7 in Action notifications";
                ScheduledActionService.Add(cleanupTask);
            }
            catch (InvalidOperationException)
            {
                AgentStatus += "Unable to create the background task.";
                cleanupTask  = null;
            }

            if (cleanupTask != null)
            {
                ScheduledActionService.LaunchForTest(cleanupTask.Name,
                                                     TimeSpan.FromSeconds(3));
            }
        }
        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            LiveTileHelper.UpdateLiveTile(false, incompleteItems);

            NotifyViaToast();

#if DEBUG_AGENT
            TodoItem[] allItems = DataProvider.RetrieveValue <TodoItem[]>().Concat(new [] { new TodoItem {
                                                                                                Text = "from test..."
                                                                                            } }).ToArray();
            bool successfullySaved = DataProvider.SaveValue <TodoItem[]>(allItems);

            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
#endif

            NotifyComplete();
        }
示例#6
0
        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override async void OnInvoke(ScheduledTask task)
        {
            if (task.Name.Equals(PERIODIC_TASKNAME, StringComparison.OrdinalIgnoreCase))
            {
                await UpdateCycleTile();
            }
            else
            {
                // If your application uses another ScheduledTask, handle it here
            }

#if DEBUG
            ScheduledActionService.LaunchForTest(PERIODIC_TASKNAME, TimeSpan.FromSeconds(60));
#endif

            NotifyComplete();
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //ScheduledAgent

            var oldTask = ScheduledActionService.Find("ScheduledAgent") as PeriodicTask;

            if (oldTask != null)
            {
                ScheduledActionService.Remove("ScheduledAgent");
            }

            Microsoft.Phone.Scheduler.PeriodicTask task = new Microsoft.Phone.Scheduler.PeriodicTask("ScheduledAgent");
            task.Description = "Updates theme live tiles";

            ScheduledActionService.Add(task);
            ScheduledActionService.LaunchForTest("ScheduledAgent", TimeSpan.FromMilliseconds(1200));
        }
示例#8
0
        //***********************************************************************************************************************

        //***********************************************************************************************************************
        /// <summary>
        /// Se produit quand l'application se ferme.
        /// </summary>
        /// <param name="Sender">Objet source de l'appel.</param>
        /// <param name="Args">
        /// <b>ClosingEventArgs</b> qui contient les données d'événement.
        /// </param>
        //-----------------------------------------------------------------------------------------------------------------------
        private void OnClosing(object Sender, ClosingEventArgs Args)
        {
            //-------------------------------------------------------------------------------------------------------------------
            #region             // DEBUG
            //-------------------------------------------------------------------------------------------------------------------
#if DEBUG
            //-------------------------------------------------------------------------------------------------------------------
            if (Instance.ScheduledAgentActive)
            {
                ScheduledActionService.LaunchForTest(AppInfos.SchedulerName, TimeSpan.FromSeconds(10));
            }
            //-------------------------------------------------------------------------------------------------------------------
#endif
            //-------------------------------------------------------------------------------------------------------------------
            #endregion
            //-------------------------------------------------------------------------------------------------------------------
        }
示例#9
0
        // 생성자
        public MainPage()
        {
            InitializeComponent();

            //업그레이드 관련 작업
            UpgradeVersion();

            DateTime LastRunForLivetile, LastRunForLockscreen;

            IsolatedStorageSettings.ApplicationSettings.TryGetValue <DateTime>(Constants.LAST_RUN_LIVETILE, out LastRunForLivetile);
            IsolatedStorageSettings.ApplicationSettings.TryGetValue <DateTime>(Constants.LAST_RUN_LOCKSCREEN, out LastRunForLockscreen);

            //스케줄러 복구 모드
            scheduleSettings = MutexedIsoStorageFile.Read <ScheduleSettings>("ScheduleSettings", Constants.MUTEX_DATA);
            if (DateTime.Now.Subtract(LastRunForLivetile).TotalMinutes > scheduleSettings.LivetileUpdateInterval + 60 && //원래 업데이트 시간보다 60분 초과
                DateTime.Now.Subtract(LastRunForLockscreen).TotalMinutes > scheduleSettings.LockscreenUpdateInterval + 60)
            {
                //스케줄러 초기화
                RemoveAgent(Constants.PERIODIC_TASK_NAME);
            }

            //위치 고정
            InitializeSystemTray();
            //보호색 설정
            InitializeProtectiveColor();

            //락스크린 초기화
            MainPageLockscreen();
            //라이브타일 초기화
            MainPageLivetile();
            //날씨 초기화
            MainPageWeather();
            //달력 초기화
            MainPageCalendar();

            //앱바 기본설정 설정
            BuildLocalizedApplicationBar();

#if (DEBUG_AGENT)
            RemoveAgent(Constants.PERIODIC_TASK_NAME);
            StartPeriodicAgent();
            ScheduledActionService.LaunchForTest(Constants.PERIODIC_TASK_NAME, TimeSpan.FromSeconds(30));
            //MessageBox.Show("스케줄러가 강제 시작됨");
#endif
        }
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            _periodicTask = ScheduledActionService.Find(_periodicTaskName) as PeriodicTask;

            if (_periodicTask != null)
            {
                ScheduledActionService.Remove(_periodicTaskName);
            }

            _periodicTask             = new PeriodicTask(_periodicTaskName);
            _periodicTask.Description = "testing";

            try
            {
                ScheduledActionService.Add(_periodicTask);

#if DEBUG_AGENT
                ScheduledActionService.LaunchForTest(_periodicTaskName, TimeSpan.FromSeconds(10));
#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                }

                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.
                }
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
            }

            // Set the data context of the listbox control to the sample data
            //DataContext = App.ViewModel;

            //RecentReleaseList.ItemsSource = new List<string>();
            //RecentReleaseList.ItemsSource = _recentReleaseVersionInfo;
        }
示例#11
0
        private void StartPeriodicAgent()
        {
            // Obtain a reference to the period task, if one exists
            mPeriodicTask = ScheduledActionService.Find(TILE_NAME) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update
            // the schedule
            if (mPeriodicTask != null)
            {
                RemoveAgent(TILE_NAME);
            }

            mPeriodicTask = new PeriodicTask(TILE_NAME);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            mPeriodicTask.Description = "將晴時多雲偶陣雨APP釘選到開始畫面後,會自動更新氣象資訊。";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(mPeriodicTask);
                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if (DEBUG_AGENT)
                ScheduledActionService.LaunchForTest(TILE_NAME, TimeSpan.FromSeconds(60));
#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    //MessageBox.Show("Background agents for this application have been disabled by the user.");
                }

                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.
                }
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
            }
        }
示例#12
0
        // Code, der beim Starten der Anwendung ausgeführt werden soll (z. B. über "Start")
        // Dieser Code wird beim Reaktivieren der Anwendung nicht ausgeführt
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            // Obtain a reference to the period task, if one exists
            var task = ScheduledActionService.Find("DataUpdate") as PeriodicTask;

            if (task != null)
            {
                ScheduledActionService.Remove("DataUpdate");
            }

            task = new PeriodicTask("DataUpdate")
            {
                Description = "Hier aktualisieren wir den Zähler auf der Kachel. Uuuunglaublich!"
            };

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(task);

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if DEBUG
                ScheduledActionService.LaunchForTest("DataUpdate", TimeSpan.FromSeconds(30));
#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MainPage.ShowBgDisabBox = true;
                }

                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.
                }
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
            }
        }
示例#13
0
        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            FSLog.Info();
            if (!SettingsManager.IsLocationUploadEnabled)
            {
                FSLog.Info("Locationing not enabled, aborting");
                Abort(); // Agent no longer active
                return;
            }

            LocationService.Instance.LocationChanged += LocationService_LocationChanged;
            LocationService.Instance.Start();

#if DEBUG_AGENT
            // If debugging is enabled, launch the agent again in one minute.
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));
#endif
        }
示例#14
0
        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            //TODO: Add code to perform your task in background
            string toastMessage = "Find and share your location";

            ShellToast toast = new ShellToast();

            toast.Title         = "Find Me";
            toast.Content       = toastMessage;
            toast.NavigationUri = new Uri("/MainPage.xaml", UriKind.Relative);
            toast.Show();

#if DEBUG_AGENT
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));
#endif

            NotifyComplete();
        }
示例#15
0
 public static void StartTask()
 {
     try
     {
         if (Database.Settings.NotificationState)
         {
             EndTask();
             var taskName     = "Mobisis Task";
             var periodicTask = new PeriodicTask(taskName)
             {
                 Description = "some desc"
             };
             ScheduledActionService.Add(periodicTask);
             ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(30));
         }
     }
     catch (Exception) { }
 }
示例#16
0
        private void StartScrobbler()
        {
            // Obtain a reference to the period task, if one exists
            oneScrobbler = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            if (oneScrobbler != null)
            {
                RemoveAgent(periodicTaskName);
            }

            oneScrobbler = new PeriodicTask(periodicTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            oneScrobbler.Description = "OneScrobble's scrobbling service.";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(oneScrobbler);

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
                #if (DEBUG_AGENT)
                ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(10));
                #endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                    agentsAreEnabled = false;
                }

                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.
                }
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
            }
        }
示例#17
0
        public static void Start()
        {
            Stop();
            try
            {
                var uahExchangeAgent = new PeriodicTask(Constants.TaskName)
                {
                    Description = Constants.TaskDescription
                };
                ScheduledActionService.Add(uahExchangeAgent);
#if DEBUG
                ScheduledActionService.LaunchForTest(Constants.TaskName, new TimeSpan(0, 0, 1));
#endif
            }
            catch (Exception ex)
            {
                Alert.Show("Background agent failed", ex.Message);
            }
        }
示例#18
0
        private void btnAddTile_Click(object sender, RoutedEventArgs e)
        {
            //add tile
            //start background agent
            PeriodicTask periodicTask = new PeriodicTask("PeriodicAgent");

            periodicTask.Description    = "Live Tile Update - TileProject";
            periodicTask.ExpirationTime = System.DateTime.Now.AddDays(1);

            // If the agent is already registered with the system,
            if (ScheduledActionService.Find(periodicTask.Name) != null)
            {
                ScheduledActionService.Remove("PeriodicAgent");
            }

            ScheduledActionService.Add(periodicTask);

            ScheduledActionService.LaunchForTest(periodicTask.Name, TimeSpan.FromSeconds(10));
        }
示例#19
0
        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            string key = "invokedTimes";

            System.Diagnostics.Debug.WriteLine("Scheduled task invoke.");

            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

            if (!settings.Contains(key))
            {
                settings.Add(key, 1);
                settings.Save();
            }
            else if ((int)settings[key] < 2)
            {
                settings[key] = 2;
                settings.Save();
                System.Diagnostics.Debug.WriteLine("half hour.");
            }
            else if ((int)settings[key] == 2)
            {
                //stop music
                ShellToast toast = new ShellToast();
                toast.Title   = "StopMusic";
                toast.Content = "StopMusic";
                toast.Show();
                System.Diagnostics.Debug.WriteLine("one hour.");
                BackgroundAudioPlayer.Instance.Stop();
                try
                {
                    ScheduledActionService.Remove("MusicTimer");
                }
                catch (Exception) { }
            }



            // If debugging is enabled, launch the agent again in one minute.
//#if DEBUG_AGENT
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(10));
//#endif
            NotifyComplete();
        }
示例#20
0
        private void RegisterBackgroundTask()
        {
            var taskName = "taskname";
            var oldTask  = ScheduledActionService.Find(taskName) as PeriodicTask;

            if (oldTask != null)
            {
                ScheduledActionService.Remove(taskName);
            }
            PeriodicTask task = new PeriodicTask(taskName);

            task.Description = "task description";

            //at this point there are no tasks in background tasks of phone settings
            ScheduledActionService.Add(task);
            #if (DEBUG_AGENT)
            ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(60));
            #endif
        }
        protected override void OnInvoke(ScheduledTask task)
        {
            int timeout = 0;

            System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.TryGetValue <int>("timespan", out timeout);

            DateTime lastrun;

            System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.TryGetValue <DateTime>("lastrun", out lastrun);

            if (DateTime.Now.Subtract(lastrun).TotalMinutes < timeout)
            {
                System.Diagnostics.Debug.WriteLine("Too soon, stopping.");
                NotifyComplete();
                return;
            }


            ScheduledActionService.LaunchForTest("task", TimeSpan.FromMinutes(timeout));

            System.Diagnostics.Debug.WriteLine("here we go...");

            try
            {
                background.render();
                try
                {
                    System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Remove("lastrun");
                }
                catch
                {
                }
                System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("lastrun", DateTime.Now);
                System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Save();
            }
            catch
            {
            }

            System.Threading.Thread.Sleep(9000);
            NotifyComplete();
        }
示例#22
0
        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected async override void OnInvoke(ScheduledTask task)
        {
            /*CacheContext cache = new CacheContext();
             * IUnitOfWork unitOfWork = new UnitOfWork(cache);
             * IBumbleApiService BumbleApi = new BumbleApiService(new Uri(DatabaseSetup.BumbleGatewayUrl, UriKind.Absolute), DatabaseSetup.AppKey, unitOfWork);
             * IEnumerable<TransportMode> modes = unitOfWork.TransportModeRepository.GetAll();
             * IEnumerable<OperatorSetting> operatorSettings = unitOfWork.OperatorSettingRepository.GetAll();
             *
             * try
             * {
             *  List<string> excludedModes = modes.Where(x => x.IsEnabled == false).Select(x => x.ApplicationTransportMode.ToString()).ToList();
             *  List<string> excludedOperators = operatorSettings.Where(x => x.IsEnabled == false).Select(x => x.OperatorName).ToList();
             *
             *  IEnumerable<Announcement> announcements = await BumbleApi.Announcements(CancellationToken.None, unitOfWork.UserRepository.GetUser(), excludedModes, excludedOperators, DateTime.UtcNow.AddHours(-1));
             *
             *  // get tile
             *  ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("/Views/Announcements.xaml"));
             *
             *  if (null != tile)
             *  {
             *      var data = new StandardTileData()
             *      {
             *          Title = "Announcements",
             *          BackgroundImage = new Uri("/Images/Tiles/TileAnnouncement7.png", UriKind.Relative),
             *          Count = announcements.Count()
             *      };
             *      // update tile
             *      tile.Update(data);
             *  }
             * }
             * catch (Exception)
             * {
             *
             * }*/

#if DEBUG
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
            System.Diagnostics.Debug.WriteLine("Periodic task started again: " + task.Name);
#endif

            NotifyComplete();
        }
示例#23
0
        private void UpdateLiveTileButton_Click(object sender, RoutedEventArgs e)
        {
            PeriodicTask tileUpdaterTask;
            string       taskName = "TileUpdateAgent";

            tileUpdaterTask = ScheduledActionService.Find(taskName) as PeriodicTask;

            if (tileUpdaterTask != null)
            {
                ScheduledActionService.Remove(taskName);
            }

            tileUpdaterTask             = new PeriodicTask(taskName);
            tileUpdaterTask.Description = "Omeddle Tile Updater";

            ScheduledActionService.Add(tileUpdaterTask);
            ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(10));

            UpdateLiveTileButton.IsEnabled = false;
        }
示例#24
0
        private void startResourceIntensiveAgent()
        {
            _periodicTask = ScheduledActionService.Find(_periodicTaskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update
            // the schedule.
            if (_periodicTask != null)
            {
                removeAgent(_periodicTaskName);
            }

            _periodicTask = new PeriodicTask(_periodicTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            _periodicTask.Description = "Updates Pocal LiveTile";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(_periodicTask);


                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if (DEBUG_AGENT)
                ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(10));
#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    //MessageBox.Show("Background agents for this application have been disabled by the user.");
                }
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
            }
        }
示例#25
0
        private void StartPeriodicAgent()
        {
            // Obtain a reference to the period task, if one exists
            ScheduledTask periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update
            // the schedule
            if (periodicTask != null)
            {
                try
                {
                    ScheduledActionService.Remove(periodicTaskName);
                }
                catch (Exception)
                {
                }
            }

            periodicTask = new PeriodicTask(periodicTaskName)
            {
                // The description is required for periodic agents. This is the string that the user
                // will see in the background services Settings page on the device.
                Description    = "Download cineworld data and refresh tiles",
                ExpirationTime = DateTime.Today.AddDays(14)
            };

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(periodicTask);
                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if (DEBUG)
                ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(60));
#endif
            }
            catch (Exception ex)
            {
                int i = 1;
            }
        }
示例#26
0
        public static bool ActivateAgent()
        {
            // Wenn der Task bereits hinzugefügt wurde. dann diesen stoppen
            PeriodicTask syncTask = ScheduledActionService.Find(AgentName) as PeriodicTask;

            if (syncTask != null)
            {
                StopAgent(AgentName);
            }

            // Task anlegen und Beschreibung für Einstellungs-UI setzen
            syncTask             = new PeriodicTask(AgentName);
            syncTask.Description = "Download der neusten Nachrichten von Spiegel Online";

            ResourceIntensiveTask intensiveTask = ScheduledActionService.Find(AgentIntensiveName) as ResourceIntensiveTask;

            if (intensiveTask != null)
            {
                StopAgent(AgentIntensiveName);
            }
            intensiveTask = new ResourceIntensiveTask(AgentIntensiveName);

            try
            {
                // Tasks im System registrieren für Ausführung
                ScheduledActionService.Add(syncTask);
                ScheduledActionService.Add(intensiveTask);

#if DEBUG
                // Für's Debuggen: Tasks in 30 bzw. 90sek ausführen
                ScheduledActionService.LaunchForTest(AgentName, TimeSpan.FromSeconds(30));
                ScheduledActionService.LaunchForTest(AgentIntensiveName, TimeSpan.FromSeconds(90));
#endif

                return(true);
            }
            catch (InvalidOperationException ex)
            {
                return(false);
            }
        }
示例#27
0
        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            //TODO: Add code to perform your task in background
            if (task.Name == "DatingDiaryTask")
            {
                if (task is PeriodicTask)
                {
                    // Execute periodic task actions here.
                    ShellTile TileToFind = ShellTile.ActiveTiles.First(); // OrDefault(x => x.NavigationUri.ToString().Contains("DefaultTitle=DatingApp"));

                    if (TileToFind != null)
                    {
                        string           ConnectionString = @"isostore:/DatingDiaryDB.sdf";
                        DatingAppContext ctx = new DatingAppContext(ConnectionString);

                        // get the number of dates there are today ...
                        int dateCount = ctx.Dates.Count(x => x.DateOfMeeting.Date == DateTime.Now.Date);

                        // get the next date
                        Date nextDate = ctx.Dates.FirstOrDefault(x => x.DateOfMeeting.Date == DateTime.Now.Date);

                        StandardTileData NewTileData = new StandardTileData
                        {
                            Title               = dateCount > 0 ? "Dating Diary" : string.Empty,
                            Count               = dateCount,
                            BackTitle           = nextDate.Person.FullName,
                            BackBackgroundImage = new Uri("BackBackground.png", UriKind.RelativeOrAbsolute),
                            BackContent         = string.Format("Today @ {0}", nextDate.DateOfMeeting.ToString(CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern, CultureInfo.CurrentCulture.DateTimeFormat))
                        };

                        TileToFind.Update(NewTileData);
                    }
                }
                else
                {
                    // Execute resource-intensive task actions here.
                }
            }
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(3));
            NotifyComplete();
        }
        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override async void OnInvoke(ScheduledTask task)
        {
            //TODO: Add code to perform your task in background

            //if (task is PeriodicTask)
            //{

            //}

            //ShellToast toast = new ShellToast();
            //toast.Title = "Background Agent Sample";
            //toast.Content = "testing";
            //toast.Show();

            int NewReleasesCount = (await _deviceIntegrator.GetUncheckedNewReleasesAsync()).Count();

            // debugging
            //
            //NewReleasesCount = (new Random()).Next(1, 10);

            IconicTileData TileUpdate = new IconicTileData();

            TileUpdate.Title = "SQL Versions";
            TileUpdate.Count = NewReleasesCount;
            //TileUpdate.WideContent1 = "wc1";
            //TileUpdate.WideContent2 = "wc2";
            //TileUpdate.WideContent3 = "wc3";

            ShellTile AppTile = ShellTile.ActiveTiles.First();

            if (AppTile != null)
            {
                AppTile.Update(TileUpdate);
            }

#if DEBUG_AGENT
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
#endif

            NotifyComplete();
        }
示例#29
0
        protected override void OnInvoke(ScheduledTask task)
        {
            Deployment.Current.Dispatcher.BeginInvoke(async delegate
            {
                try
                {
                    LiveTileManager.AppointmentsOnLiveTile = await LiveTileManager.GetNextAppointments();
                    LiveTileManager.UpdateTile();
                }
                catch
                {
                    // ignored
                }

#if DEBUG_AGENT
                ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));
#endif

                NotifyComplete();
            });
        }
示例#30
0
        public static void CheckBackgroundAgent()
        {
            PeriodicTask tileUpdaterPeriodicTask;

            tileUpdaterPeriodicTask = ScheduledActionService.Find(taskName) as PeriodicTask;

            if (tileUpdaterPeriodicTask == null)
            {
                tileUpdaterPeriodicTask             = new PeriodicTask(taskName);
                tileUpdaterPeriodicTask.Description = "Élőcsempék menetrend adatainak frissítését végzi az alkalmazás a háttérben.";

                try
                {
                    ScheduledActionService.Add(tileUpdaterPeriodicTask);
                }
                catch (InvalidOperationException exception)
                {
                    if (exception.Message.Contains("BNS Error: The action is disabled"))
                    {
                        MessageBox.Show("Background agents for this application have been disabled by the user.");
                    }
                    else
                    {
                        MessageBox.Show(exception.Message);
                    }
                }
                catch (Exception e) { }
            }

            if (Debugger.IsAttached)
            {
                try
                {
                    ScheduledActionService.LaunchForTest(
                        taskName,
                        TimeSpan.FromSeconds(10));
                }
                catch (Exception) { }
            }
        }