Beispiel #1
0
        //Notification - Day time progression
        void ShowNotiDayTime()
        {
            try
            {
                if (setNotiDayTime)
                {
                    //Load Day Time Remaining
                    TimeSpan TimeTomorrow = DateTime.Today.AddDays(1).Subtract(DateTimeNow);
                    int      TimeTomorrowHours = TimeTomorrow.Hours; int TimeTomorrowMinutes = TimeTomorrow.Minutes;

                    string TimeTillTomorrow = "";
                    if (TimeTomorrowHours != 0)
                    {
                        TimeTillTomorrow = TimeTillTomorrow + TimeTomorrowHours + "h ";
                    }
                    if (TimeTomorrowMinutes != 0)
                    {
                        TimeTillTomorrow = TimeTillTomorrow + TimeTomorrowMinutes + "m ";
                    }
                    if (String.IsNullOrEmpty(TimeTillTomorrow))
                    {
                        TimeTillTomorrow = "a minute ";
                    }

                    //Set Notification Clock Icon
                    string ClockIcon = "ms-appx:///Assets/Analog/Minimal/" + DateTimeNow.ToString("hmm") + ".png";

                    if (setNotiStyle == 0)
                    {
                        Tile_XmlContent.LoadXml("<toast><visual><binding template=\"ToastImageAndText02\"><image id=\"1\" src=\"" + ClockIcon + "\"/><text id=\"1\">The day has progressed " + DayTimeProgress + "%</text><text id=\"2\">And has about " + TimeTillTomorrow + "time remaining, enjoy the rest of your day!</text></binding></visual><audio silent=\"true\"/></toast>");
                        Toast_UpdateManager.Show(new ToastNotification(Tile_XmlContent)
                        {
                            SuppressPopup = true, Tag = "T5", Group = "G1"
                        });
                    }
                    else if (setNotiStyle == 1)
                    {
                        Tile_XmlContent.LoadXml("<toast><visual><binding template=\"ToastImageAndText02\"><image id=\"1\" src=\"" + ClockIcon + "\"/><text id=\"1\">The day has progressed " + DayTimeProgress + "%</text><text id=\"2\">And has about " + TimeTillTomorrow + "time remaining, enjoy the rest of your day!</text></binding></visual><audio silent=\"true\"/></toast>");
                        Toast_UpdateManager.Show(new ToastNotification(Tile_XmlContent)
                        {
                            SuppressPopup = false, Tag = "T5", Group = "G1"
                        });
                    }
                    else if (setNotiStyle == 2)
                    {
                        Tile_XmlContent.LoadXml("<toast><visual><binding template=\"ToastImageAndText02\"><image id=\"1\" src=\"" + ClockIcon + "\"/><text id=\"1\">The day has progressed " + DayTimeProgress + "%</text><text id=\"2\">And has about " + TimeTillTomorrow + "time remaining, enjoy the rest of your day!</text></binding></visual><audio silent=\"false\"/></toast>");
                        Toast_UpdateManager.Show(new ToastNotification(Tile_XmlContent)
                        {
                            SuppressPopup = false, Tag = "T5", Group = "G1"
                        });
                    }
                }
                //else { Toast_History.Remove("T5", "G1"); }
            }
            catch { }
        }
Beispiel #2
0
        public async Task <object> SendWeightNotification(int patientId, string doctorEmail, [FromBody] PatientWeight item)
        {
            Models.Patient patient    = await new PatientController(IPConfig, JsonStructureConfig).Read(patientId);
            var            goalWeight = await new GoalWeightController(IPConfig, JsonStructureConfig)
                                        .Read(patientId, DateTimeNow.ToString(italianDateFormat));

            if (item.Weight <= goalWeight.Goal)
            {
                await HubContext.Clients.All.SendAsync(doctorEmail + "/" + WeightConfig.Key[0], patient.Name, patientId);
            }

            return(Empty);
        }
Beispiel #3
0
        public void Test_ToString()
        {
            //---------------Set up test pack-------------------
            DateTimeNow dteNow = new DateTimeNow();
            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            string toString = dteNow.ToString();
            //---------------Test Result -----------------------
            DateTime dteParsedDateTime;

            Assert.IsTrue(DateTime.TryParse(toString, out dteParsedDateTime));
//            Assert.IsTrue(dteNow == dteParsedDateTime);
            Assert.AreEqual(toString, dteParsedDateTime.ToString());
        }
        public async Task <object> Update(int id, [FromBody] GoalWeight item)
        {
            item.StartDate   = DateTimeNow;
            item.StartWeight = (await new WeightController(IPConfig, JsonStructureConfig).
                                Read(id, DateTimeNow.ToString(italianDateFormat))).Weight;

            var jsonGoalWeight = new JObject
            {
                { JsonDataConfig.Root, JObject.Parse(JsonConvert.SerializeObject(item, serializerSettings)) }
            };

            await APIUtils.PostAsync(IPConfig.GetTotalUrlUser() + id + JsonDataConfig.Url, jsonGoalWeight.ToString());

            return(Empty);
        }
Beispiel #5
0
        public async Task <object> SendActivitySummaryNotification(int patientId, string doctorEmail, [FromBody] Models.PatientData.ActivitySummary item)
        {
            Models.Patient patient   = await new PatientController(IPConfig, JsonStructureConfig).Read(patientId);
            var            goalSteps = await new GoalStepsDailyController(IPConfig, JsonStructureConfig)
                                       .Read(patientId, DateTimeNow.ToString(italianDateFormat));
            var goalCalories = await new GoalCaloriesOutController(IPConfig, JsonStructureConfig)
                               .Read(patientId, DateTimeNow.ToString(italianDateFormat));

            if (item.Steps >= goalSteps.Goal)
            {
                await HubContext.Clients.All.SendAsync(doctorEmail + "/" + ActivitySummaryConfig.Key[0], patient.Name, patientId);
            }
            if (item.CaloriesCategory.OutCalories >= goalCalories.Goal)
            {
                await HubContext.Clients.All.SendAsync(doctorEmail + "/" + ActivitySummaryConfig.Key[1], patient.Name, patientId);
            }

            return(Empty);
        }
        private async Task <List <GoalRealDataCompare> > GetGoalRealDataCompareListAsync(string doctorEmail)
        {
            List <GoalRealDataCompare> goalRealDataCompareList = new List <GoalRealDataCompare>();

            var dateNow = DateTimeNow.ToString(italianDateFormat);
            var doctor  = HttpContext.Session.Get <Models.Doctor>(sessionKeyName + doctorEmail);

            foreach (Models.Patient patient in doctor.Patients)
            {
                var realData = await RealDataController.Read(patient.Id, dateNow);

                var goal = await GoalController.Read(patient.Id, dateNow);

                goalRealDataCompareList.Add(new GoalRealDataCompare
                {
                    Goal        = (goal != null) ? goal.Goal : default(TType),
                    RealData    = (realData != null) ? realData.RealData : default(TType),
                    PatientName = patient.Name
                });
            }

            return(goalRealDataCompareList);
        }
Beispiel #7
0
        public async Task <IViewComponentResult> InvokeAsync(Models.Patient currentPatient)
        {
            //List<Models.PatientData.ActivitySummary> summariesMonth = await ActivitySummaryController.Read(currentPatient.Id, DateTimeNow.ToString(italianDateFormat), "1m");
            //List<Models.PatientData.ActivitySummary> summariesWeek = await ActivitySummaryController.Read(currentPatient.Id, DateTimeNow.ToString(italianDateFormat), "1w");

            var data = new PatientPersonalData
            {
                Patient = currentPatient
            };

            //data.TotalSteps.Month = (from s in summariesMonth select s.Steps).Sum();
            //data.TotalSteps.Week = (from s in summariesWeek select s.Steps).Sum();

            //data.TotalCalories.Month = (from s in summariesMonth select s.CaloriesCategory.OutCalories).Sum();
            //data.TotalCalories.Week = (from s in summariesWeek select s.CaloriesCategory.OutCalories).Sum();

            //data.AverageFloors.Month = (from s in summariesMonth select s.Floors).Average();
            //data.AverageFloors.Week = (from s in summariesWeek select s.Floors).Average();

            data.WeightComparison.Today = await WeightController.Read(currentPatient.Id, DateTimeNow.ToString(italianDateFormat));

            data.WeightComparison.Yesterday = await WeightController.Read(currentPatient.Id, DateTimeNow.Subtract(TimeSpan.FromDays(1)).ToString(italianDateFormat));

            return(View(data));
        }
Beispiel #8
0
        public void TestConvertValueToPropertyType_NowStringToDateTimeNow_VariedCase()
        {
            //---------------Set up test pack-------------------
            PropDef propDef = new PropDef("a", typeof (DateTime), PropReadWriteRule.ReadWrite, null);
            const string dateTimeString = "NoW";
            DateTimeNow dateTimeToday = new DateTimeNow();

            //---------------Execute Test ----------------------
            object convertedDateTimeValue;
            bool parsed = propDef.TryParsePropValue(dateTimeString, out convertedDateTimeValue);

            //---------------Test Result -----------------------
            Assert.IsTrue(parsed); 
            Assert.IsInstanceOf(typeof(DateTimeNow), convertedDateTimeValue);
            Assert.AreEqual(dateTimeToday.ToString(), convertedDateTimeValue.ToString());
        }
 public async Task <IViewComponentResult> InvokeAsync(Models.Patient currentPatient)
 {
     ViewBag.AerobicFunction = new AerobicFunction(currentPatient);
     return(View(await ActivityController.Read(currentPatient.Id, DateTimeNow.ToString(italianDateFormat), "1d")));
 }
Beispiel #10
0
        //Download Bing wallpaper
        async Task DownloadBingWallpaper()
        {
            try
            {
                Debug.WriteLine("Downloading Bing update.");

                //Check for internet connection
                if (!DownloadInternetCheck())
                {
                    BackgroundStatusUpdateSettings(null, null, "Never", null, "NoWifiEthernet"); return;
                }

                //Load and set Download Information
                string DownloadBingRegion = "en-US";
                switch (setDownloadBingRegion)
                {
                case 0: { DownloadBingRegion = vCultureInfoReg.Name; break; }

                case 2: { DownloadBingRegion = "en-GB"; break; }

                case 3: { DownloadBingRegion = "en-AU"; break; }

                case 4: { DownloadBingRegion = "de-DE"; break; }

                case 5: { DownloadBingRegion = "en-CA"; break; }

                case 6: { DownloadBingRegion = "ja-JP"; break; }

                case 7: { DownloadBingRegion = "zh-CN"; break; }

                case 8: { DownloadBingRegion = "fr-FR"; break; }

                case 9: { DownloadBingRegion = "pt-BR"; break; }

                case 10: { DownloadBingRegion = "nz-NZ"; break; }
                }
                string DownloadBingResolution = "1920x1080";
                switch (setDownloadBingResolution)
                {
                case 1: { DownloadBingResolution = "1280x720"; break; }

                case 2: { DownloadBingResolution = "1080x1920"; break; }

                case 3: { DownloadBingResolution = "720x1280"; break; }

                case 4: { DownloadBingResolution = "1024x768"; break; }
                }

                //Download and read Bing Wallpaper XML
                XDocument XDocumentBing = XDocument.Parse(await AVDownloader.DownloadStringAsync(5000, "TimeMe", null, new Uri("https://www.bing.com/HPImageArchive.aspx?format=xml&n=1&mkt=" + DownloadBingRegion)));

                //Read and check current Bing wallpaper
                XElement XElement        = XDocumentBing.Descendants("image").First();
                string   BingUrlName     = XElement.Element("urlBase").Value + "_" + DownloadBingResolution + ".jpg";
                string   BingDescription = XElement.Element("copyright").Value;
                if (BgStatusBingDescription != BingDescription)
                {
                    //Download and Save Bing Wallpaper image
                    IBuffer BingWallpaperFile = await AVDownloader.DownloadBufferAsync(5000, "TimeMe", new Uri("https://www.bing.com" + BingUrlName));

                    if (BingWallpaperFile != null)
                    {
                        //Save the Bing wallpaper image
                        StorageFile BingSaveFile = await AVFile.SaveBuffer("TimeMeTilePhoto.png" + new String(' ', new Random().Next(1, 50)), BingWallpaperFile);

                        //Set background photo as device wallpaper
                        try
                        {
                            if (setDeviceWallpaper)
                            {
                                await UserProfilePersonalizationSettings.Current.TrySetWallpaperImageAsync(BingSaveFile);
                            }
                        }
                        catch { Debug.WriteLine("Failed to update Device wallpaper."); }

                        //Set background photo as lockscreen wallpaper
                        try
                        {
                            if (setLockWallpaper)
                            {
                                if (setDevStatusMobile)
                                {
                                    await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Tiles/TimeMeTileColor.png")));
                                }
                                await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(BingSaveFile);
                            }
                        }
                        catch { Debug.WriteLine("Failed to update Lock screen wallpaper."); }

                        //Save Bing photo name
                        BgStatusPhotoName = BingUrlName;
                        vApplicationSettings["BgStatusPhotoName"] = BgStatusPhotoName;

                        //Save Bing description status
                        BgStatusBingDescription = BingDescription;
                        vApplicationSettings["BgStatusBingDescription"] = BgStatusBingDescription;

                        //Notification - Bing description
                        ShowNotiBingDescription();

                        //Force live tile update
                        TileLive_ForceUpdate = true;
                    }
                    else
                    {
                        Debug.WriteLine("Failed downloading the Bing wallpaper.");
                        BackgroundStatusUpdateSettings(null, null, "Never", null, "FailedDownloadBingWallpaper");
                        return;
                    }
                }

                //Save Bing update status
                BgStatusDownloadBing = DateTimeNow.ToString(vCultureInfoEng);
                vApplicationSettings["BgStatusDownloadBing"] = BgStatusDownloadBing;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed updating the Bing wallpaper.");
                BackgroundStatusUpdateSettings(null, null, "Never", null, "CatchDownloadBingWallpaper" + ex.Message);
            }
        }
Beispiel #11
0
        //Plan and render future live tiles
        async Task PlanLiveTiles()
        {
            try
            {
                //Show render start debug message
                if (setAppDebug)
                {
                    Tile_XmlContent.LoadXml("<toast><visual><binding template=\"ToastText02\"><text id=\"1\">Renderstart: " + taskInstanceName + "</text><text id=\"2\">" + DateTimeNow.ToString() + "</text></binding></visual><audio silent=\"true\"/></toast>");
                    Toast_UpdateManager.Show(new ToastNotification(Tile_XmlContent)
                    {
                        SuppressPopup = true, Tag = "T1", Group = "G3"
                    });
                }

                //Remove old planned live tiles
                Debug.WriteLine("Removing " + Tile_PlannedUpdates.Count + " older live task updates.");
                foreach (ScheduledTileNotification Tile_Update in Tile_PlannedUpdates)
                {
                    try { Tile_UpdateManager.RemoveFromSchedule(Tile_Update); } catch { }
                }

                //Render future live tile back
                if (TileLive_BackRender)
                {
                    Debug.WriteLine("Started rendering back live tile.");
                    await RenderLiveTileBack();
                }

                //Render future live tiles front
                Debug.WriteLine("Started rendering front live tiles.");
                TileTimeNow = DateTime.Now;
                TileTimeMin = TileTimeNow.AddSeconds(-TileTimeNow.Second).AddMinutes(-1);
                for (int LiveTileRenderId = 0; LiveTileRenderId < 18; LiveTileRenderId++)
                {
                    try
                    {
                        TileTimeNow    = DateTime.Now;
                        TileTimeMin    = TileTimeMin.AddMinutes(1);
                        TileContentId  = TileTimeMin.Minute.ToString();
                        TileRenderName = LiveTileRenderId.ToString();

                        if (TileTimeNow.Minute == TileTimeMin.Minute)
                        {
                            Tile_UpdateManager.Update(new TileNotification(await RenderLiveTile()));
                        }
                        else
                        {
                            Tile_UpdateManager.AddToSchedule(new ScheduledTileNotification(await RenderLiveTile(), new DateTimeOffset(TileTimeMin)));
                        }
                        if (TileLive_BackRender)
                        {
                            Tile_XmlContent.LoadXml("<tile><visual contentId=\"" + TileContentId + "\" branding=\"none\"><binding template=\"TileSquareImage\"><image id=\"1\" src=\"ms-appx:///Assets/Tiles/SquareLogoSize.png\"/></binding><binding template=\"TileWideImage\"><image id=\"1\" src=\"ms-appdata:///local/TimeMeBack.png\"/></binding></visual></tile>");
                            if (TileTimeNow < TileTimeMin.AddSeconds(12))
                            {
                                Tile_UpdateManager.AddToSchedule(new ScheduledTileNotification(Tile_XmlContent, new DateTimeOffset(TileTimeMin.AddSeconds(12))));
                            }
                            if (TileTimeNow < TileTimeMin.AddSeconds(32))
                            {
                                Tile_UpdateManager.AddToSchedule(new ScheduledTileNotification(Tile_XmlContent, new DateTimeOffset(TileTimeMin.AddSeconds(32))));
                            }
                            if (TileTimeNow < TileTimeMin.AddSeconds(52))
                            {
                                Tile_UpdateManager.AddToSchedule(new ScheduledTileNotification(Tile_XmlContent, new DateTimeOffset(TileTimeMin.AddSeconds(52))));
                            }
                            Tile_XmlContent.LoadXml("<tile><visual contentId=\"" + TileContentId + "\" branding=\"none\"><binding template=\"TileSquareImage\"><image id=\"1\" src=\"ms-appx:///Assets/Tiles/SquareLogoSize.png\"/></binding><binding template=\"TileWideImage\"><image id=\"1\" src=\"ms-appdata:///local/TimeMe" + TileRenderName + ".png\"/></binding></visual></tile>");
                            if (TileTimeNow < TileTimeMin.AddSeconds(20))
                            {
                                Tile_UpdateManager.AddToSchedule(new ScheduledTileNotification(Tile_XmlContent, new DateTimeOffset(TileTimeMin.AddSeconds(20))));
                            }
                            if (TileTimeNow < TileTimeMin.AddSeconds(40))
                            {
                                Tile_UpdateManager.AddToSchedule(new ScheduledTileNotification(Tile_XmlContent, new DateTimeOffset(TileTimeMin.AddSeconds(40))));
                            }
                        }

                        //Show live tile render debug message
                        if (setAppDebug)
                        {
                            Tile_XmlContent.LoadXml("<toast><visual><binding template=\"ToastText02\"><text id=\"1\">Renderedtile: " + taskInstanceName + "</text><text id=\"2\">" + TileRenderName + "/17 at " + DateTimeNow.ToString() + " Mem " + (MemoryManager.AppMemoryUsage / 1024f / 1024f).ToString() + "</text></binding></visual><audio silent=\"true\"/></toast>");
                            Toast_UpdateManager.Show(new ToastNotification(Tile_XmlContent)
                            {
                                SuppressPopup = true, Tag = "T2", Group = "G3"
                            });
                        }
                    }
                    catch { }
                }

                ////Add tile will be updated shortly on the end
                //Tile_DateTimeMin = Tile_DateTimeMin.AddMinutes(1);
                //Tile_XmlContent.LoadXml("<tile><visual contentId=\"" + TileContentId + "\" branding=\"none\"><binding template=\"TileSquareImage\"><image id=\"1\" src=\"ms-appx:///Assets/Tiles/SquareLogoUpdate.png\"/></binding><binding template=\"TileWideImage\"><image id=\"1\" src=\"ms-appx:///Assets/Tiles/WideLogoUpdate.png\"/></binding></visual></tile>");
                //Tile_UpdateManager.AddToSchedule(new ScheduledTileNotification(Tile_XmlContent, new DateTimeOffset(Tile_DateTimeMin)));

                Debug.WriteLine("Finished rendering live tiles batch.");
            }
            catch { Debug.WriteLine("Failed rendering live tiles batch."); }
        }
Beispiel #12
0
        //Download location
        async Task <bool> DownloadLocation()
        {
            try
            {
                Debug.WriteLine("Downloading Location update.");

                //Check for internet connection
                if (!DownloadInternetCheck())
                {
                    BackgroundStatusUpdateSettings(null, "Never", null, null, "NoWifiEthernet");
                    return(false);
                }

                //Load and set current GPS location
                if (setWeatherGpsLocation)
                {
                    try
                    {
                        //Get current GPS position from geolocator
                        Geolocator Geolocator = new Geolocator();
                        Geolocator.DesiredAccuracy = PositionAccuracy.Default;
                        Geoposition ResGeoposition = await Geolocator.GetGeopositionAsync(TimeSpan.FromMinutes(setBackgroundDownloadIntervalMin), TimeSpan.FromSeconds(6));

                        DownloadWeatherLocation = ResGeoposition.Coordinate.Point.Position.Latitude.ToString().Replace(",", ".") + "," + ResGeoposition.Coordinate.Point.Position.Longitude.ToString().Replace(",", ".");
                    }
                    catch { DownloadGpsUpdateFailed = true; }
                }
                else
                {
                    if (String.IsNullOrEmpty(setWeatherNonGpsLocation))
                    {
                        DownloadGpsUpdateFailed = true;
                    }
                    else
                    {
                        DownloadWeatherLocation = setWeatherNonGpsLocation;
                    }
                }

                //Load and set manual location
                if (DownloadGpsUpdateFailed)
                {
                    string PreviousLocation = BgStatusWeatherCurrentLocationFull.Replace("!", "");
                    if (PreviousLocation != "N/A" && !String.IsNullOrEmpty(PreviousLocation))
                    {
                        DownloadWeatherLocation = PreviousLocation;
                    }
                    else
                    {
                        Debug.WriteLine("Failed no previous location has been set.");
                        BackgroundStatusUpdateSettings(null, "Failed", null, null, "GpsPrevUpdateFailed");
                        return(false);
                    }
                }

                //Download and save the weather location
                string LocationResult = await AVDownloader.DownloadStringAsync(5000, "TimeMe", null, new Uri("https://service.weather.microsoft.com/" + DownloadWeatherLanguage + "/locations/search/" + DownloadWeatherLocation + DownloadWeatherUnits));

                //Check if there is location data available
                JObject LocationJObject = JObject.Parse(LocationResult);
                if (LocationJObject["responses"][0]["locations"] == null || !LocationJObject["responses"][0]["locations"].Any())
                {
                    Debug.WriteLine("Failed no overall info for location found.");
                    BackgroundStatusUpdateSettings(null, "Failed", null, null, "GpsNoLocationOverall");
                    return(false);
                }
                else
                {
                    JToken HttpJTokenGeo = LocationJObject["responses"][0]["locations"][0];

                    //Set current location coords
                    if (HttpJTokenGeo["coordinates"]["lat"] != null && HttpJTokenGeo["coordinates"]["lon"] != null)
                    {
                        DownloadWeatherLocation = HttpJTokenGeo["coordinates"]["lat"].ToString().Replace(",", ".") + "," + HttpJTokenGeo["coordinates"]["lon"].ToString().Replace(",", ".");
                    }
                    else
                    {
                        if (!setWeatherGpsLocation || DownloadGpsUpdateFailed)
                        {
                            Debug.WriteLine("Failed no gps coords for location found.");
                            BackgroundStatusUpdateSettings(null, "Failed", null, null, "GpsNoLocationCoords");
                            return(false);
                        }
                    }

                    //Set weather current location
                    if (HttpJTokenGeo["displayName"] != null)
                    {
                        string LocationName = HttpJTokenGeo["displayName"].ToString();
                        if (!String.IsNullOrEmpty(LocationName))
                        {
                            BgStatusWeatherCurrentLocationFull = LocationName;
                            vApplicationSettings["BgStatusWeatherCurrentLocationFull"] = BgStatusWeatherCurrentLocationFull;

                            if (LocationName.Contains(","))
                            {
                                LocationName = LocationName.Split(',')[0];
                            }
                            BgStatusWeatherCurrentLocation = LocationName;
                            vApplicationSettings["BgStatusWeatherCurrentLocation"] = BgStatusWeatherCurrentLocation;
                        }
                        else
                        {
                            Debug.WriteLine("Failed empty location name found.");
                            BackgroundStatusUpdateSettings(null, "Failed", null, null, "NoLocationNameEmpty");
                            return(false);
                        }
                    }
                    else
                    {
                        Debug.WriteLine("Failed no location name found.");
                        BackgroundStatusUpdateSettings(null, "Failed", null, null, "NoLocationNameFound");
                        return(false);
                    }
                }

                //Save Location status
                BgStatusDownloadLocation = DateTimeNow.ToString(vCultureInfoEng);
                vApplicationSettings["BgStatusDownloadLocation"] = BgStatusDownloadLocation;
                return(true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed updating the location info.");
                BackgroundStatusUpdateSettings(null, "Failed", null, null, "CatchDownloadLocation" + ex.Message);
                return(false);
            }
        }
Beispiel #13
0
        public void Test_ToString()
        {
            //---------------Set up test pack-------------------
            DateTimeNow dteNow = new DateTimeNow();
            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            string toString = dteNow.ToString();
            //---------------Test Result -----------------------
            DateTime dteParsedDateTime;
            Assert.IsTrue(DateTime.TryParse(toString, out dteParsedDateTime));
//            Assert.IsTrue(dteNow == dteParsedDateTime);
            Assert.AreEqual(toString, dteParsedDateTime.ToString());
        }
Beispiel #14
0
        //Download weather and forecast
        async Task DownloadWeather()
        {
            try
            {
                Debug.WriteLine("Downloading Weather update.");

                //Check for internet connection
                if (!DownloadInternetCheck())
                {
                    BackgroundStatusUpdateSettings("Never", null, null, null, "NoWifiEthernet");
                    return;
                }

                //Check if location is available
                if (String.IsNullOrEmpty(DownloadWeatherLocation))
                {
                    BackgroundStatusUpdateSettings("Never", null, null, null, "NoWeatherLocation");
                    return;
                }

                //Download and save weather summary
                string WeatherSummaryResult = await AVDownloader.DownloadStringAsync(5000, "TimeMe", null, new Uri("https://service.weather.microsoft.com/" + DownloadWeatherLanguage + "/weather/summary/" + DownloadWeatherLocation + DownloadWeatherUnits));

                if (!String.IsNullOrEmpty(WeatherSummaryResult))
                {
                    //Update weather summary status
                    UpdateWeatherSummaryStatus(WeatherSummaryResult);

                    //Notification - Current Weather
                    ShowNotiWeatherCurrent();

                    //Save weather summary data
                    await AVFile.SaveText("TimeMeWeatherSummary.js", WeatherSummaryResult);
                }
                else
                {
                    Debug.WriteLine("Failed no weather summary found.");
                    BackgroundStatusUpdateSettings("Failed", null, null, null, "NoWeatherSummary");
                    return;
                }

                //Download and save weather forecast
                string WeatherForecastResult = await AVDownloader.DownloadStringAsync(5000, "TimeMe", null, new Uri("https://service.weather.microsoft.com/" + DownloadWeatherLanguage + "/weather/forecast/daily/" + DownloadWeatherLocation + DownloadWeatherUnits));

                if (!String.IsNullOrEmpty(WeatherForecastResult))
                {
                    //Save weather forecast data
                    await AVFile.SaveText("TimeMeWeatherForecast.js", WeatherForecastResult);
                }
                else
                {
                    Debug.WriteLine("Failed no weather forecast found.");
                    BackgroundStatusUpdateSettings("Failed", null, null, null, "NoWeatherForecast");
                    return;
                }

                //Save Weather status
                BgStatusDownloadWeather = DateTimeNow.ToString(vCultureInfoEng);
                vApplicationSettings["BgStatusDownloadWeather"] = BgStatusDownloadWeather;
                BgStatusDownloadWeatherTime = BgStatusDownloadWeather;
                vApplicationSettings["BgStatusDownloadWeatherTime"] = BgStatusDownloadWeather;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed updating the weather info.");
                BackgroundStatusUpdateSettings("Failed", null, null, null, "CatchDownloadWeather" + ex.Message);
            }

            //Update weather summary status
            void UpdateWeatherSummaryStatus(string WeatherSummaryResult)
            {
                try
                {
                    //Check if there is summary data available
                    JObject SummaryJObject = JObject.Parse(WeatherSummaryResult);
                    if (SummaryJObject["responses"][0]["weather"] != null)
                    {
                        //Set Weather Provider Information
                        JToken HttpJTokenProvider = SummaryJObject["responses"][0]["weather"][0]["provider"];
                        if (HttpJTokenProvider["name"] != null)
                        {
                            string Provider = HttpJTokenProvider["name"].ToString();
                            if (!String.IsNullOrEmpty(Provider))
                            {
                                BgStatusWeatherProvider = Provider; vApplicationSettings["BgStatusWeatherProvider"] = BgStatusWeatherProvider;
                            }
                            else
                            {
                                BgStatusWeatherProvider = "N/A"; vApplicationSettings["BgStatusWeatherProvider"] = BgStatusWeatherProvider;
                            }
                        }

                        //Set Weather Current Conditions
                        string Icon               = "";
                        string Condition          = "";
                        string Temperature        = "";
                        string WindSpeedDirection = "";
                        JToken UnitsJToken        = SummaryJObject["units"];
                        JToken HttpJTokenCurrent  = SummaryJObject["responses"][0]["weather"][0]["current"];
                        if (HttpJTokenCurrent["icon"] != null)
                        {
                            Icon = HttpJTokenCurrent["icon"].ToString();
                        }
                        if (HttpJTokenCurrent["cap"] != null)
                        {
                            Condition = HttpJTokenCurrent["cap"].ToString();
                        }
                        if (HttpJTokenCurrent["temp"] != null)
                        {
                            Temperature = HttpJTokenCurrent["temp"].ToString() + "°";
                        }
                        if (HttpJTokenCurrent["windSpd"] != null && HttpJTokenCurrent["windDir"] != null)
                        {
                            WindSpeedDirection = HttpJTokenCurrent["windSpd"].ToString() + " " + UnitsJToken["speed"].ToString() + " " + AVFunctions.DegreesToCardinal(Convert.ToDouble((HttpJTokenCurrent["windDir"].ToString())));
                        }

                        //Set Weather Forecast Conditions
                        string RainChance         = "";
                        string TemperatureLow     = "";
                        string TemperatureHigh    = "";
                        JToken HttpJTokenForecast = SummaryJObject["responses"][0]["weather"][0]["forecast"]["days"][0];
                        if (HttpJTokenForecast["precip"] != null)
                        {
                            RainChance = HttpJTokenForecast["precip"].ToString() + "%";
                        }
                        if (HttpJTokenForecast["tempLo"] != null)
                        {
                            TemperatureLow = HttpJTokenForecast["tempLo"].ToString() + "°";
                        }
                        if (HttpJTokenForecast["tempHi"] != null)
                        {
                            TemperatureHigh = HttpJTokenForecast["tempHi"].ToString() + "°";
                        }

                        //Set Weather Icon
                        if (!String.IsNullOrEmpty(Icon))
                        {
                            BgStatusWeatherCurrentIcon = Icon;
                            vApplicationSettings["BgStatusWeatherCurrentIcon"] = BgStatusWeatherCurrentIcon;
                        }
                        else
                        {
                            BgStatusWeatherCurrentIcon = "0";
                            vApplicationSettings["BgStatusWeatherCurrentIcon"] = BgStatusWeatherCurrentIcon;
                        }

                        //Set Weather Temperature and Condition
                        if (!String.IsNullOrEmpty(Temperature) && !String.IsNullOrEmpty(Condition))
                        {
                            BgStatusWeatherCurrent = AVFunctions.ToTitleCase(Condition) + ", " + Temperature;
                            vApplicationSettings["BgStatusWeatherCurrent"] = BgStatusWeatherCurrent;
                        }
                        else
                        {
                            BgStatusWeatherCurrent = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrent"] = BgStatusWeatherCurrent;
                        }

                        //Set Weather Temperature
                        if (!String.IsNullOrEmpty(Temperature))
                        {
                            BgStatusWeatherCurrentTemp = Temperature;
                            vApplicationSettings["BgStatusWeatherCurrentTemp"] = BgStatusWeatherCurrentTemp;
                        }
                        else
                        {
                            BgStatusWeatherCurrentTemp = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentTemp"] = BgStatusWeatherCurrentTemp;
                        }

                        //Set Weather Condition
                        if (!String.IsNullOrEmpty(Condition))
                        {
                            BgStatusWeatherCurrentText = AVFunctions.ToTitleCase(Condition);
                            vApplicationSettings["BgStatusWeatherCurrentText"] = BgStatusWeatherCurrentText;
                        }
                        else
                        {
                            BgStatusWeatherCurrentText = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentText"] = BgStatusWeatherCurrentText;
                        }

                        //Set Weather Wind Speed and Direction
                        if (!String.IsNullOrEmpty(WindSpeedDirection))
                        {
                            BgStatusWeatherCurrentWindSpeed = WindSpeedDirection;
                            vApplicationSettings["BgStatusWeatherCurrentWindSpeed"] = BgStatusWeatherCurrentWindSpeed;
                        }
                        else
                        {
                            BgStatusWeatherCurrentWindSpeed = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentWindSpeed"] = BgStatusWeatherCurrentWindSpeed;
                        }

                        //Set Weather Rain Chance
                        if (!String.IsNullOrEmpty(RainChance))
                        {
                            BgStatusWeatherCurrentRainChance = RainChance;
                            vApplicationSettings["BgStatusWeatherCurrentRainChance"] = BgStatusWeatherCurrentRainChance;
                        }
                        else
                        {
                            BgStatusWeatherCurrentRainChance = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentRainChance"] = BgStatusWeatherCurrentRainChance;
                        }

                        //Set Weather Temp Low
                        if (!String.IsNullOrEmpty(TemperatureLow))
                        {
                            BgStatusWeatherCurrentTempLow = TemperatureLow;
                            vApplicationSettings["BgStatusWeatherCurrentTempLow"] = BgStatusWeatherCurrentTempLow;
                        }
                        else
                        {
                            BgStatusWeatherCurrentTempLow = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentTempLow"] = BgStatusWeatherCurrentTempLow;
                        }

                        //Set Weather Temp High
                        if (!String.IsNullOrEmpty(TemperatureHigh))
                        {
                            BgStatusWeatherCurrentTempHigh = TemperatureHigh;
                            vApplicationSettings["BgStatusWeatherCurrentTempHigh"] = BgStatusWeatherCurrentTempHigh;
                        }
                        else
                        {
                            BgStatusWeatherCurrentTempHigh = "N/A";
                            vApplicationSettings["BgStatusWeatherCurrentTempHigh"] = BgStatusWeatherCurrentTempHigh;
                        }
                    }
                }
                catch { }
            }
        }
Beispiel #15
0
        //Run Task Agent Update
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                //Set current background task info
                taskInstanceDeferral   = taskInstance.GetDeferral();
                taskInstance.Canceled += delegate { DisposeVariables(); taskInstance.Progress = 100; taskInstanceDeferral.Complete(); return; };
                taskInstanceName       = taskInstance.Task.Name;

                //Load tile and application settings
                taskInstance.Progress = 90;
                if (!LoadAppSettings())
                {
                    if (TileLive_Pinned)
                    {
                        RenderTileAppUpdated("TimeMeLiveTile");
                    }
                    if (TileWeather_Pinned)
                    {
                        RenderTileAppUpdated("TimeMeWeatherTile");
                    }
                    if (TileBattery_Pinned)
                    {
                        RenderTileAppUpdated("TimeMeBatteryTile");
                    }
                    DisposeVariables();
                    taskInstance.Progress = 100;
                    taskInstanceDeferral.Complete();
                    return;
                }

                //Show task start debug message
                if (setAppDebug)
                {
                    Tile_XmlContent.LoadXml("<toast><visual><binding template=\"ToastText02\"><text id=\"1\">Taskstart: " + taskInstanceName + "</text><text id=\"2\">" + DateTimeNow.ToString() + "</text></binding></visual><audio silent=\"true\"/></toast>");
                    Toast_UpdateManager.Show(new ToastNotification(Tile_XmlContent)
                    {
                        SuppressPopup = true, Tag = "T3", Group = "G3"
                    });
                }

                //Load other used data first
                if (!await LoadOtherDataFirst())
                {
                    if (TileLive_Pinned)
                    {
                        RenderTileLiveFailed("TimeMeLiveTile");
                    }
                    if (TileWeather_Pinned)
                    {
                        RenderTileLiveFailed("TimeMeWeatherTile");
                    }
                    if (TileBattery_Pinned)
                    {
                        RenderTileLiveFailed("TimeMeBatteryTile");
                    }
                    DisposeVariables();
                    taskInstance.Progress = 100;
                    taskInstanceDeferral.Complete();
                    return;
                }

                //Download the background updates
                taskInstance.Progress = 10;
                await DownloadBackground();

                //Update the lockscreen information
                taskInstance.Progress = 20;
                UpdateLockscreen();

                //Check if weather tile is pinned
                if (TileWeather_Pinned)
                {
                    taskInstance.Progress = 40;
                    Tile_UpdateManager    = TileUpdateManager.CreateTileUpdaterForSecondaryTile("TimeMeWeatherTile");
                    Tile_UpdateManager.EnableNotificationQueue(false);
                    Tile_PlannedUpdates = Tile_UpdateManager.GetScheduledTileNotifications();
                    if (await LoadTileDataWeather())
                    {
                        RenderWeatherTile();
                    }
                    else
                    {
                        RenderTileWeatherDisabled();
                    }
                }

                //Check if battery tile is pinned
                if (TileBattery_Pinned)
                {
                    taskInstance.Progress = 50;
                    Tile_UpdateManager    = TileUpdateManager.CreateTileUpdaterForSecondaryTile("TimeMeBatteryTile");
                    Tile_UpdateManager.EnableNotificationQueue(false);
                    Tile_PlannedUpdates = Tile_UpdateManager.GetScheduledTileNotifications();
                    if (await LoadTileDataBattery())
                    {
                        RenderBatteryTile();
                    }
                    else
                    {
                        RenderTileBatteryDisabled();
                    }
                }

                //Check if live tile is pinned
                if (TileLive_Pinned)
                {
                    taskInstance.Progress = 30;
                    Tile_UpdateManager    = TileUpdateManager.CreateTileUpdaterForSecondaryTile("TimeMeLiveTile");
                    Tile_UpdateManager.EnableNotificationQueue(false);
                    Tile_PlannedUpdates = Tile_UpdateManager.GetScheduledTileNotifications();

                    //Delay timer task to avoid collision
                    //if (TaskInstanceName.StartsWith("TimeMeTaskTimer")) { await Task.Delay(1000); }

                    //Check if there is a live tile update needed
                    if (!FreshDeviceBoot && !TileLive_ForceUpdate && taskInstanceName != "TimeMeTaskTimeZone" && BgStatusLastRunDate != "Never" && Tile_PlannedUpdates.Any())
                    {
                        //Check if the live tile has failed to update
                        if (Tile_PlannedUpdates.Last().DeliveryTime.Subtract(DateTime.Parse(BgStatusLastRunDate, vCultureInfoEng)).TotalMilliseconds <= 960000)
                        {
                            Debug.WriteLine("Live tile has failed to render succesfully.");
                        }
                        else
                        {
                            if (taskInstanceName == "TimeMeTaskUser")
                            {
                                Debug.WriteLine("There is no user live tile update needed."); TileLive_NeedUpdate = false;
                            }
                            else if (taskInstanceName == "TimeMeTaskTimer" && Tile_PlannedUpdates.Last().DeliveryTime.Subtract(DateTimeNow).TotalMilliseconds >= 960000)
                            {
                                Debug.WriteLine("There is no timer live tile update needed."); TileLive_NeedUpdate = false;
                            }
                        }
                    }

                    //Update the live tile if needed
                    if (TileLive_NeedUpdate)
                    {
                        //Load first one time live tile data
                        if (await LoadTileDataFirst())
                        {
                            //Plan and render future live tiles
                            await PlanLiveTiles();
                        }
                        else
                        {
                            RenderTileLiveFailed("TimeMeLiveTile");
                        }
                    }
                }
            }
            catch { }
            DisposeVariables();
            taskInstance.Progress = 100;
            taskInstanceDeferral.Complete();
            return;
        }