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

            if(task is PeriodicTask)
            {

                toastMessage = "Periodic task running.";

            }
            else
            {
                toastMessage = "Resource-intensive task running.";
            }

            var toast = new ShellToast {Title = "Background Agent Sample", Content = toastMessage};

            toast.Show();

#if DEBUG_AGENT

            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds((60)));

#endif

            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 void OnInvoke(ScheduledTask task)
        {
            //TODO: Add code to perform your task in background

            string toastMessage = "";

            // If your application uses both PeriodicTask and ResourceIntensiveTask
            // you can branch your application code here. Otherwise, you don't need to.
            if (task is PeriodicTask)
            {
                // Execute periodic task actions here.
                toastMessage = "Periodic task running.";
            }
            else
            {  
                // Execute resource-intensive task actions here.
                toastMessage = "Resource-intensive task running.";
            }

            // Launch a toast to show that the agent is running.
            // The toast will not be shown if the foreground application is running.
            ShellToast toast = new ShellToast();
            toast.Title = "Background Agent Sample";
            toast.Content = toastMessage;
            toast.Show();

            // If debugging is enabled, launch the agent again in one minute.
            #if DEBUG_AGENT
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));
            #endif

            // Call NotifyComplete to let the system know the agent is done working.
            NotifyComplete();
        }
        private void LoadUrl()
        {
            try
            {
                RestRequest request = new RestRequest(URL.BASE3 + "APIv2/charityorganization/charity_program.php", Method.POST);

                request.AddHeader("content-type", "multipart/form-data");
                request.AddParameter("id_donors", Navigation.navIdDonors);
                request.AddParameter("token", Navigation.token);
                request.AddParameter("id_program", Navigation.idProgram);

                //calling server with restClient
                RestClient restClient = new RestClient();
                restClient.ExecuteAsync(request, (response) =>
                {
                    ShellToast toast = new ShellToast();
                    toast.Title = "Status Upload";
                    JObject jRoot = JObject.Parse(response.Content);
                    String result = jRoot.SelectToken("result").ToString();
                    JArray JItem = JArray.Parse(jRoot.SelectToken("item").ToString());

                    foreach (JObject item in JItem)
                    {
                       
                        Id_program = item.SelectToken("id_program").ToString();
                        Program_name = item.SelectToken("program_name").ToString();
                        Description = item.SelectToken("description").ToString();
                    }
                });
            }
            catch { }
        }
 public static void ErrorToast(Exception exc)
 {
     ShellToast toast = new ShellToast();
     toast.Content = DateTime.Now.ToShortTimeString() + " " + exc.ToString();
     toast.Title = "Waze Task Error";
     toast.Show();
 }
Exemple #5
0
        private void DeleteThisSong(object sender, System.Windows.Input.GestureEventArgs e)
        {
            string           SongTitle = App.VirtualSongBook.MyOwnSongs[SelecSong].Title;
            MessageBoxResult WarnMeNow = MessageBox.Show("Are you sure you want to delete the song: \"" + SongTitle
                                                         + "\" from your own songs? This action is permanent and can not be reversed.",
                                                         "Just a minute...", MessageBoxButton.OKCancel);

            if (WarnMeNow == MessageBoxResult.OK)
            {
                OwnsongsDelete deleteOwn = new OwnsongsDelete();
                deleteOwn.DeleteOwnsong(CurrSong);

                ShellToast toast = new ShellToast();
                toast.Title   = "vSongBook";
                toast.Content = "You have deleted the song " + SongTitle;
                toast.Show();

                this.NavigationService.GoBack();
            }

            else if (WarnMeNow == MessageBoxResult.Cancel)
            {
                settings.Hint2Setting = false;
            }
        }
Exemple #6
0
        // Code to execute when the application is deactivated (sent to background)
        // This code will not execute when the application is closing
        private void Application_Deactivated(object sender, DeactivatedEventArgs e)
        {
            SaveApplicationState();

            // If the app is running lap timing in the background then notify the user that timing has stopped
            if (ViewModel.AppIsRunningInBackground && ViewModel.Timer != null && ViewModel.Timer.IsTiming)
            {
                var toastNotification = new ShellToast
                {
                    Title = AppResources.Text_Toast_Title
                };

                switch (e.Reason)
                {
                case DeactivationReason.PowerSavingModeOn:
                    toastNotification.Content = AppResources.Text_Toast_Content_TimingStoppedLowBattery;
                    break;

                case DeactivationReason.ResourcesUnavailable:
                    toastNotification.Content = AppResources.Text_Toast_Content_TimingStoppedLowResources;
                    break;

                case DeactivationReason.UserAction:
                case DeactivationReason.ApplicationAction:
                default:
                    toastNotification.Content = AppResources.Text_Toast_Content_TimingStopped;
                    break;
                }
                toastNotification.Show();
            }

            EndTimingAndReleaseResources();
        }
Exemple #7
0
        /// <summary>
        /// Function to handle the callback from cloudservice - hides progress bar, if its been a success,
        /// navigates to LoginView else output error to view (Or toast if its dormant)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void CloudService_RegisterCompleted(object sender, Domain.CloudService.RegisterCompletedEventArgs e)
        {
            //Hide progress bar
            Progress = Visibility.Collapsed;

            //If success, navigate to LoginView else output error to view
            if (e.Result.ToString() == "Success")
            {
                if (!App.RunningInBackground)
                {
                    (application.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/Views/LoginView.xaml", UriKind.Relative));
                }
            }
            else
            {
                Message = e.Result.ToString();
            }

            //If app is dormant write message to toast for user
            if (App.RunningInBackground)
            {
                ShellToast msg = new ShellToast();
                msg.Title   = "Register:";
                msg.Content = e.Result.ToString();
                msg.Show();
            }
        }
 public void ShowToastNotification(string title, string content)
 {
     ShellToast toast = new ShellToast();
     toast.Title = title;
     toast.Content = content;
     toast.Show();
 }
        private void webClient_DownloadCombinedTrainsCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                string json = e.Result;


                if (!string.IsNullOrEmpty(json))
                {
                    RouteInformation routeInformation = JsonConvert.DeserializeObject <RouteInformation>(json);
                    detailedStationList[tempIndex].fromDistance        = Math.Round(routeInformation.resourceSets[0].resources[0].travelDistance, 1);
                    detailedStationList[tempIndex].fromDistanceDisplay = getDistanceFromDisplay(detailedStationList[tempIndex].fromDistance);
                }
            }
            catch (Exception ex)
            {
                //Telerik.Windows.Controls.RadMessageBox.ShowAsync("AW SNAP :-(", Telerik.Windows.Controls.MessageBoxButtons.OK, "We are having trouble downloading data due to network connectivity or temporary server unavailability at the moment. Please make sure you are connected to internet and try again.");
                detailedStationList[tempIndex].fromDistance = 1000;
                ShellToast toast = new ShellToast();
                toast.Title   = "AW SNAP :(";
                toast.Content = "We could not retreive some routing infomation. But this won't affect to your routing options as offline maps features would still available";
                toast.Show();
            }
            tempIndex++;
            if (detailedStationList.Count == tempIndex)
            {
                this.busyIndicator.IsRunning = false;
                populateStations();
            }
        }
Exemple #10
0
        private static void ActiveToastNotifications()
        {
            if (StateUtility.IsRunningInBackground && IsRegisteredUser)
            {
                Debug.WriteLine(DateTime.Now.ToLongTimeString() + " - Executing Global Position Changed event in background");

                ShellToast toast = new ShellToast();

                var currentMinute = DateTime.Now.Minute;
                if (CurrentProfile.IsSOSOn && currentMinute % 10 == 0 && !_toastFlag)
                {
                    _toastFlag          = true;
                    toast.Title         = "Guardian SOS is active!";
                    toast.Content      += "If you are safe, please turn off";
                    toast.NavigationUri = new Uri("/Pages/SOS.xaml", UriKind.Relative);
                    toast.Show();
                }
                else if (CurrentProfile.IsTrackingOn && currentMinute % 15 == 0 && !_toastFlag)
                {
                    _toastFlag          = true;
                    toast.Title         = "Guardian Tracking is active!";
                    toast.Content       = "Turn off, when not needed";
                    toast.NavigationUri = new Uri("/Pages/TrackMe.xaml", UriKind.Relative);
                    toast.Show();
                }
                else if (currentMinute % 10 == 0 || currentMinute % 15 == 0)
                {
                    return;
                }
                else if (currentMinute % 10 != 0 || currentMinute % 15 != 0)
                {
                    _toastFlag = false;
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// Display the toast notification
        /// </summary>
        public override async Task CheckAndToastAsync()
        {
            // Resolve model
            IReadableLimitable <Conference> model;

            using (ILifetimeScope scope = ViewModelLocator.Container.BeginLifetimeScope())
                model = scope.Resolve <IReadableLimitable <Conference> >();

            // Get last conference Id from model
            int idLastConference = await model.GetLastInsertedId();

            IsolatedStorageSettings localSettings = IsolatedStorageSettings.ApplicationSettings;

            // Get last conference saved Id
            int idLastConferenceSaved = localSettings.Contains(LibResources.ConferenceStorageKey) ? (int)localSettings[LibResources.ConferenceStorageKey] : 0;

            // If Ids are differents, update the saved Id and show a toast notification
            if (idLastConference != idLastConferenceSaved)
            {
                Conference lastConference = await model.GetAsync(idLastConference);

                ShellToast toast = new ShellToast
                {
                    Title         = LibResources.NewConference,
                    Content       = lastConference.Name,
                    NavigationUri = new Uri(string.Format("/ConferencePage.xaml?Id={0}", lastConference.Id), UriKind.Relative)
                };

                toast.Show();

                localSettings[LibResources.ConferenceStorageKey] = idLastConference;
                localSettings.Save();
            }
        }
Exemple #12
0
        private void UpdateNotification(int articleCount, NewsItem article)
        {
            if (article.id != dataService.Settings.LastNotifiedArticleId)
            {
                dataService.Settings.LastNotifiedArticleId = article.id;
                dataService.Settings.LastNotificationTime  = DateTime.Now;
                dataService.SaveSettings();
                UpdateLiveTile(article);

                if (dataService.Settings.IsToastNotificationUsed)
                {
                    try
                    {
                        ShellToast shellToast = new ShellToast();
                        shellToast.Content       = article.news_title;
                        shellToast.Title         = "DD NEWS";
                        shellToast.NavigationUri = new Uri(string.Format("/Views/HomePage.xaml?Id={0}&Language={1}&Toast={2}", article.id, article.language, true), UriKind.Relative);
                        shellToast.Show();
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
Exemple #13
0
        public static void PostDownload(IList <Feed> downloadedFeeds)
        {
            if (downloadedFeeds != null && downloadedFeeds.Count > 0)
            {
                var dbContext          = new PersistentManager();
                var downloadedFileName = string.Format("{0}-{1}.dat", AppConfig.TEMP_DOWNLOAD_FILE_PATTERN, DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-tt"));

                if (dbContext.UpdateSerializedCopy(downloadedFeeds, downloadedFileName, false))
                {
                    if (AppConfig.ShowBackgroundUpdateResult)
                    {
                        ShellToast toast = new ShellToast();
                        toast.Title   = "duyệt báo";
                        toast.Content = string.Format("tải {0} tin từ {1} mục", downloadedFeeds.Sum(f => f.Items.Count).ToString(), downloadedFeeds.Count);
                        toast.Show();
                    }

                    FlipTileData flipTileData = new FlipTileData()
                    {
                        Count               = downloadedFeeds.Sum(f => f.Items.Count),
                        BackContent         = string.Format("tải {0} tin", downloadedFeeds.Sum(f => f.Items.Count)).ToString(),
                        BackTitle           = string.Format("cập nhật {0} mục", downloadedFeeds.Count),
                        BackBackgroundImage = new Uri("Resources/tile-med-back.png", UriKind.Relative)
                    };
                    ShellTile appTile = ShellTile.ActiveTiles.First();
                    if (appTile != null)
                    {
                        appTile.Update(flipTileData);
                    }
                }
            }
        }
        protected override void OnInvoke(ScheduledTask task)
        {
            string username;

            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

            if (settings.Contains("username"))
            {
                username = settings["username"].ToString();
            }
            else
            {
                ShellToast toast = new ShellToast();
                toast.Title         = "LatestChatty: ";
                toast.Content       = "Please login to receive reply notifications";
                toast.NavigationUri = new Uri("/", UriKind.Relative);
                toast.Show();
                NotifyComplete();
                return;
            }

            if (settings.Contains("lastReplySeen"))
            {
                _lastReplySeen = int.Parse(settings["lastReplySeen"].ToString());
            }

            string         uri     = "http://shackapi.stonedonkey.com/Search/?ParentAuthor=" + username;
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

            request.Method = "GET";
            request.Headers[HttpRequestHeader.CacheControl] = "no-cache";

            IAsyncResult token = request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
        }
        /// <summary>
        /// Display the toast notification
        /// </summary>
        public override async Task CheckAndToastAsync()
        {
            // Resolve model
            IReadableLimitable<Conference> model;

            using (ILifetimeScope scope = ViewModelLocator.Container.BeginLifetimeScope())
                model = scope.Resolve<IReadableLimitable<Conference>>();

            // Get last conference Id from model
            int idLastConference = await model.GetLastInsertedId();

            IsolatedStorageSettings localSettings = IsolatedStorageSettings.ApplicationSettings;

            // Get last conference saved Id
            int idLastConferenceSaved = localSettings.Contains(LibResources.ConferenceStorageKey) ? (int)localSettings[LibResources.ConferenceStorageKey] : 0;

            // If Ids are differents, update the saved Id and show a toast notification
            if (idLastConference != idLastConferenceSaved)
            {
                Conference lastConference = await model.GetAsync(idLastConference);

                ShellToast toast = new ShellToast
                {
                    Title = LibResources.NewConference,
                    Content = lastConference.Name,
                    NavigationUri = new Uri(string.Format("/ConferencePage.xaml?Id={0}", lastConference.Id), UriKind.Relative)
                };

                toast.Show();

                localSettings[LibResources.ConferenceStorageKey] = idLastConference;
                localSettings.Save();
            }
        }
        /// <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 = "";

            // If your application uses both PeriodicTask and ResourceIntensiveTask
            // you can branch your application code here. Otherwise, you don't need to.
            if (task is PeriodicTask)
            {
                // Execute periodic task actions here.
                toastMessage = "Periodic task running.";
            }
            else
            {
                // Execute resource-intensive task actions here.
                toastMessage = "Resource-intensive task running.";
            }

            // Launch a toast to show that the agent is running.
            // The toast will not be shown if the foreground application is running.
            ShellToast toast = new ShellToast();

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

            // If debugging is enabled, launch the agent again in one minute.
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));


            // Call NotifyComplete to let the system know the agent is done working.
            NotifyComplete();
        }
        protected override void OnInvoke(ScheduledTask task)
        {
            Task             = task;
            scheduledUpdates = 0;
            completedUpdates = 0;
            statusUpdateDb   = new StatusUpdateDataContext(StatusUpdateDataContext.DBConnectionString);
            // Define the query to gather all of the to-do items.
            var statusItemsInDB = from statusUpdateItem statusItem in statusUpdateDb.StatusUpdateItems
                                  select statusItem;

            NetworkInformationUtility.GetNetworkTypeCompleted += GetNetworkTypeCompleted;

            NetworkInformationUtility.GetNetworkTypeAsync(3000); // Timeout of 3 seconds
            // Execute the query and place the results into a collection.
            StatusUpdateItems = new ObservableCollection <statusUpdateItem>(statusItemsInDB);
            //TODO: Add code to perform your task in background
            string     toastMessage = "Started";
            ShellToast toast        = new ShellToast();

            toast.Title   = "Started";
            toast.Content = toastMessage;
            toast.Show();
            //var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(10) };
            //timer.Tick += (sender2, args) => { stopPosting(); timer.Stop(); };
            //timer.Start();
            //var timer2 = new DispatcherTimer { Interval = TimeSpan.FromSeconds(24) };
            //timer2.Tick += (sender3, args3) => { notify(); timer2.Stop(); };
            //timer2.Start();


            //postOnFb();
            //postOnLinkedin();
            //postOnTwitter();
            //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 void OnInvoke(ScheduledTask task)
        {
            string toastMessage = string.Empty;

            if ((task is PeriodicTask))
            {
                toastMessage = "periodic task running...";
            }
            else
            {
                toastMessage = "Resource-intensive task is running...";
            }

            ShellToast toast = new ShellToast();

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

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

            NotifyComplete();
        }
        private void GetNetworkTypeCompleted(object sender, NetworkTypeEventArgs networkTypeEventArgs)
        {
            if (networkTypeEventArgs.HasTimeout)
            {
                string     toastMessage = "network timeout";
                ShellToast toast        = new ShellToast();
                toast.Title   = ".";
                toast.Content = toastMessage;
                toast.Show();
                notify();
            }
            else if (networkTypeEventArgs.HasInternet)
            {
                startPosting();
            }
            else
            {
                string     toastMessage = "no network";
                ShellToast toast        = new ShellToast();
                toast.Title   = ".";
                toast.Content = toastMessage;
                toast.Show();
                notify();
            }

            // Always dispatch on the UI thread
        }
Exemple #20
0
        /// <summary>
        /// Change the alarm's BeginTime to now
        /// </summary>
        /// <param name="bs"></param>
        public void TriggerAlarm(BusStop bs)
        {
            if (bs == null)
            {
                return;
            }

            var alarm = ScheduledActionService.Find(bs.Id) as Alarm;

            if (alarm == null)
            {
                return;
            }

            alarm.BeginTime = DateTime.Now.AddSeconds(30);
            try
            {
                ScheduledActionService.Replace(alarm);
            }
            catch
            {
                ShellToast toast = new ShellToast()
                {
                    Content       = "Your stop is nearing",
                    NavigationUri = new Uri("/Pages/PanoPage.xaml", UriKind.Relative),
                    Title         = "Stop Alarm"
                };
                toast.Show();
            }

            this.Notif = null;
        }
Exemple #21
0
        /// <summary>
        /// Function to handle the callback from cloudservice - hides progress bar, sets logged in user to the
        /// checked one thats been sent to the cloudservice, then navigates 1 back in stack (Or toast if its dormant)
        /// </summary>
        /// <param name="sender">Sender object</param>
        /// <param name="e">Arguments that the CloudService Login function can return (Results, cancelled etc)</param>
        public void CloudService_LoginCompleted(object sender, Domain.CloudService.LoginCompletedEventArgs e)
        {
            // Remove progress bar visibility
            Progress = Visibility.Collapsed;

            // If success, apply new user to whole program and navigate away, else output error to view
            if (e.Result.ToString() == "Success")
            {
                application.User = user;
                if (!App.RunningInBackground)
                {
                    (application.RootVisual as PhoneApplicationFrame).GoBack();
                }
            }
            else
            {
                Message = e.Result.ToString();
            }

            //If app is dormant write message to toast for user
            if (App.RunningInBackground)
            {
                ShellToast msg = new ShellToast();
                msg.Title   = "Login:";
                msg.Content = e.Result.ToString();
                msg.Show();
            }
        }
 private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
 {
     ShellToast toast = new ShellToast();
     toast.Title = "Sample Application";
     toast.Content = "Background Task Complete";
     toast.Show();
 }
        /// <summary>
        /// 运行计划任务的代理
        /// </summary>
        /// <param name="task">
        /// 调用的任务
        /// </param>
        /// <remarks>
        /// 调用定期或资源密集型任务时调用此方法
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            string taskType="";
            //TODO: 添加用于在后台执行任务的代码
            if (task is PeriodicTask)
                taskType = "PeriodicTask";
            if (task is ResourceIntensiveTask)
                taskType = "ResourceIntensiveTask";

            ShellToast shellToast = new ShellToast();
            shellToast.Title = taskType;
            shellToast.Content = "测试";
            shellToast.NavigationUri=new System.Uri("/MainPage.xaml?taskType="+taskType, System.UriKind.Relative);
            shellToast.Show();

            ShellTile shellTile=ShellTile.ActiveTiles.First();
            shellTile.Update
                (new StandardTileData{
             Count=5
                } );

            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(15));

            NotifyComplete(); 
        }
Exemple #24
0
        public static void RemoveSentDocs()
        {
            try
            {
                Table <W2RTask> table = dataContext.GetTable <W2RTask>();

                // Define query to gather all of the to-do items.
                var toDoItemsInDB = from W2RTask task in dataContext.ToDoItems
                                    where task._isDone == true
                                    select task;

                // Execute query and place results into a collection.
                ObservableCollection <W2RTask> sentDocuments = new ObservableCollection <W2RTask>(toDoItemsInDB);

                foreach (W2RTask tsk in sentDocuments)
                {
                    table.DeleteOnSubmit(tsk);
                }

                dataContext.SubmitChanges();
            }
            catch (DbException e)
            {
                ShellToast toast = new ShellToast();
                toast.Title   = "WPToReader";
                toast.Content = "Exception occured in background task processing(RemoveDocs). Please report to developer.Error Msg = " + e.Message;
                toast.Show();
            }
        }
Exemple #25
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)
        {
            try
            {
                if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                {
                    return;
                }

                IAppSettingsStore settings = new AppSettingsStore(IsolatedStorageCacheManager.Instance);
                IFalconService    fService = new FalconWebServiceClient(ServiceLoginUrl);
                using (var updatesService = new CheckUpdatesService(settings, new RaptorService(fService, AESCipherManager.Instance), AESCipherManager.Instance))
                {
                    var updates = updatesService.Updates();


                    UpdateTile(updatesService.GetUpdateCount());

                    if (updates.Count() == 0)
                    {
#if DEBUG
                        ShellToast toast2 = new ShellToast();
                        toast2.Title   = "DEBUG: ";
                        toast2.Content = "No updates";
                        toast2.Show();
#endif
                    }
                    else
                    {
                        string message =
                            updates.Count() == 1
                            ? string.Format("Torrent {0} downloaded", updates.First())
                            : string.Format("{0} favorite torrents were downloaded", updates.Count());

                        ShellToast toast = new ShellToast();
                        toast.Title   = "Torrents: ";
                        toast.Content = message;
                        toast.Show();
                    }
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                ShellToast toast = new ShellToast();
                toast.Title   = "Error:";
                toast.Content = ex.Message;
                toast.Show();
#endif
            }
            finally
            {
#if DEBUG_AGENT
                ScheduledActionService.LaunchForTest(
                    task.Name, TimeSpan.FromSeconds(30));
#endif

                NotifyComplete();
            }
        }
Exemple #26
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: see when last prompted & if time for next prompt

            var data = new MainViewModel();

            var nextLesson = data.Lessons.FirstOrDefault(l => !l.Completed);

            var toast = new ShellToast
            {
                Title = "Time for",
                Content = nextLesson.Name
            };
            toast.Show();

            var mainTile = ShellTile.ActiveTiles.First();

            mainTile.Update(new IconicTileData
            {
                WideContent1 = "Time for more",
                WideContent2 = "watch " + nextLesson.Name
            });

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

            NotifyComplete();
        }
Exemple #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)
        {
            if (!System.IO.File.Exists(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "flag")))
            {
                Sincronizacao.Sincronizacao sinc = new Sincronizacao.Sincronizacao();
                sinc.Sincronizar();
                while (sinc.concluiu == false)
                {
                }

                if (!sinc.erro)
                {
                    ShellToast toast = new ShellToast();
                    toast.Title   = "TCCWP";
                    toast.Content = "Sincronizou";
                    toast.Show();
                }
            }
#if DEBUG_AGENT
            ScheduledActionService.LaunchForTest(task.Name, System.TimeSpan.FromSeconds(60));
#endif


            NotifyComplete();
        }
Exemple #28
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)
        {
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(61));

            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                Core.TileOptions to = new Core.TileOptions();
                to.UpdateTile();
            });

            giveToast();


            string toastMessage = "Periodic task running.";

            ShellToast toast = new ShellToast();

            toast.Title   = "Hey";
            toast.Content = toastMessage;
            //toast.Show();

            addBatteryStatus();



            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 void OnInvoke(ScheduledTask task)
        {
            try
            {
                if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
                    return;

                IAppSettingsStore settings = new AppSettingsStore(IsolatedStorageCacheManager.Instance);
                IFalconService fService = new FalconWebServiceClient(ServiceLoginUrl);
                using (var updatesService = new CheckUpdatesService(settings, new RaptorService(fService, AESCipherManager.Instance), AESCipherManager.Instance))
                {
                    var updates = updatesService.Updates();

                    UpdateTile(updatesService.GetUpdateCount());

                    if (updates.Count() == 0)
                    {
            #if DEBUG
                        ShellToast toast2 = new ShellToast();
                        toast2.Title = "DEBUG: ";
                        toast2.Content = "No updates";
                        toast2.Show();
            #endif
                    }
                    else
                    {
                        string message =
                            updates.Count() == 1
                            ? string.Format("Torrent {0} downloaded", updates.First())
                            : string.Format("{0} favorite torrents were downloaded", updates.Count());

                        ShellToast toast = new ShellToast();
                        toast.Title = "Torrents: ";
                        toast.Content = message;
                        toast.Show();
                    }
                }

            }
            catch (Exception ex)
            {
            #if DEBUG
                ShellToast toast = new ShellToast();
                toast.Title = "Error:";
                toast.Content = ex.Message;
                toast.Show();
            #endif
            }
            finally
            {

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

                NotifyComplete();
            }
        }
        private void LoadUrl()
        {
            try
            {
                RestRequest request = new RestRequest(URL.BASE3 + "APIv2/donation/get_donation.php", Method.POST);

                request.AddHeader("content-type", "multipart/form-data");
                request.AddParameter("id_donors", Navigation.navIdDonors);
                request.AddParameter("token", Navigation.token);

                //calling server with restClient
                RestClient restClient = new RestClient();
                restClient.ExecuteAsync(request, (response) =>
                {
                    ShellToast toast = new ShellToast();
                    toast.Title = "Status Upload";
                    JObject jRoot = JObject.Parse(response.Content);
                    String result = jRoot.SelectToken("result").ToString();
                    JArray JItem = JArray.Parse(jRoot.SelectToken("item").ToString());

                    foreach (JObject item in JItem)
                    {
                        ModelGetKeranjang modelGetKeranjang = new ModelGetKeranjang();
                        modelGetKeranjang.id_donation = item.SelectToken("id_donation").ToString();
                        modelGetKeranjang.id_fosterchildren = item.SelectToken("id_fosterchildren").ToString();
                        modelGetKeranjang.children_name = item.SelectToken("children_name").ToString();
                        modelGetKeranjang.photo = URL.BASE3 + "modul/mod_AnakAsuh/photo/" + item.SelectToken("photo").ToString();
                        modelGetKeranjang.pre_donation_time = item.SelectToken("pre_donation_time").ToString();
                        modelGetKeranjang.cha_org_name = item.SelectToken("cha_org_name").ToString();
                        collectionGetKeranjang.Add(modelGetKeranjang);

                    }
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        if (result.Equals("success"))
                        {
                            PageKeranjangDonasi keranjangdonasi = new PageKeranjangDonasi();
                            keranjangdonasi.LoadingBar.Visibility = Visibility.Collapsed;
                           
                        }
                        else
                        {
                           
                        }
                    
                    }
                    else
                    {
                        //error ocured during upload

                        toast.Content = "Your posting failed. Please check the Internet connection.";
                        toast.Show();
                        //progressBar1.Visibility = System.Windows.Visibility.Visible;

                    }
                });
            }
            catch { }
        }
Exemple #31
0
        /// <summary>
        /// Add pivot dynamically on the bases of  filter city list count.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                base.OnNavigatedTo(e);
                this.DataContext = App.ViewModel.CityDetailsViewModel;
                string   parameterValue = NavigationContext.QueryString["parameter"];
                string[] parameters     = parameterValue.Split(new string[] { Constant.Seprator }, StringSplitOptions.None);
                if (e.NavigationMode == NavigationMode.New)
                {
                    var localSettings = IsolatedStorageSettings.ApplicationSettings;
                    int count         = 0;
                    if (localSettings.Contains("TotalUpdatedItems"))
                    {
                        count = Convert.ToInt32(localSettings["TotalUpdatedItems"]);
                    }
                    if (count != 0)
                    {
                        for (var i = 0; i < count; i++)
                        {
                            if (localSettings.Contains("DatasetName" + i))
                            {
                                if (localSettings["DatasetName" + i].ToString().Equals(parameters[0]) && localSettings["City" + i].ToString().Equals(parameters[1]))
                                {
                                    localSettings["UpdatedItems"] = Convert.ToInt32(localSettings["UpdatedItems"]) - 1;

                                    localSettings.Remove("DatasetName" + i);
                                    localSettings.Remove("City" + i);

                                    localSettings.Save();
                                    if (Convert.ToInt32(localSettings["UpdatedItems"]) > 0)
                                    {
                                        UpdatePrimaryTile(localSettings["UpdatedItems"].ToString() + " " + Constant.NotificationMsg);
                                        ShellToast toast = new ShellToast();
                                        toast.Title         = localSettings["UpdatedItems"].ToString();
                                        toast.Content       = Constant.NotificationMsg;
                                        toast.NavigationUri = new Uri("/MainPage.xaml", UriKind.Relative);
                                        toast.Show();
                                    }
                                    else
                                    {
                                        UpdatePrimaryTile(string.Empty);
                                    }
                                }
                            }
                        }
                    }
                    LoadPivotItems(parameters[0]);
                }
                else if (e.NavigationMode == NavigationMode.Back)
                {
                    ucCityDetailsControl.LoadCategoriesData();
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }
        /// <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)
        {
            System.Diagnostics.Debug.WriteLine("Launching the agent...");

            int cleared = -1;

            if (getSetting("clean"))
            {
                var fires = getIntSetting("taskFireCount");
                System.Diagnostics.Debug.WriteLine("Task fire count: " + fires);
                if (fires > 48)
                { //only run ever 48 launches, or about 24 hours
                    setSetting("taskFireCount", 0);

                    //Clean cache
                    cleared = CacheClearer.cleanCache.clearAll();
                    if (getSetting("toast"))
                    {
                        ShellToast toast = new ShellToast();
                        toast.Content = "Cleared " + CacheClearer.Utils.readableFileSize(cleared);
                        toast.Title   = "CacheClearer";
                        toast.Show();
                    }
                }
                else
                {
                    setSetting("taskFireCount", fires + 1);
                }
            }

            if (getSetting("updatetile"))
            {
                if (cleared >= 0)
                {
                    BackTitle   = "Cache cleared";
                    BackContent = DateTime.Now.ToString() + "\n" + CacheClearer.Utils.readableFileSize(cleared);
                }
                else
                {
                    uint bytes = CacheClearer.cleanCache.getTotalCacheSize();
                    BackContent = DateTime.Now.ToString() + "\n" + CacheClearer.Utils.readableFileSize(bytes);
                    BackTitle   = "Cache Size";
                }
                // Execute periodic task actions here.
                ShellTile TileToFind = ShellTile.ActiveTiles.First();
                if (TileToFind != null)
                {
                    StandardTileData NewTileData = new StandardTileData
                    {
                        BackContent = BackContent,
                        BackTitle   = BackTitle
                    };
                    TileToFind.Update(NewTileData);
                }
            }


            NotifyComplete();
        }
Exemple #33
0
        public static void MostrarToast(string titulo, string conteudo)
        {
            ShellToast toast = new ShellToast();

            toast.Title   = titulo;
            toast.Content = conteudo;
            toast.Show();
        }
Exemple #34
0
        static public void PushSend(string text)
        {
            ShellToast toast = new ShellToast();

            toast.Title   = "Alert";
            toast.Content = text;
            toast.Show();
        }
        /// <summary>
        /// Shows a toast notification
        /// </summary>
        /// <param name="content">Content of notification</param>
        /// <param name="title">Title of notification</param>
        /// <param name="navigationUri">URI to navigate to</param>
        private static void RaiseToast(String content, String title, Uri navigationUri)
        {
            var toast = new ShellToast {
                Content = content, Title = title, NavigationUri = navigationUri
            };

            toast.Show();
        }
Exemple #36
0
        public void ShowToastNotification(string title, string content)
        {
            ShellToast toast = new ShellToast();

            toast.Title   = title;
            toast.Content = content;
            toast.Show();
        }
        public static void ErrorToast(Exception exc)
        {
            ShellToast toast = new ShellToast();

            toast.Content = DateTime.Now.ToShortTimeString() + " " + exc.ToString();
            toast.Title   = "Waze Task Error";
            toast.Show();
        }
 public void testToast()
 {
     ShellToast toastPop = new ShellToast();
     toastPop.Title = "Test";
     toastPop.Content = "Hello world";
     toastPop.Show();
     ScheduledActionService.LaunchForTest("energyPoll", TimeSpan.FromSeconds(60));
 }
        public void testToast()
        {
            ShellToast toastPop = new ShellToast();

            toastPop.Title   = "Test";
            toastPop.Content = "Hello world";
            toastPop.Show();
            ScheduledActionService.LaunchForTest("energyPoll", TimeSpan.FromSeconds(60));
        }
Exemple #40
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)
        {
            try
            {
                Config.Initialize();
                var services = new WPSilverlightCoreServices();
                var tb       = new TransitBase.TransitBaseComponent(
                    root: services.FileSystem.GetAppStorageRoot(),
                    directionsService: null,
                    preLoad: false,
                    bigTableLimit: Config.Current.BigTableLimit,
                    checkSameRoutes: Config.Current.CheckSameRoutes,
                    latitudeDegreeDistance: Config.Current.LatitudeDegreeDistance,
                    longitudeDegreeDistance: Config.Current.LongitudeDegreeDistance
                    );
                var ub     = new UserBase.UserBaseLinqToSQLComponent("Data Source=isostore:ddb.sdf", Config.Current.UBVersion, forbidMigration: true);
                var common = new CommonComponent(services, tb, ub);

                foreach (var tile in ShellTile.ActiveTiles)
                {
                    if (tile.NavigationUri.OriginalString.StartsWith("/MainPage.xaml?tile="))
                    {
                        if (tile.NavigationUri.OriginalString.StartsWith("/MainPage.xaml?tile=stoproute"))
                        {
                            updateTileUnknown(tile);
                        }
                        else
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                Tiles.UpdateTile(tile);
                                //bool ret = Tiles.UpdateTile(tile);
                                //if (ret == false)
                                //    updateTileUnknown(tile);
                                tb.Flush();
                            });
                        }
                    }
                }
                if (NetworkInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 && NetworkInterface.GetIsNetworkAvailable() && !AppFields.UpdateAvailable)
                {
                    var checkResult = await UpdateMonitor.CheckUpdate();

                    if (checkResult == UpdateMonitor.Result.Found)
                    {
                        ShellToast toast = new ShellToast();
                        toast.Title   = "Update";
                        toast.Content = "A database update is required.";
                        toast.Show();
                    }
                }
            }
            catch (Exception) { }


            NotifyComplete();
        }
Exemple #41
0
 private void bark_Click(object sender, RoutedEventArgs e)
 {
     App.barks_sent.Add(new bark { When = DateTime.Now.ToShortDateString(), From = memname.Text, Pack = packname.Text });
     ShellToast st = new ShellToast();
     st.Title = "Bark Bark:";
     st.Content = "from " + memname.Text;
     st.Show();
     NavigationService.GoBack();
 }
Exemple #42
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
     ShellToast toast = new ShellToast();
     toast.Title = "DropboxSync";
     toast.Content = "Ran";
     toast.Show();
     NotifyComplete();
 }
Exemple #43
0
 public void giveBatteryFullToast()
 {
     if (SystemEndPoints.currentBatteryLevel() > 99 && SystemEndPoints.isCharging())
     {
         ShellToast toast = new ShellToast();
         toast.Title   = "BatteryGuru";
         toast.Content = "You can unplug me.";
         toast.Show();
     }
 }
Exemple #44
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
     ShellToast st = new ShellToast();
     st.Title = "Hello";
     st.Content = "World !";
     st.NavigationUri = new System.Uri("/MainPage.xaml", System.UriKind.Relative);
     st.Show();
     NotifyComplete();
 }
Exemple #45
0
        public void ExecuteAlertForNotification(Notification notification, bool withSound)
        {
            VibrateController vibrateController = VibrateController.Default;
            vibrateController.Start(TimeSpan.FromSeconds(1));

            if (withSound)
            {
                Stream soundStream = Application.GetResourceStream(new Uri("Assets/Audio/ow.wav", UriKind.Relative)).Stream;
                SoundEffectInstance Sound = SoundEffect.FromStream(soundStream).CreateInstance();
                Sound.Play();

                while (Sound.State == SoundState.Playing)
                {

                }

                switch (notification.Type)
                {
                    case 1:
                        soundStream = Application.GetResourceStream(new Uri("Assets/Audio/vamo.wav", UriKind.Relative)).Stream;
                        break;

                    case 2:
                        soundStream = Application.GetResourceStream(new Uri("Assets/Audio/perai.wav", UriKind.Relative)).Stream;
                        break;

                    case 3:
                        soundStream = Application.GetResourceStream(new Uri("Assets/Audio/chegou.wav", UriKind.Relative)).Stream;
                        break;

                    case 4:
                        soundStream = Application.GetResourceStream(new Uri("Assets/Audio/maneiro.wav", UriKind.Relative)).Stream;
                        break;

                    case 5:
                        soundStream = Application.GetResourceStream(new Uri("Assets/Audio/tocomfome.wav", UriKind.Relative)).Stream;
                        break;

                    case 6:
                        soundStream = Application.GetResourceStream(new Uri("Assets/Audio/owkey.wav", UriKind.Relative)).Stream;
                        break;
                }

                Sound = SoundEffect.FromStream(soundStream).CreateInstance();
                Sound.Play();
            }

            ShellToast toast = new ShellToast();

            toast.Title = "Ow";
            toast.Content = String.Format(AppResources.NotificationMessage,
                notification.Contact.FirstName, notification.TypeToString());

            toast.Show();
        }
        protected async override void OnInvoke(Microsoft.Phone.Scheduler.ScheduledTask task)
        {
            var  userAccountEntity = new UserAccountEntity();
            var  authManager       = new AuthenticationManager();
            bool loginTest         = await authManager.RefreshAccessToken(userAccountEntity);

            if (loginTest)
            {
                UserAccountEntity.User user = await authManager.GetUserEntity(userAccountEntity);

                if (user == null)
                {
                    return;
                }
                userAccountEntity.SetUserEntity(user);
                NotificationEntity notificationEntity = await GetNotifications(userAccountEntity);

                if (notificationEntity == null)
                {
                    return;
                }
                if (notificationEntity.Notifications == null)
                {
                    return;
                }
                var notificationList = notificationEntity.Notifications.Where(o => o.SeenFlag == false);
                NotificationEntity.Notification firstNotification = notificationList.FirstOrDefault();
                ShellTile appTile = ShellTile.ActiveTiles.First();
                if (firstNotification != null)
                {
                    var toastMessage = firstNotification.Message;
                    var toast        = new ShellToast {
                        Title = "FoulPlay", Content = toastMessage
                    };
                    toast.Show();
                    if (appTile != null)
                    {
                        var tileData = new FlipTileData
                        {
                            Title           = "FoulPlay",
                            BackTitle       = "FoulPlay",
                            BackContent     = firstNotification.Message,
                            WideBackContent = firstNotification.Message,
                            Count           = notificationList.Count()
                        };
                        appTile.Update(tileData);
                    }
                    await NotificationManager.ClearNotification(firstNotification, userAccountEntity);
                }
            }
#if DEBUG_AGENT
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));
#endif
            NotifyComplete();
        }
        public static void ShowToast(String title, String message, String NavigationURL)
        {
            var toast = new ShellToast
            {
                Title = title,
                Content = message,
                NavigationUri = new System.Uri(NavigationURL, System.UriKind.Relative)
            };

            toast.Show();
        }
        private void NotifyViaToast()
        {
            ShellToast toast = new ShellToast
            {
                Title = "TIG Todo",
                Content = string.Format("You have {0} incomplete todos.", incompleteItems.Length),
                NavigationUri = new Uri("/MainPage.xaml", UriKind.Relative)
            };

            toast.Show();
        }
        /// <summary>
        /// Display a toast message with the specified title and content.
        /// </summary>
        /// <param name="title">The title of the toast message.</param>
        /// <param name="content">The contents of the toast message.</param>
        /// <param name="navigationUri">Uri to navigate to if the user taps the toast message.</param>
        public void Show(string title, string content, Uri navigationUri)
        {
            var toast = new ShellToast()
            {
                Title = title,
                Content = content,
                NavigationUri = navigationUri
            };

            toast.Show();
        }
        /// <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

            ShellToast Toast = new ShellToast();

            Toast.Title = "Wi-Fi Enabled";
            Toast.Content = DeviceNetworkInformation.IsWiFiEnabled.ToString();
            Toast.Show();

            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 async override void OnInvoke(ScheduledTask task)
        {
            var isProvider = Windows.Phone.System.UserProfile.LockScreenManager.IsProvidedByCurrentApplication;
            if (isProvider)
            {
                var uri = Lib.LockscreenUpdater.GetLockScreenImageUri();
                var currentFileName = System.IO.Path.GetFileName(uri.AbsolutePath);

                var pictures = (await Lib.WallpaperManager.QueryLocalPictures()).ToList();

                if (pictures.Count == 0)
                {
                    Lib.LockscreenUpdater.SetLockScreenImage("DefaultLockScreen.jpg", true);
                }
                else
                {
                    var currentPictureFile = pictures.FirstOrDefault(p => p.Name == currentFileName);
                    if (currentPictureFile != null)
                    {
                        var indexOfCurrent = pictures.IndexOf(currentPictureFile);
                        if (indexOfCurrent < pictures.Count - 1)
                        {
                            Lib.LockscreenUpdater.SetLockScreenImage(pictures[indexOfCurrent + 1].Name, false);
                        }
                        else
                        {
                            Lib.LockscreenUpdater.SetLockScreenImage(pictures.First().Name, false);
                        }
                    }
                    else
                    {
                        Lib.LockscreenUpdater.SetLockScreenImage(pictures.First().Name, false);
                    }
                }
                
            
            // Launch a toast to show that the agent is running.
            // The toast will not be shown if the foreground application is running.
            ShellToast toast = new ShellToast();
            toast.Title = "FavWallpaper";
            toast.Content = "update lockscreen image";
            toast.Show();

            // If debugging is enabled, launch the agent again in one minute.
#if DEBUG
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));
#endif

            }

            NotifyComplete();
        }
Exemple #52
0
        /// <summary>
        /// Agente que ejecuta una tarea programada
        /// </summary>
        /// <param name="task">
        /// Tarea invocada
        /// </param>
        /// <remarks>
        /// Se llama a este método cuando se invoca una tarea periódica o con uso intensivo de recursos
        /// </remarks>
        protected async override void OnInvoke(ScheduledTask task)
        {
            //TODO: Agregar código para realizar la tarea en segundo plano
            // Intentaremos descargar una nueva imagen
            bool result = await this.DownloadNewImageTest();

            ShellToast toast = new ShellToast()
            {
                Content = "Se ha descargado una nueva imagen",
                Title = "Nueva Imagen",
                NavigationUri = new Uri("/Views/MainPage.xaml",UriKind.Relative)
            };

            if(result)
                toast.Show();

            // Si ya hay imagenes descargadas, las agregamos al Tile
            List<Image> images = StorageHelper.GetImages();
            if (images.Count > 0)
            {
                CycleTileData tile = new CycleTileData();
                tile.Count = images.Count;
                tile.Title = StorageHelper.GetTag() ?? "Chihuahua";
                List<Uri> uris = new List<Uri>();
                
                foreach (var item in images)
                {                    
                    uris.Add(new Uri("isostore:" + item.UrlLocal, UriKind.Absolute));                    
                }

                tile.CycleImages = uris;
                var activeTile = Microsoft.Phone.Shell.ShellTile.ActiveTiles.First();

                if (activeTile != null)
                {
                    activeTile.Update(tile);
                }


                // Cambiamos el lockscreen por una imagen random
                var isProvider = Windows.Phone.System.UserProfile.LockScreenManager.IsProvidedByCurrentApplication;
                if (isProvider)
                {
                    int random = new Random().Next(0,images.Count - 1);
                    string tempUri = "ms-appdata:///local/" + images[random].UrlLocal;
                    Windows.Phone.System.UserProfile.LockScreen.SetImageUri(new Uri("ms-appdata:///local/" + images[random].UrlLocal, UriKind.Absolute));
                }
            }
            
            NotifyComplete();
        }
        private void LoadUrl()
        {
            try
            {
                RestRequest request = new RestRequest(URL.BASE3 + "APIv2/donation/donation_list.php", Method.POST);

                request.AddHeader("content-type", "multipart/form-data");
                request.AddParameter("id_donors", Navigation.navIdDonors);
                request.AddParameter("token", Navigation.token);
                request.AddParameter("id_fosterchildren", Navigation.navIdAnak);

                //calling server with restClient
                RestClient restClient = new RestClient();
                restClient.ExecuteAsync(request, (response) =>
                {
                    ShellToast toast = new ShellToast();
                    toast.Title = "Status Upload";
                    JObject jRoot = JObject.Parse(response.Content);
                    String result = jRoot.SelectToken("result").ToString();
                    ModelKeranjang modelKeranjang = new ModelKeranjang();
                    modelKeranjang.id_donation = jRoot.SelectToken("id_donation").ToString();
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        if (result.Equals("success"))
                        {

                            if (MessageBox.Show("Request has done, check your Donation List") == MessageBoxResult.OK)
                            {
                                var frame = App.Current.RootVisual as PhoneApplicationFrame;
                                frame.Navigate(new Uri("/Views/PageKeranjangDonasi.xaml", UriKind.Relative));
                            }
                        }
                        else
                        {
                            MessageBox.Show("Request has done, check your Donation List");
                        }
                    }
                    else
                    {
                        //error ocured during upload
                        toast.Content = "Your posting failed. Please check the Internet connection.";
                        toast.Show();

                        //progressBar1.Visibility = System.Windows.Visibility.Visible;

                    }
                });
            }
            catch { 
            }
        }
Exemple #54
0
 static void cameraCaptureTask_Completed(object sender, PhotoResult e)
 {
     if (e.TaskResult == TaskResult.OK)
     {
         ShellToast toast= new ShellToast();
         toast.Title = "I hate Guy";
         toast.Content = "I really hate him";
         toast.Show();
         //Code to display the photo on the page in an image control named myImage.
         //System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
         //bmp.SetSource(e.ChosenPhoto);
         //myImage.Source = bmp;
     }
 }
        /// <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)
        {
            var h = new OAuthMessageHandler(new HttpClientHandler());
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("https://api-content.dropbox.com/1/dropbox/");

            string toastMessage = "Upload started";
            ShellToast toast = new ShellToast();
            toast.Title = "Auto Upload";
            toast.Content = toastMessage;
            toast.Show();

            PostFile(client);
        }
        /// <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)
        {
            #if DEBUG
            ShellToast toast = new ShellToast()
            {
                Title = "Start " + (DeviceStatus.ApplicationCurrentMemoryUsage / 1024).ToString() + " KB",
                Content = (DeviceStatus.ApplicationMemoryUsageLimit / 1024).ToString() + " KB"
            };
            toast.Show();
            #endif

            TileUpdater updater = new TileUpdater();
            updater.OnUpdateCompleted += updater_OnUpdateCompleted;
            updater.UpdateAsync();
        }
        /// <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 PushToServer(object obj)
        {
            try
            {

                RestRequest request = new RestRequest(URL.BASE3 + "api/environment/environment.php", Method.POST);

               
                //calling server with restClient
                RestClient restClient = new RestClient();
                restClient.ExecuteAsync(request, (response) =>
                {
                    ShellToast toast = new ShellToast();
                    toast.Title = "Status Upload";
                    JObject jRoot = JObject.Parse(response.Content);
                    String result = jRoot.SelectToken("result").ToString();
                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        if (result.Equals("sukses"))
                        {
                            MessageBox.Show("Your posting successfully uploaded");

                        }
                        else
                        {

                            MessageBox.Show("Failed");
                        }
                    }
                    else
                    {
                        //error ocured during upload
                        MessageBox.Show("Your posting failed. Please check the Internet connection.");
                    }
                });
            }
            catch (Exception ec)
            {
                MessageBox.Show("Failed to display, the Internet connection is unstable.");
            }
            finally
            {
                //ProgressVisibiliy = Visibility.Visible;
            }
        }
Exemple #59
0
        /// <summary>
        /// Agent qui exécute une tâche planifiée
        /// </summary>
        /// <param name="task">
        /// La tâche appelée
        /// </param>
        /// <remarks>
        /// Cette méthode est appelée lorsqu'une tâche périodique ou  resource intensive est appelée
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            if (task.Name.Equals("RemindAgent", StringComparison.OrdinalIgnoreCase))
            {
                Debug.WriteLine("MESSAGE FROM AGENT: Called!");

               Mutex mutex = new Mutex(true, "RemindAgentData");
                mutex.WaitOne();
                IsolatedStorageSettings setting = IsolatedStorageSettings.ApplicationSettings;
                List<RemindEvent> events = (List<RemindEvent>)setting["events"];
                mutex.ReleaseMutex();

                int i = 0;
                bool Alert = false;
                while (i < events.Count)
                {
                    DateTime lastTime = events[i].lastTime;
                    TimeSpan repeatEvery = events[i].repeatEvery;
                    double repeatEverySeconds = repeatEvery.TotalSeconds;
                    TimeSpan timeLeft = DateTime.Now - (lastTime.Add(repeatEvery));
                    double timeLeftSeconds = timeLeft.TotalSeconds;
                    double eventComingSoon = (10 / 100) * repeatEverySeconds;

                    if (timeLeft.TotalSeconds <= 0)
                        Alert = true; // In this case, the user missed the event :(
                    if (timeLeftSeconds < eventComingSoon)
                        Alert = true; // If we are 10% away from the next "milestone", we warn the user

                    i++;
                }

                if (Alert)
                {
                    ShellToast toast = new ShellToast();
                    toast.Title = "REMINDME";
                    toast.Content = "You have events coming soon!";
                    toast.NavigationUri = new Uri("/MainPage.xaml", UriKind.Relative);
                    toast.Show();
                    Debug.WriteLine("EVENTS COMING");
                }
             }

            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(3));
            NotifyComplete();
        }
Exemple #60
0
 void geolocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
 {
     Dispatcher.BeginInvoke(() =>
     {
         if (App.IsRunningInBackground)
         {
             ShellToast toast = new ShellToast();
             toast.Content = string.Format("Lat: {0} Long: {1}", args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude);
             toast.Title = "Cambio de ubicación";
             toast.Show();
         }
         else
         {
             map.SetView(new GeoCoordinate(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude), 15, MapAnimationKind.Parabolic);
             //map.Center = new GeoCoordinate(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude);
         }
     });
 }