public override void OnBind(MessageData message) { if (time != null) { time.Text = DateFormatter.Format(message.CreatedAt, DateFormatter.Template.TIME); } }
public async Task <IActionResult> CreateRole([FromBody] SecRoles model) { if (ModelState.IsValid) { try { //model.CreatedOn = DateTime.Now; model.CreatedOn = DateFormatter.ConvertStringToDate(DateTime.Now.ToString("dd/MM/yyyy")); var roleId = await _roleService.CreateRole(model); if (roleId > 0) { return(Ok(roleId)); } else { return(NotFound()); } } catch (Exception ex) { Console.WriteLine("Some Error AAcquired: " + ex.StackTrace); return(BadRequest()); } } return(BadRequest()); }
private void generateDateHeaders(IList <MessageData> messages) { for (int i = 0; i < messages.Count; i++) { MessageData message = messages[i]; this.items.Add(new Wrapper(this, message)); if (messages.Count > i + 1) { MessageData nextMessage = messages[i + 1]; if (!DateFormatter.IsSameDay(message.CreatedAt, nextMessage.CreatedAt)) { var dateMessage = new MessageData { CreatedAt = message.CreatedAt, Type = MessageData.DataType.Date }; this.items.Add(new Wrapper(this, dateMessage)); } } else { var dateMessage = new MessageData { CreatedAt = message.CreatedAt, Type = MessageData.DataType.Date }; this.items.Add(new Wrapper(this, dateMessage)); } } }
private void PopulateModel(UserModel userModel, UserEntity user, UserProfileEntity userProfile) { userModel.Religions = SelectListGenerator.GetSelectedReligions(userProfile); userModel.Statuses = SelectListGenerator.GetSelectedStatuses(userProfile); userModel.Orientations = SelectListGenerator.GetSelectedOrientations(userProfile); userModel.Genders = SelectListGenerator.GetSelectedGenders(userProfile); userModel.Email = user.UserEmail; userModel.UserName = user.UserUsername; userModel.Description = string.IsNullOrWhiteSpace(userProfile.UserProfileDescription) ? "" : userProfile.UserProfileDescription; userModel.Phone = string.IsNullOrWhiteSpace(userProfile.UserProfilePhone) ? "" : userProfile.UserProfilePhone; userModel.Job = string.IsNullOrWhiteSpace(userProfile.UserProfileJob) ? "" : userProfile.UserProfileJob; userModel.Name = userProfile.UserProfileName; userModel.Surname = userProfile.UserProfileSurname; userModel.ReligionId = userProfile.ReligionId; userModel.StatusId = userProfile.StatusId; userModel.OrientationId = userProfile.OrientationId; userModel.GenderId = userProfile.GenderId; userModel.Age = AgeCalculator.GetDifferenceInYears(userProfile.UserProfileBirthday, DateTime.Now); userModel.Birthday = userProfile.UserProfileBirthday; userModel.BirthdayString = DateFormatter.GetDate(userProfile.UserProfileBirthday); userModel.Starsign = StarsignCalculator.GetStarsignName(userProfile.UserProfileBirthday); userModel.Motto = string.IsNullOrWhiteSpace(userProfile.Motto) ? "" : userProfile.Motto; var prefHandler = new PreferenceHandler(); userModel.LikesList = prefHandler.GetAllForUserProfile(userProfile.UserProfileId, true).Entity.ToList(); userModel.DislikesList = prefHandler.GetAllForUserProfile(userProfile.UserProfileId, false).Entity.ToList(); }
public void EncodingSingleCookieV0() { const int MaxAge = 50; const string Result = "myCookie=myValue; Max-Age=50; Expires=(.+?); Path=/apathsomewhere; Domain=.adomainsomewhere; Secure"; var cookie = new DefaultCookie("myCookie", "myValue") { Domain = ".adomainsomewhere", MaxAge = MaxAge, Path = "/apathsomewhere", IsSecure = true }; string encodedCookie = ServerCookieEncoder.StrictEncoder.Encode(cookie); var regex = new Regex(Result, RegexOptions.Compiled); MatchCollection matches = regex.Matches(encodedCookie); Assert.Single(matches); Match match = matches[0]; Assert.NotNull(match); DateTime? expiresDate = DateFormatter.ParseHttpDate(match.Groups[1].Value); Assert.True(expiresDate.HasValue, $"Parse http date failed : {match.Groups[1].Value}"); long diff = (expiresDate.Value.Ticks - DateTime.UtcNow.Ticks) / TimeSpan.TicksPerSecond; // 2 secs should be fine Assert.True(Math.Abs(diff - MaxAge) <= 2, $"Expecting difference of MaxAge < 2s, but was {diff}s (MaxAge={MaxAge})"); }
public void Append() { StringBuilder sb = new StringBuilder(); DateFormatter.Append(_expectedTime, sb); Assert.Equal("Sun, 06 Nov 1994 08:49:37 GMT", sb.ToString()); }
public List <DateTime> GetRecentlyReadDates() { List <DateTime> results = new List <DateTime>(); try { if (!File.Exists(Filename_Store)) { return(results); } using (StreamReader sr = new StreamReader(Filename_Store)) { while (true) { string line = sr.ReadLine(); if (String.IsNullOrEmpty(line)) { break; } string[] line_splits = line.Split(','); DateTime read_date = DateFormatter.FromYYYYMMDDHHMMSS(line_splits[1]); results.Add(read_date); } } } catch (Exception ex) { Logging.Error(ex, "There was a problem with getting the recently read documents."); } return(results); }
/** **@ brief: this method removes the data from bookibg table which becomes useless when the date passes **@ Params: IJobExecutionContext context **/ public void Execute(IJobExecutionContext context) { try { DAO dao = new DAO(); DateTime currentDate = DateTime.Now; currentDate = currentDate.AddDays(-3); string dateStr = currentDate.ToString("yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture); dateStr = DateFormatter.removeTime(dateStr); dateStr = DateFormatter.setDateFormat(dateStr); DateTime dateValue = DateTime.ParseExact(dateStr, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture); List <BookingTable> listData = (from obj in dao.BookingTable_DBset where obj.bookingDate <= dateValue select obj).ToList(); if (listData.Count >= 1) { foreach (BookingTable item in listData) { dao.BookingTable_DBset.Remove(item); dao.SaveChanges(); } } } catch (Exception ex) { } }
protected override string GetCurrentPathDescription(CardItemViewModel current) { if (current == null) { return(null); } string delim = " \\ "; var sb = new StringBuilder(); var h = current.Holder; var p = h.GetPatient(); sb.Append(NameFormatter.GetFullName(p) ?? string.Format("Пациент ({0:dd.MM.yy hh:mm})", p.CreatedAt)); if (h is Course) { var c = h as Course; sb.AppendFormat("{0}курс {1}", delim, DateFormatter.GetIntervalString(c.Start, c.End)); } else if (h is Appointment) { var a = h as Appointment; sb.AppendFormat("{0}курс {1}{2}осмотр {3}", delim, DateFormatter.GetIntervalString(a.Course.Start, a.Course.End), delim, DateFormatter.GetDateString(a.DateAndTime)); } return(sb.ToString()); }
private void PopulateException(Exception ex, bool display_exception_section) { if (display_exception_section) { StringBuilder sb = new StringBuilder(); sb.Append(DateFormatter.asYYYYMMDDHHMMSS(DateTime.UtcNow) + ":"); Exception current_exception = ex; while (null != current_exception) { sb.AppendLine(current_exception.ToString()); sb.AppendLine(); sb.AppendLine("--------------------------------------------"); sb.AppendLine(); current_exception = current_exception.InnerException; } TextExceptions.Text = sb.ToString(); TextExceptionSummary.Text = ex.Message; } else { TextExceptionsRegion.Visibility = Visibility.Collapsed; } }
public static void DoBackup() { string DEFAULT_FILENAME = String.Format("QiqqaBackup.{0}.qiqqa_backup", DateFormatter.asYYYYMMDDHHMMSS(DateTime.Now)); SaveFileDialog save_file_dialog = new SaveFileDialog(); save_file_dialog.AddExtension = true; save_file_dialog.CheckPathExists = true; save_file_dialog.DereferenceLinks = true; save_file_dialog.OverwritePrompt = true; save_file_dialog.ValidateNames = true; save_file_dialog.DefaultExt = "qiqqa_backup"; save_file_dialog.Filter = "Qiqqa backup files (*.qiqqa_backup)|*.qiqqa_backup|All files (*.*)|*.*"; save_file_dialog.FileName = DEFAULT_FILENAME; save_file_dialog.Title = "Please select the file to which you want to backup."; if (true != save_file_dialog.ShowDialog()) { MessageBoxes.Warn("You have cancelled your backup of the Qiqqa database."); return; } string target_filename = save_file_dialog.FileName; string source_directory = ConfigurationManager.Instance.BaseDirectoryForQiqqa; string parameters = String.Format("a -tzip -mm=Deflate -mmt=on -mx9 \"{0}\" \"{1}\\*\"", target_filename, source_directory); Process.Start(ConfigurationManager.Instance.Program7ZIP, parameters); }
public void FormatIso8601Utc() { var actual = DateFormatter. FormatIso8601Utc(2011, 07, 13, 14, 24, 38); Assert.AreEqual("2011-07-13T14:24:38Z", actual); }
public void WhenDateFormatterCalledThenSplitIntoDayMonthYear() { DateFormatter dateFormatter = new DateFormatter(DateList); Assert.True(dateFormatter.IsDateFormatted); Console.WriteLine("WhenDateFormatterCalledThenSplitIntoDayMonthYear Done!"); }
public void TestPerformance() { CountDownLatch simpleDateFormatGate = new CountDownLatch(CONCURRENCY); CountDownLatch simpleDateFormatFinisher = new CountDownLatch(CONCURRENCY); AtomicLong simpleDateFormatCount = new AtomicLong(); for(int i = 0; i < CONCURRENCY; i++) { new ThRead(new SimpleDateFormatTask(simpleDateFormatFinisher, simpleDateFormatGate, simpleDateFormatCount, FORMAT)).start(); } simpleDateFormatFinisher.await(); CountDownLatch synchronizedGate = new CountDownLatch(CONCURRENCY); CountDownLatch synchronizedFinisher = new CountDownLatch(CONCURRENCY); AtomicLong synchronizedCount = new AtomicLong(); SimpleDateFormat format = new SimpleDateFormat(FORMAT); for(int i = 0; i < CONCURRENCY; i++) { new ThRead(new SynchronizedTask(synchronizedFinisher, synchronizedGate, synchronizedCount, format)).start(); } synchronizedFinisher.await(); CountDownLatch formatterGate = new CountDownLatch(CONCURRENCY); CountDownLatch formatterFinisher = new CountDownLatch(CONCURRENCY); AtomicLong formatterCount = new AtomicLong(); DateFormatter formatter = new DateFormatter(FORMAT, CONCURRENCY); for(int i = 0; i < CONCURRENCY; i++) { new ThRead(new FormatterTask(formatterFinisher, formatterGate, formatterCount, formatter)).start(); } formatterFinisher.await(); System.err.printf("pool: %s, new: %s, synchronized: %s", formatterCount.get(), simpleDateFormatCount.get(), synchronizedCount.get()); //assertTrue(formatterCount.get() < simpleDateFormatCount.get()); //assertTrue(formatterCount.get() < synchronizedCount.get()); // Synchronized is faster? }
public ActionResult RegisterUser(RegisterModel registerModel) { RegisterHelper registerHelper = new RegisterHelper(); var response = registerHelper.AddUser(registerModel); if (response) { //incorrect user input if (!string.IsNullOrEmpty(registerHelper.InvalidRegisterMessage)) { ViewBag.RegisterMessage = registerHelper.InvalidRegisterMessage; ViewBag.Date = DateFormatter.GetDate(DateTime.Now); var model = registerHelper.GetRegisterModel(registerModel); return(View("Register", model)); } //success return(RedirectToAction("Login", "Login")); } //errors due to other causes return(RedirectToAction("Index", "Error", new { errorMessage = registerHelper.InvalidRegisterMessage.Replace(' ', '-') })); }
public void TestFormatter() { DateFormatter formatter = new DateFormatter(FORMAT); Date date = new Date(); String value = formatter.Write(date); Date copy = formatter.Read(value); AssertEquals(date, copy); }
public async Task <IActionResult> CreateUser([FromBody] SecUsers model) { if (ModelState.IsValid) { try { model.Channel = "website"; model.Status = 1; model.CreatedOn = DateFormatter.ConvertStringToDate(DateTime.Now.ToString("dd/MM/yyyy")); var userId = await _userService.CreateUser(model); if (userId > 0) { return(Ok(userId)); } else { return(NotFound()); } } catch (Exception ex) { Console.WriteLine("Some Error AAcquired: " + ex.StackTrace); return(BadRequest()); } } return(BadRequest()); }
private void updateMealsList(DateFormatter dateFormatter) { DateTime start; DateTime end; if (dayRadioButton.Checked) { start = dateFormatter.DayBeginning(); end = dateFormatter.DayEnding(); } else if (weekRadioButton.Checked) { start = dateFormatter.WeekBeginning(); end = dateFormatter.WeekEnding(); } else { start = dateFormatter.MonthBeginning(); end = dateFormatter.MonthEnding(); } MealsList.Clear(); Globals.AllUsersMeals .Where(mealView => mealView.GetMeal().Date >= start && mealView.GetMeal().Date <= end).ToList() .ForEach(mealView => MealsList.Add(mealView)); }
public override void OnBind(Java.Lang.Object p0) { base.OnBind(p0); var message = (ChatKitQs.Src.Common.Data.Models.Message)p0; tvDuration.Text = FormatUtils.GetDurationString(message.MessageVoice.Duration); tvTime.Text = DateFormatter.Format(message.CreatedAt, DateFormatter.Template.Time); }
/// <summary> /// Creates a basic duration formatter with the given formatter, builder, and /// fallback. It's up to the caller to ensure that the locales and timezones /// of these are in sync. /// </summary> /// public BasicDurationFormatter(PeriodFormatter formatter_0, PeriodBuilder builder_1, DateFormatter fallback_2, long fallbackLimit_3) { this.formatter = formatter_0; this.builder = builder_1; this.fallback = fallback_2; this.fallbackLimit = (fallbackLimit_3 < 0) ? (long)(0) : (long)(fallbackLimit_3); }
private void generateButton_Click(object sender, EventArgs e) { try { var text = new StringBuilder(); var start = new DateFormatter(startDateTimePicker.Value); var end = new DateFormatter(endDateTimePicker.Value); if (start.DayBeginning() > end.DayEnding()) { throw new InputExemption("The start date cannot be after the end date."); } var mealsInDateRange = Globals.AllUsersMeals.Select(mealView => mealView.GetMeal()) .Where(meal => meal.Date > start.DayBeginning() && meal.Date < end.DayEnding()).ToList(); if (shoppingListRadioButton.Checked) { text.AppendLine("Shopping List"); text.AppendLine($"For dates {start} to {end}"); text.AppendLine(); var mealIdArray = mealsInDateRange.Select(meal => meal.Id).ToHashSet <int>().ToArray(); Globals.GetListOfIngredientsForMeals(mealIdArray) .ForEach(ingredient => text.AppendLine($"*\t{ingredient}")); reportTextBox.Text = text.ToString(); } if (topTenRadioButton.Checked) { text.AppendLine($"Top Recipes for dates {start} to {end}"); text.AppendLine("(Max 10)"); text.AppendLine(); text.AppendLine("Recipe Title\t\t| Times Recipe Used"); text.AppendLine("-----------------------------------------------------------------------------------"); var groupOfRecipes = Globals.GetMealsRecipes(mealsInDateRange).GroupBy(recipe => recipe.Title) .OrderByDescending(recipe => recipe.Count()).Take(10); foreach (var group in groupOfRecipes) { if (group.Key.Length < 8) { text.AppendLine($"{group.Key}\t\t\t| {group.Count()}"); } else { text.AppendLine($"{group.Key}\t\t| {group.Count()}"); } } reportTextBox.Text = text.ToString(); } } catch (InputExemption error) { MessageBox.Show(error.Message, "Instructions", MessageBoxButtons.OK); } }
/** *@ brief: this method first checks that parameters are not null or empty then it will check the parameter's character * length then it will get the user by name, phone and date. if it will get only one user then it will send that * user object in response, if it get more than one user then it will send the message "multipleUsers" wrapped in * http error response, if it does not finds any user then it will send the message "notFound" wrapped in * http error response *@ Params: string fname, string lname, string phone, string joinDate *@ return: HttpResponseMessage **/ public HttpResponseMessage getUserByNamePhoneAndDateFromDB(string fname, string lname, string phone, string joinDate) { try { string[] inputStrings = trimInputString(fname, lname, phone, joinDate); fname = inputStrings[0]; lname = inputStrings[1]; phone = inputStrings[2]; joinDate = inputStrings[3]; // checks string is null or empty if (!string.IsNullOrEmpty(fname) && !string.IsNullOrEmpty(lname) && !string.IsNullOrEmpty(phone) && !string.IsNullOrEmpty(joinDate)) { if (fname.Length <= 20 && lname.Length <= 20 && phone.Length <= 20 && joinDate.Length <= 50) { dao.Configuration.ProxyCreationEnabled = false; dao.Configuration.LazyLoadingEnabled = false; joinDate = DateFormatter.setDateFormat(joinDate); DateTime _joinDate = DateTime.ParseExact(joinDate, "yyyy/MM/dd HH:mm:ss", CultureInfo.InvariantCulture); var list = (from obj in dao.User_DBset where obj.firstName == fname && obj.lastName == lname && obj.phoneNo == phone && obj.joinDate == _joinDate select obj).Include(c => c.club).ToList(); if (list.Count == 1) { var item = list.First(); response = Request.CreateResponse(HttpStatusCode.OK, item, GlobalConfiguration.Configuration); } if (list.Count > 1) { // make log that multiple user exist response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "multipleUsers"); } if (list.Count == 0) { response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "notFound"); } } else { response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ""); } } else { //make log response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ""); } } catch (Exception ex) { response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ""); } return(response); }
static void Main(string[] args) { var formatter = new DateFormatter(); string formatedNow = formatter.Format(DateTime.Now); Console.WriteLine(formatedNow); Console.ReadLine(); }
public DiscordEmbed Build(LaunchInfo launch, ulong?guildId, bool informAboutSubscription) { var embed = new DiscordEmbedBuilder { Title = $"{launch.FlightNumber}. {launch.Name} ({launch.Rocket.Value.Name} {launch.Rocket.Value.Type})", Description = launch.Details.ShortenString(1024) ?? "*No description at this moment :(*", Color = new DiscordColor(Constants.EmbedColor), Thumbnail = new DiscordEmbedBuilder.EmbedThumbnail { Url = launch.Links.Patch.Large ?? Constants.SpaceXLogoImage } }; var launchDateTime = DateFormatter.GetDateStringWithPrecision( launch.DateUtc ?? DateTime.MinValue, launch.DatePrecision ?? DatePrecision.Year, true, true, true); embed.AddField(":clock4: Launch time (UTC)", launchDateTime, true); if (guildId != null) { var localLaunchDateTime = GetLocalLaunchDateTime( guildId.Value, launch.DateUtc ?? DateTime.MinValue, launch.DatePrecision ?? DatePrecision.Year); var timeZoneName = _timeZoneService.GetTimeZoneForGuild(guildId.Value); if (timeZoneName != null) { embed.AddField($":clock230: Launch time ({timeZoneName})", localLaunchDateTime); } } var googleMapsLink = $"[Map]({GoogleMapsLinkFormatter.GetGoogleMapsLink(launch.Launchpad.Value.Latitude ?? 0.0, launch.Launchpad.Value.Longitude ?? 0.0)})"; embed.AddField(":stadium: Launchpad", $"{launch.Launchpad.Value.FullName} **[{googleMapsLink}]**"); embed.AddField($":rocket: First stages ({1 + launch.Rocket.Value.Boosters})", GetCoresData(launch.Cores)); embed.AddField($":package: Payloads ({launch.Payloads.Count})", GetPayloadsData(launch.Payloads)); embed.AddField(":recycle: Reused parts", GetReusedPartsData(launch)); var linksData = GetLinksData(launch); if (linksData.Length > 0) { embed.AddField(":newspaper: Links", linksData); } if (informAboutSubscription) { embed.AddField("\u200b", "*Click the reaction below to subscribe this flight and be notified on DM 10 minutes before the launch.*"); } return(embed); }
/// <summary> /// Map a conference to an generic item /// </summary> /// <param name="element">Conference to map</param> /// <returns>Corresponding generic item</returns> public VisualGenericItem Map(Conference element) { return(new VisualGenericItem { Id = element.Id, Title = element.Name, Subtitle = string.Format("{0}, {1}", element.Campus.Place, DateFormatter.Format(element.Start_DateTime)), ImageUrl = element.ImageUrl, Type = element.GetType().Name }); }
public void Format_GivenDateString_ShouldReturnFormattedString() { // Arrange. var testObject = new DateFormatter("d MMM (ddd)"); // Act. string result = testObject.Format("2019-7-1"); // Assert. Assert.AreEqual("1 Jul (Mon)", result); }
public RuntimeInfo() { ComputerUpTime = DateFormatter.ToReadableString(GetComputerUpTime()); ComputerName = Environment.MachineName; OSInfo = Environment.OSVersion.VersionString; TotalMemorySize = ByteFormatter.Format(GetTotalMemorySize()); InstallDate = GetWindowsInstallationDateTime(); ProcessorCount = Environment.ProcessorCount; InputLocale = InputLanguage.CurrentInputLanguage.Culture.TwoLetterISOLanguageName; SystemLocale = GetSysLocale(); }
protected internal BasicDurationFormatter(PeriodFormatter formatter_0, PeriodBuilder builder_1, DateFormatter fallback_2, long fallbackLimit_3, String localeName_4, IBM.ICU.Util.TimeZone timeZone_5) { this.formatter = formatter_0; this.builder = builder_1; this.fallback = fallback_2; this.fallbackLimit = fallbackLimit_3; this.localeName = localeName_4; this.timeZone = timeZone_5; }
/// <summary> /// Map a show to an generic item /// </summary> /// <param name="element">Show to map</param> /// <returns>Corresponding generic item</returns> public VisualGenericItem Map(Show element) { return(new VisualGenericItem { Id = element.Id, Title = element.Name, Subtitle = DateFormatter.Format(element.Start_DateTime), ImageUrl = element.ImageUrl, Type = element.GetType().Name }); }
public override void calculateFeedDate() { if (isActivePeriod()) { FeedDate = DateFormatter.addDays(FeedDate, 2); } else { FeedDate = DateFormatter.addDays(FeedDate, 1); } }
public override ICharSequence ConvertObject(object value) { if (value is ICharSequence seq) { return(seq); } if (value is DateTime time) { return(new StringCharSequence(DateFormatter.Format(time))); } return(new StringCharSequence(value.ToString())); }
public void DateFormatterReturnsCorrectToStringMethod() { //Arrange var date = new DateTime(2021, 3, 14, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); //Act var newDateFormatter = new DateFormatter(date); var actual = newDateFormatter.ToString(); var expected = "3-14-2021"; //Assert Assert.AreEqual(expected, actual); }
public FormatterTask(CountDownLatch main, CountDownLatch gate, AtomicLong count, DateFormatter formatter) { this.formatter = formatter; this.count = count; this.gate = gate; this.main = main; }