public void Test_IResolvableToValue() { //---------------Set up test pack------------------- //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- DateTimeNow dateTimeNow = new DateTimeNow(); //---------------Test Result ----------------------- TestUtil.AssertIsInstanceOf<IResolvableToValue>(dateTimeNow); }
public async Task <IActionResult> Login(UserForLoginDto userForLoginDto) { var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password); if (userFromRepo == null) { return(UnAuthorized()); } var claims = new[] { new claim(ClaimTypes, userFromRepo.Id.ToString()), new claim(ClaimTypes, userFromRepo.Username) }; var key = new SymmetricSecurityKey(Encoding.UTF8 .GetBytes(_config.GetSection("AppSettings:Token").value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(CLaims), Expires = DateTimeNow.AddDays(1), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return(Ok(new { token = tokenHandler.WriteToken(token) })); }
private static AppSummary BuildAppSummary() { var dateTimeprovider = new DateTimeNow(); var logger = BuildLogger(); var summary = new AppSummary(dateTimeprovider, logger); return(summary); }
//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 { } }
public void Test_IResolvableToValue() { //---------------Set up test pack------------------- //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- DateTimeNow dateTimeNow = new DateTimeNow(); //---------------Test Result ----------------------- TestUtil.AssertIsInstanceOf <IResolvableToValue>(dateTimeNow); }
static void Main(string[] args) { IDateTimeNow dateTimeNow = new DateTimeNow(); IProductsMonitorService _productsMonitorService = new ProductsMonitorService(dateTimeNow); _productsMonitorService.Monitor(); Console.ReadKey(); }
public void Test_Equals_WithDateTimeValue_ShouldReturnFalse() { //-------------Setup Test Pack ------------------ DateTimeNow dateTimeNow = new DateTimeNow(); DateTime dateTime2 = DateTime.Now; //-------------Execute test --------------------- bool result = dateTimeNow.Equals(dateTime2); //-------------Test Result ---------------------- Assert.IsFalse(result); }
public void Test_Equals_WithDateTimeNowType_ShouldReturnTrue() { //-------------Setup Test Pack ------------------ DateTimeNow dateTimeNow = new DateTimeNow(); DateTimeNow dateTimeNow2 = new DateTimeNow(); //-------------Execute test --------------------- bool result = dateTimeNow.Equals(dateTimeNow2); //-------------Test Result ---------------------- Assert.IsTrue(result); }
public void Test_Equals_WithNull_ShouldReturnFalse() { //-------------Setup Test Pack ------------------ DateTimeNow dateTimeNow = new DateTimeNow(); const DateTimeNow dateTimeNow2 = null; //-------------Execute test --------------------- bool result = dateTimeNow.Equals(dateTimeNow2); //-------------Test Result ---------------------- Assert.IsFalse(result); }
public void Test_Comparable_Equals_WithDateTimeNowType() { //-------------Setup Test Pack ------------------ DateTimeNow dateTimeNow = new DateTimeNow(); IComparable comparable = dateTimeNow; //-------------Execute test --------------------- int i = comparable.CompareTo(new DateTimeNow()); //-------------Test Result ---------------------- Assert.AreEqual(0, i); }
public void Test_DataMapper_ParsePropValue_FromDateTimeNowObject() { //---------------Set up test pack------------------- DateTimeNow dateTimeNow = new DateTimeNow(); //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- object parsedValue; bool parseSucceed = _dataMapper.TryParsePropValue(dateTimeNow, out parsedValue); //---------------Test Result ----------------------- Assert.IsTrue(parseSucceed); Assert.AreSame(dateTimeNow, parsedValue); }
public void Test_Comparable_GreaterThan() { //-------------Setup Test Pack ------------------ DateTimeNow dateTimeNow = new DateTimeNow(); IComparable comparable = dateTimeNow; DateTime dateTime = DateTimeNow.Value.AddDays(-1); //-------------Test Pre-conditions -------------- //-------------Execute test --------------------- int i = comparable.CompareTo(dateTime); //-------------Test Result ---------------------- Assert.AreEqual(1, i); }
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); }
public void Test_Comparable_OfDateTime_LessThan() { //-------------Setup Test Pack ------------------ DateTimeNow dateTimeNow = new DateTimeNow(); IComparable <DateTime> comparable = dateTimeNow; //-------------Test Pre-conditions -------------- //-------------Execute test --------------------- int i = comparable.CompareTo(DateTimeNow.Value.AddDays(1)); //-------------Test Result ---------------------- Assert.AreEqual(-1, i); }
/// <summary> /// the time mines some day /// </summary> /// <param name="theDay"> total day you are gonna go back</param> /// <returns>date time </returns> public static DateTimeNow DateNow(int theDay) { DateTimeNow value = new DateTimeNow(); System.Globalization.PersianCalendar pc = new System.Globalization.PersianCalendar(); DateTime specieficDate = DateTime.Now.AddDays(-theDay); string Data = pc.GetYear(specieficDate).ToString() + "-" + pc.GetMonth(specieficDate).ToString().PadLeft(2, '0') + "-" + pc.GetDayOfMonth(specieficDate).ToString().PadLeft(2, '0'); value.Date = Data; value.Time = DateTime.Now.Hour.ToString().PadLeft(2, '0') + ":" + DateTime.Now.Minute.ToString().PadLeft(2, '0') + ":" + DateTime.Now.Second.ToString().PadLeft(2, '0'); return(value); }
public void Test_DefaultTypeConverter_WithDateTime_ShouldReturnNowValue() { //---------------Set up test pack------------------- TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(DateTimeNow)); DateTimeNow dateTimeNow = new DateTimeNow(); DateTime snapshot = DateTime.Now; //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- object result = typeConverter.ConvertTo(dateTimeNow, typeof(DateTime)); //---------------Test Result ----------------------- DateTime dateTime = TestUtil.AssertIsInstanceOf<DateTime>(result); Assert.Greater(dateTime, snapshot.AddSeconds(-1)); Assert.Less(dateTime, snapshot.AddSeconds(1)); }
public void Test_IResolvableToValue_ResolveToValue() { //---------------Set up test pack------------------- DateTimeNow dateTimeNow = new DateTimeNow(); IResolvableToValue resolvableToValue = dateTimeNow; DateTime dateTimeBefore = DateTime.Now; //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- object resolvedValue = resolvableToValue.ResolveToValue(); //---------------Test Result ----------------------- DateTime dateTimeAfter = DateTime.Now; DateTime dateTime = TestUtil.AssertIsInstanceOf<DateTime>(resolvedValue); Assert.GreaterOrEqual(dateTime, dateTimeBefore); Assert.LessOrEqual(dateTime, dateTimeAfter); }
public void Test_DefaultTypeConverter_WithDateTime_ShouldReturnNowValue() { //---------------Set up test pack------------------- TypeConverter typeConverter = TypeDescriptor.GetConverter(typeof(DateTimeNow)); DateTimeNow dateTimeNow = new DateTimeNow(); DateTime snapshot = DateTime.Now; //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- object result = typeConverter.ConvertTo(dateTimeNow, typeof(DateTime)); //---------------Test Result ----------------------- DateTime dateTime = TestUtil.AssertIsInstanceOf <DateTime>(result); Assert.Greater(dateTime, snapshot.AddSeconds(-1)); Assert.Less(dateTime, snapshot.AddSeconds(1)); }
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); }
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 void Test_IResolvableToValue_ResolveToValue() { //---------------Set up test pack------------------- DateTimeNow dateTimeNow = new DateTimeNow(); IResolvableToValue resolvableToValue = dateTimeNow; DateTime dateTimeBefore = DateTime.Now; //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- object resolvedValue = resolvableToValue.ResolveToValue(); //---------------Test Result ----------------------- DateTime dateTimeAfter = DateTime.Now; DateTime dateTime = TestUtil.AssertIsInstanceOf <DateTime>(resolvedValue); Assert.GreaterOrEqual(dateTime, dateTimeBefore); Assert.LessOrEqual(dateTime, dateTimeAfter); }
public static int Main(string[] args) { DateTimeNow now = new DateTimeNow(); TestLibrary.TestFramework.BeginTestCase("Testing System.DateTime.Now property..."); if (now.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 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); }
public static int Main(string[] args) { DateTimeNow now = new DateTimeNow(); TestLibrary.TestFramework.BeginTestCase("Testing System.DateTime.Now property..."); if (now.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return(100); } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return(0); } }
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); }
public void Test_Value_WhenDateTimeNow_ShouldReturnResolvedValue() { //---------------Set up test pack------------------- PropDef propDef = CreateTestPropDateTimePropDef(); ; IBOProp boProp = propDef.CreateBOProp(true); DateTimeNow dateTimeNow = new DateTimeNow(); boProp.Value = dateTimeNow; //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- object value = boProp.Value; //---------------Test Result ----------------------- Assert.IsNotNull(value); Assert.AreNotSame(dateTimeNow, value); }
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)); }
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 void TestConvertValueToPropertyType_DateTimeAcceptsDateTimeNow() { //---------------Set up test pack------------------- PropDef propDef = new PropDef("a", typeof (DateTime), PropReadWriteRule.ReadWrite, null); DateTimeNow dateTimeToday = new DateTimeNow(); //---------------Execute Test ---------------------- object convertedDateTimeValue; bool parsed = propDef.TryParsePropValue(dateTimeToday, out convertedDateTimeValue); //---------------Test Result ----------------------- Assert.IsTrue(parsed); Assert.IsInstanceOf(typeof (DateTimeNow), convertedDateTimeValue); Assert.AreSame(dateTimeToday, convertedDateTimeValue); }
public void Test_Comparable_OfDateTime_LessThan() { //-------------Setup Test Pack ------------------ DateTimeNow dateTimeNow = new DateTimeNow(); IComparable<DateTime> comparable = dateTimeNow; //-------------Test Pre-conditions -------------- //-------------Execute test --------------------- int i = comparable.CompareTo(DateTimeNow.Value.AddDays(1)); //-------------Test Result ---------------------- Assert.AreEqual(-1, i); }
//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 { } } }
//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); } }
///<summary> /// Constructs A DateRangeOptions Converter with a specified DateTimeNow. /// This is primarily used for testing so that a Fake DateTimeNow can be used. ///</summary> public DateRangeOptionsConverter(DateTimeNow dateTimeNow) { if (dateTimeNow == null) throw new ArgumentNullException("dateTimeNow"); _dateTimeNow = dateTimeNow; }
/// <summary> /// Sets a fixed date time to use as now. /// </summary> /// <param name="now">the Fixed DateTime to use as now in all calculations</param> public void SetNow(DateTime now) { _dateTimeNow = new DateTimeNowFixed(now); }
//Download Weather Forecast and Bing Wallpaper async Task DownloadBackground() { try { Debug.WriteLine("Checking if background download is needed."); //Check if background download is enabled if (setBackgroundDownload) { if (setDownloadBingWallpaper && (BgStatusDownloadBing == "Never" || DateTimeNow.Subtract(DateTime.Parse(BgStatusDownloadBing, vCultureInfoEng)).TotalMinutes >= setBackgroundDownloadIntervalMin)) { await DownloadBingWallpaper(); } if (setDownloadWeather && (BgStatusDownloadLocation == "Never" || BgStatusDownloadLocation == "Failed" || BgStatusDownloadWeather == "Never" || BgStatusDownloadWeather == "Failed" || DateTimeNow.Subtract(DateTime.Parse(BgStatusDownloadWeather, vCultureInfoEng)).TotalMinutes >= setBackgroundDownloadIntervalMin)) { //Load and set Download variables if (setFahrenheitCelsius == 1) { DownloadWeatherUnits = "?units=C"; } if (setDisplayRegionLanguage) { DownloadWeatherLanguage = vCultureInfoReg.Name; } //Start downloading weather information bool LocationResult = await DownloadLocation(); if (LocationResult) { await DownloadWeather(); //Force live tile update TileLive_ForceUpdate = true; } } } } catch { } }
//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."); } }
public async Task <IViewComponentResult> InvokeAsync(Models.Patient currentPatient) { ViewBag.AerobicFunction = new AerobicFunction(currentPatient); return(View(await ActivityController.Read(currentPatient.Id, DateTimeNow.ToString(italianDateFormat), "1d"))); }
///<summary> /// Tries to parse a value as an object to a valid DateTimeValue or a resolvable DateTimeValue. /// The valid value may not be a date but could instead return a <see cref="DateTimeToday"/> or <see cref="DateTimeNow"/> etc /// These objects are convertable to DateTime via the <see cref="DateTimeToday.ResolveToValue"/> ///</summary> ///<param name="valueToParse"></param> ///<param name="returnValue"></param> ///<returns>If the value cannot be parsed to a valid date time then returns false else true</returns> public static bool TryParseValue(object valueToParse, out object returnValue) { returnValue = null; if (valueToParse != null && valueToParse is string && ((string)valueToParse).Length == 0) return true; if(valueToParse == null || valueToParse == DBNull.Value) return true; if (!(valueToParse is DateTime)) { if (valueToParse is DateTimeToday || valueToParse is DateTimeNow) { returnValue = valueToParse; return true; } if (valueToParse is String) { string stringValueToConvert = (string)valueToParse; var stringValueToConvertUpperCase = stringValueToConvert.ToUpper(); if (stringValueToConvertUpperCase == "TODAY") { returnValue = new DateTimeToday(); return true; } if (stringValueToConvertUpperCase == "YESTERDAY") { returnValue = new DateTimeToday(); ((DateTimeToday) returnValue).OffSet = -1; return true; } if (stringValueToConvertUpperCase == "TOMORROW") { returnValue = new DateTimeToday(); ((DateTimeToday) returnValue).OffSet = 1; return true; } if (stringValueToConvertUpperCase == "NOW") { returnValue = new DateTimeNow(); return true; } DateTime dtOut; if (DateTime.TryParseExact(stringValueToConvert, StandardDateTimeFormat, _dateTimeFormatProvider, DateTimeStyles.AllowWhiteSpaces, out dtOut)) { returnValue = dtOut; return true; } } DateTime dateTimeOut; string valueToParseAsString = valueToParse.ToString(); if (DateTime.TryParse(valueToParseAsString, out dateTimeOut)) { returnValue = dateTimeOut; return true; } if (DateTime.TryParse(valueToParseAsString, new DateTimeFormatInfo { FullDateTimePattern = "dd/MM/yyyy HH:mm:ss:fff" }, DateTimeStyles.AllowWhiteSpaces, out dateTimeOut)) { returnValue = dateTimeOut; return true; } if (DateTime.TryParse(valueToParseAsString, new DateTimeFormatInfo { FullDateTimePattern = "MM/dd/yyyy HH:mm:ss:fff" }, DateTimeStyles.AllowWhiteSpaces, out dateTimeOut)) { returnValue = dateTimeOut; return true; } return false; } returnValue = valueToParse; return true; }
public void Test_ConvertTo_WithTypeArgument() { //---------------Set up test pack------------------- DateTimeNow dateTimeNow = new DateTimeNow(); DateTime snapshot = DateTime.Now; //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- object returnValue = TypeUtilities.ConvertTo(typeof(DateTime), dateTimeNow); //---------------Test Result ----------------------- DateTime dateTime = TestUtil.AssertIsInstanceOf<DateTime>(returnValue); Assert.Greater(dateTime, snapshot.AddSeconds(-1)); Assert.Less(dateTime, snapshot.AddSeconds(1)); }
public void Test_ConvertTo() { //---------------Set up test pack------------------- DateTimeNow dateTimeNow = new DateTimeNow(); DateTime snapshot = DateTime.Now; //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- DateTime dateTime = TypeUtilities.ConvertTo<DateTime>(dateTimeNow); //---------------Test Result ----------------------- Assert.Greater(dateTime, snapshot.AddSeconds(-1)); Assert.Less(dateTime, snapshot.AddSeconds(1)); }
public void TestIsMatch_DateTimeNow_LessThan_NoMatch() { //---------------Set up test pack------------------- ClassDef.ClassDefs.Clear(); ContactPersonTestBO.LoadDefaultClassDef(); ContactPersonTestBO cp = new ContactPersonTestBO(); cp.Surname = Guid.NewGuid().ToString("N"); DateTimeNow dateTimeNow = new DateTimeNow(); cp.DateOfBirth = DateTime.Today.AddDays(1); //---------------Assert PreConditions--------------- //---------------Execute Test ---------------------- Criteria criteria = new Criteria("DateOfBirth", Criteria.ComparisonOp.LessThan, dateTimeNow); bool isMatch = criteria.IsMatch(cp); //---------------Test Result ----------------------- Assert.IsFalse(isMatch, "The object should not be a match since it does not match the criteria given."); //---------------Tear Down ------------------------- }
//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); } }