private void PrepareArticleVIew(long articleId) { var addedAt = DateTimeHelpers.GetCurrenTime(); articleView = new ArticleView(articleId, addedAt); }
public virtual void Flush() { MetricsManager.FlushMetricsLogger(this); MetricsManager.FlushToServer(DateTimeHelpers.GetTimeStampInSeconds()); }
public void ParseGermanDateTimeString_MMDDYYYY_ShouldReturnCorrectDateTime() { var text = "09/12/2020"; var actual = DateTimeHelpers.ParseGermanDateTimeString(text); }
public void Invalid_Second() { var date = new DateTime(2010, 10, 3, 12, 22, 7); DateTimeHelpers.SetSecond(date, -8); }
public void Invalid_Year() { DateTimeHelpers.GetMonthWeeks(12, -8); }
public async Task ProcessImportRow(string userMailString, string epicString, string dateString, string hourString, string desc, List <Epic> epics, List <CodeHubUser> users) { var workLog = new WorkLog { UserId = users.FirstOrDefault(s => s.Email == userMailString)?.Id ?? throw new Exception($"User {userMailString} not found"), DateFinished = DateTime.FromOADate(int.Parse(dateString)).Date, DateStarted = DateTime.FromOADate(int.Parse(dateString)).Date, Description = desc, Epic = epics.FirstOrDefault(s => s.Name == epicString) ?? throw new Exception($"Epic {epicString} not found"), EpicId = epics.FirstOrDefault(s => s.Name == epicString)?.Id ?? throw new Exception($"Epic {epicString} not found"), Hours = DateTimeHelpers.GetTimeFromString(hourString), Status = WorkLogStatus.Unbillable, SubmittedTime = DateTime.UtcNow }; await CreateWorkLog(workLog); }
private IEnumerable <ArticleScheduleTask> GetArticleSchedulerTaskList() { var taskComposer = _fixture .Build <ArticleScheduleTask>() .With(t => t.Id, ScheduleId) .With(t => t.ArticleId, ArticleId) .With(t => t.FreqRelativeInterval, 4) .With(t => t.FreqRecurrenceFactor, 5) .With(t => t.StartDate, DateTimeHelpers.ParseDate("01/01/2011")) .With(t => t.StartTime, DateTimeHelpers.ParseTime("12:15:17")) .With(t => t.EndTime, DateTimeHelpers.ParseTime("18:15:17")) .With(t => t.Duration, TimeSpan.FromDays(5)); var onetimeTaskComposer = taskComposer.With(t => t.FreqType, ScheduleFreqTypes.OneTime).With(t => t.FreqInterval, 3); var publishingTaskComposer = taskComposer.With(t => t.FreqType, ScheduleFreqTypes.Publishing).With(t => t.FreqInterval, 3); var onetimeTasks = new[] { onetimeTaskComposer.With(t => t.EndDate, DateTimeHelpers.ParseDate("01/31/2011")).Create(), onetimeTaskComposer.With(t => t.EndDate, DateTimeHelpers.ParseDate("12/31/2011")).Create(), onetimeTaskComposer.With(t => t.EndDate, DateTimeHelpers.ParseDate("01/05/2011")).With(t => t.EndTime, DateTimeHelpers.ParseTime("12:15:17")).Create(), onetimeTaskComposer .With(t => t.StartDate, DateTimeHelpers.ParseDate(CurrentDateTime).AddHours(2)) .With(t => t.StartTime, DateTimeHelpers.ParseTime(CurrentDateTime)) .With(t => t.EndDate, DateTimeHelpers.ParseDate("12/31/2011")) .Create() }; var publishingTasks = new[] { publishingTaskComposer.With(t => t.EndDate, DateTimeHelpers.ParseDate("12/31/2011")).Create(), publishingTaskComposer .With(t => t.StartDate, DateTimeHelpers.ParseDate(CurrentDateTime).AddHours(2)) .With(t => t.StartTime, DateTimeHelpers.ParseTime(CurrentDateTime)) .Create() }; var recurringTasks = new[] { taskComposer.With(t => t.FreqType, ScheduleFreqTypes.RecurringDaily).With(t => t.FreqInterval, 1).With(t => t.EndDate, DateTimeHelpers.ParseDate("12/31/2011")).Create(), taskComposer.With(t => t.FreqType, ScheduleFreqTypes.RecurringMonthlyRelative).With(t => t.FreqInterval, 9).With(t => t.EndDate, DateTimeHelpers.ParseDate("12/31/2011")).Create() }; return(onetimeTasks.Concat(publishingTasks).Concat(recurringTasks)); }
public void Invalid_Month() { Assert.IsFalse(DateTimeHelpers.IsValidDate(2018, 13, 1)); }
public void Invalid_Day() { Assert.IsFalse(DateTimeHelpers.IsValidDate(2018, 12, 32)); }
public void NormalUse() { Assert.IsTrue(DateTimeHelpers.IsValidDate(2010, 1, 1)); Assert.IsFalse(DateTimeHelpers.IsValidDate(2010, 13, 66)); }
public void Invalid_Year() { Assert.IsFalse(DateTimeHelpers.IsValidDate(-1, 1, 1)); }
protected SpeechletRequest(JObject json) { RequestId = json.Value <string>("requestId"); Timestamp = DateTimeHelpers.FromAlexaTimestamp(json); Locale = json.Value <string>("locale"); }
public JsonResult UpdateCalendarItem(CalendarItemJson item) { if (ModelState.IsValid) { var department = _departmentsService.GetDepartmentById(DepartmentId, false); var calendarItem = _calendarService.GetCalendarItemById(item.CalendarItemId); if (calendarItem != null) { calendarItem.DepartmentId = DepartmentId; calendarItem.CalendarItemId = item.CalendarItemId; calendarItem.Title = item.Title; //if (item.Start.Kind == DateTimeKind.Utc) // calendarItem.Start = item.Start.TimeConverter(department); //else // calendarItem.Start = item.Start; //if (item.End.Kind == DateTimeKind.Utc) // calendarItem.End = item.End.TimeConverter(department); //else // calendarItem.End = item.End; calendarItem.Start = DateTime.Parse(item.Start).ToUniversalTime(); calendarItem.End = DateTime.Parse(item.End).ToUniversalTime(); calendarItem.StartTimezone = item.StartTimezone; calendarItem.EndTimezone = item.EndTimezone; calendarItem.Description = item.Description; calendarItem.RecurrenceId = item.RecurrenceId; calendarItem.RecurrenceRule = item.RecurrenceRule; calendarItem.RecurrenceException = item.RecurrenceException; calendarItem.IsAllDay = item.IsAllDay; calendarItem.Location = item.Location; calendarItem.SignupType = item.SignupType; calendarItem.Reminder = item.Reminder; calendarItem.LockEditing = item.LockEditing; calendarItem.Entities = item.Entities; calendarItem.RequiredAttendes = item.RequiredAttendes; calendarItem.OptionalAttendes = item.OptionalAttendes; calendarItem.CreatorUserId = UserId; calendarItem.Public = item.Public; calendarItem.StartTimezone = DateTimeHelpers.WindowsToIana(department.TimeZone); calendarItem.EndTimezone = DateTimeHelpers.WindowsToIana(department.TimeZone); if (item.ItemType.HasValue) { calendarItem.ItemType = item.ItemType.Value; } calendarItem = _calendarService.SaveCalendarItem(calendarItem); _eventAggregator.SendMessage <CalendarEventUpdatedEvent>(new CalendarEventUpdatedEvent() { DepartmentId = DepartmentId, Item = calendarItem }); return(Json(item)); } } return(null); }
public JsonResult CreateCalendarItem([FromBody] CalendarItemJson item) { if (ModelState.IsValid) { var department = _departmentsService.GetDepartmentById(DepartmentId, false); var timeZone = "Etc/UTC"; if (!String.IsNullOrWhiteSpace(department.TimeZone)) { timeZone = DateTimeHelpers.WindowsToIana(department.TimeZone); } CalendarItem calendarItem = new CalendarItem(); calendarItem.DepartmentId = DepartmentId; calendarItem.CalendarItemId = item.CalendarItemId; calendarItem.Title = item.Title; //if (item.Start.Kind == DateTimeKind.Utc) // calendarItem.Start = item.Start.TimeConverter(department); //else // calendarItem.Start = item.Start; //if (item.End.Kind == DateTimeKind.Utc) // calendarItem.End = item.End.TimeConverter(department); //else // calendarItem.End = item.End; if (!String.IsNullOrWhiteSpace(item.Start)) { calendarItem.Start = DateTime.Parse(item.Start).ToUniversalTime(); } else { calendarItem.Start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).ToUniversalTime(); } if (!String.IsNullOrWhiteSpace(item.End)) { calendarItem.End = DateTime.Parse(item.End).ToUniversalTime(); } else { calendarItem.Start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 23, 59, 59).ToUniversalTime(); } if (!String.IsNullOrWhiteSpace(item.StartTimezone)) { calendarItem.StartTimezone = item.StartTimezone; } else { calendarItem.StartTimezone = timeZone; } if (!String.IsNullOrWhiteSpace(item.EndTimezone)) { calendarItem.EndTimezone = item.EndTimezone; } else { calendarItem.EndTimezone = timeZone; } calendarItem.Description = item.Description; calendarItem.RecurrenceId = item.RecurrenceId; calendarItem.RecurrenceRule = item.RecurrenceRule; calendarItem.RecurrenceException = item.RecurrenceException; calendarItem.IsAllDay = item.IsAllDay; calendarItem.Location = item.Location; calendarItem.SignupType = item.SignupType; calendarItem.Reminder = item.Reminder; calendarItem.LockEditing = item.LockEditing; calendarItem.Entities = item.Entities; calendarItem.RequiredAttendes = item.RequiredAttendes; calendarItem.OptionalAttendes = item.OptionalAttendes; calendarItem.Public = item.Public; calendarItem.CreatorUserId = UserId; calendarItem.StartTimezone = DateTimeHelpers.WindowsToIana(department.TimeZone); calendarItem.EndTimezone = DateTimeHelpers.WindowsToIana(department.TimeZone); if (item.ItemType.HasValue) { calendarItem.ItemType = item.ItemType.Value; } calendarItem = _calendarService.SaveCalendarItem(calendarItem); _eventAggregator.SendMessage <CalendarEventAddedEvent>(new CalendarEventAddedEvent() { DepartmentId = DepartmentId, Item = calendarItem }); return(Json(item)); } return(null); }
public void FromUnixTime_0_IsEpoch() { DateTime actual = DateTimeHelpers.FromUnixTime(0); Assert.AreEqual(DateTimeHelpers.EPOCH, actual); }
private static SpeechletRequest RequestFromJson(JObject json) { SpeechletRequest request; var requestTypeParts = json?.Value <string>("type")?.Split('.'); if (requestTypeParts == null) { throw new ArgumentException("json"); } var requestType = requestTypeParts[0]; var requestSubType = requestTypeParts.Length > 1 ? requestTypeParts[1] : null; var requestId = json.Value <string>("requestId"); var timestamp = DateTimeHelpers.FromAlexaTimestamp(json); var locale = json.Value <string>("locale"); switch (requestType) { case "LaunchRequest": request = new LaunchRequest(requestId, timestamp, locale); break; case "IntentRequest": IntentRequest.DialogStateEnum dialogState = IntentRequest.DialogStateEnum.NONE; Enum.TryParse(json.Value <string>("dialogState"), out dialogState); var intent = Intent.FromJson(json.Value <JObject>("intent")); request = new IntentRequest(requestId, timestamp, locale, intent, dialogState); break; case "SessionStartedRequest": request = new SessionStartedRequest(requestId, timestamp, locale); break; case "SessionEndedRequest": SessionEndedRequest.ReasonEnum reason = SessionEndedRequest.ReasonEnum.NONE; Enum.TryParse(json.Value <string>("reason"), out reason); var sessionError = Error.FromJson(json.Value <JObject>("error")); request = new SessionEndedRequest(requestId, timestamp, locale, reason, sessionError); break; case "AudioPlayer": var token = json.Value <string>("token"); var offset = json.Value <long?>("offsetInMilliseconds"); var playbackError = Error.FromJson(json.Value <JObject>("error")); var currentPlaybackState = PlaybackState.FromJson(json.Value <JObject>("currentPlaybackState")); switch (requestSubType) { case "PlaybackFailed": request = new AudioPlayerPlaybackFailedRequest(requestId, timestamp, locale, requestSubType, token, playbackError, currentPlaybackState); break; default: request = new AudioPlayerRequest(requestId, timestamp, locale, requestSubType, token, offset); break; } break; case "PlaybackController": request = new PlaybackControllerRequest(requestId, timestamp, locale, requestSubType); break; case "Display": var listItemToken = json.Value <string>("token"); request = new DisplayRequest(requestId, timestamp, locale, requestSubType, listItemToken); break; case "System": switch (requestSubType) { case "ExceptionEncountered": var systemError = Error.FromJson(json.Value <JObject>("error")); var cause = Cause.FromJson(json.Value <JObject>("cause")); request = new SystemExceptionEncounteredRequest(requestId, timestamp, locale, requestSubType, systemError, cause); break; default: throw new ArgumentException("json"); } break; default: throw new ArgumentException("json"); } return(request); }
public void FromUnixTime_123456890__SPECIAL_DAY() { DateTime actual = DateTimeHelpers.FromUnixTime(SPECIAL_DAY_SECONDS); Assert.AreEqual(SPECIAL_DAY, actual); }
public async Task <List <Shift> > GetShiftsStartingNextDayAsync(DateTime currentTime) { var upcomingShifts = new List <Shift>(); var shifts = await _shiftsRepository.GetAllShiftAndDaysAsync(); foreach (var shift in shifts) { try { //var shiftData = await PopulateShiftData(shift, true, true, true, true, true); if (shift.Days != null && shift.Days.Any()) { if (shift.Department == null) { shift.Department = await _departmentsService.GetDepartmentByIdAsync(shift.DepartmentId, false); } var localizedDate = TimeConverterHelper.TimeConverter(currentTime, shift.Department); var shiftStart = shift.StartTime; if (String.IsNullOrWhiteSpace(shiftStart)) { shiftStart = "12:00 AM"; } var startTime = DateTimeHelpers.ConvertStringTime(shiftStart, localizedDate, shift.Department.Use24HourTime.GetValueOrDefault()); var shiftDays = from sd in shift.Days let shiftDayTime = DateTimeHelpers.ConvertStringTime(shiftStart, sd.Day, shift.Department.Use24HourTime.GetValueOrDefault()) let nextDayShiftTime = localizedDate.AddDays(1) where shiftDayTime == nextDayShiftTime.Within(TimeSpan.FromMinutes(15)) select sd; //List<ShiftDay> shiftDays = new List<ShiftDay>(); //foreach (var sd in shift.Days) //{ // var shiftDayTime = DateTimeHelpers.ConvertStringTime(shiftStart, sd.Day, shift.Department.Use24HourTime.GetValueOrDefault()); // var nextDayShiftTime = localizedDate.AddDays(1); // if (shiftDayTime == nextDayShiftTime.Within(TimeSpan.FromMinutes(15))) // shiftDays.Add(sd); //} if (shiftDays.Any()) { var previousShift = from sd in shift.Days where sd.Day.ToShortDateString() == startTime.ToShortDateString() select sd; if (!previousShift.Any()) { upcomingShifts.Add(shift); } } } } catch (Exception ex) { Logging.LogException(ex, $"DepartmentId:{shift.DepartmentId}"); } } return(upcomingShifts); }
public void Invalid_Minute() { var date = new DateTime(2010, 10, 3, 12, 22, 7); DateTimeHelpers.SetMinute(date, -8); }
public void UpdateActivity() { try { if (_appEnvironment.ServiceConnector == null) { throw new NullReferenceException($"Null reference of { nameof(_appEnvironment.ServiceConnector) }"); } if (SelectedActivity != null) { var activityToUpdate = new ActivityDto() { Id = SelectedActivity.Id, ProfileId = SelectedActivity.ProfileId, IsStarted = SelectedActivity.IsStarted, BeginTime = (Int64)DateTimeHelpers.ConvertToUnixTimestamp(SelectedActivity.BeginTime.ToUniversalTime()), CreatedAt = (Int64)DateTimeHelpers.ConvertToUnixTimestamp(SelectedActivity.CreatedAt.ToUniversalTime()), PlannedBeginTime = (Int64)DateTimeHelpers.ConvertToUnixTimestamp(SelectedActivity.PlannedBeginTime.ToUniversalTime()), Description = SelectedActivity.Description, Category = SelectedActivity.Category, ActualDuration = SelectedActivity.DurationSeconds, }; foreach (var interval in SelectedActivity.WorkIntervals) { activityToUpdate.WorkIntervals.Add(new WorkIntervalDto() { Begin = (Int64)DateTimeHelpers.ConvertToUnixTimestamp(interval.Begin.ToUniversalTime()), End = (Int64)DateTimeHelpers.ConvertToUnixTimestamp(interval.End.ToUniversalTime()) }); } var response = _appEnvironment.ServiceConnector.Post <ActivityDto, SuccessMsgDto, ErrorMsgDto>(new Request <ActivityDto> { AuthToken = new KeyValuePair <string, string>("session_token", SessionStorage.Instance.SessionId), UrlSegments = new Dictionary <string, string>() { { "id", SelectedActivity.Id } }, Body = activityToUpdate, OpName = OperationType.UpdateActvity }); if (response.SuccessBody != null) { } } } catch (ApplicationException e) { Logger.Log.Debug(e.Message); } catch (Exception e) { Logger.Log.Debug(e.Message); } finally { if (SelectedActivity != null && SelectedActivity.IsDirty) { SelectedActivity.AcceptChanges(); } DetailsDialogEnabled = false; } }
public void NormalUse() { Assert.AreEqual(DateTimeHelpers.Midnight(new DateTime(2018, 2, 1, 11, 45, 22)), new DateTime(2018, 2, 1, 0, 0, 0)); }
private void GetAllActivities() { try { if (_appEnvironment.ServiceConnector == null) { throw new NullReferenceException($"Null reference of { nameof(_appEnvironment.ServiceConnector) }"); } Double totalSeconds = default(Double); var userInfo = new UserInfoDto() { ProfileId = SessionStorage.Instance.ProfileId }; var response = _appEnvironment.ServiceConnector.Get <UserInfoDto, List <ActivityDto>, ErrorMsgDto>(new Request <UserInfoDto> { AuthToken = new KeyValuePair <string, string>("session_token", SessionStorage.Instance.SessionId), Body = userInfo, OpName = OperationType.GetActivities }); if (response.SuccessBody != null) { foreach (var activityDto in response.SuccessBody) { var existedActivity = Activities.Where(a => { return(a.Id == activityDto.Id); }).FirstOrDefault(); if (existedActivity == null) { var newActivity = new ActivityDomainModel(); using (UntrackedContext <ActivityDomainModel> .Untrack(newActivity)) { newActivity.Id = activityDto.Id; newActivity.ProfileId = activityDto.ProfileId; newActivity.IsStarted = activityDto.IsStarted; newActivity.Description = activityDto.Description; newActivity.Category = activityDto.Category; newActivity.DurationSeconds = activityDto.ActualDuration; newActivity.CreatedAt = DateTimeHelpers.ConvertFromUnixTimestamp(activityDto.CreatedAt).ToLocalTime(); newActivity.BeginTime = DateTimeHelpers.ConvertFromUnixTimestamp(activityDto.BeginTime).ToLocalTime(); newActivity.PlannedBeginTime = DateTimeHelpers.ConvertFromUnixTimestamp(activityDto.PlannedBeginTime).ToLocalTime(); if (activityDto.WorkIntervals != null) { foreach (var interval in activityDto.WorkIntervals) { newActivity.WorkIntervals.Add(new WorkInterval() { Begin = DateTimeHelpers.ConvertFromUnixTimestamp(interval.Begin).ToLocalTime(), End = DateTimeHelpers.ConvertFromUnixTimestamp(interval.End).ToLocalTime() }); } } Activities.Add(newActivity); }; totalSeconds += activityDto.ActualDuration; TotalDurationSeconds = totalSeconds; } } } } catch (ApplicationException e) { Logger.Log.Debug(e.Message); } catch (Exception e) { Logger.Log.Debug(e.Message); } }
public void Invalid_Month() { DateTimeHelpers.GetMonthWeeks(13, 2018); }
private void AddActivity() { try { if (_appEnvironment.ServiceConnector == null) { throw new NullReferenceException($"Null reference of { nameof(_appEnvironment.ServiceConnector) }"); } var activityDto = new ActivityDto { ProfileId = SessionStorage.Instance.ProfileId, IsStarted = false, Category = "", Description = NewActivityDescription, PlannedBeginTime = (Int64)DateTimeHelpers.ConvertToUnixTimestamp(DateTime.Now.AddHours(2).ToUniversalTime()) }; var response = _appEnvironment.ServiceConnector.Post <ActivityDto, ActivityDto, ErrorMsgDto>(new Request <ActivityDto> { AuthToken = new KeyValuePair <string, string>("session_token", SessionStorage.Instance.SessionId), Body = activityDto, OpName = OperationType.CreateActivity }); if (response.SuccessBody != null) { var newActivity = new ActivityDomainModel(); newActivity.Id = response.SuccessBody.Id; newActivity.IsStarted = response.SuccessBody.IsStarted; newActivity.ProfileId = response.SuccessBody.ProfileId; newActivity.Description = response.SuccessBody.Description; newActivity.Category = response.SuccessBody.Category; newActivity.PlannedBeginTime = DateTimeHelpers.ConvertFromUnixTimestamp(response.SuccessBody.PlannedBeginTime).ToLocalTime(); newActivity.CreatedAt = DateTimeHelpers.ConvertFromUnixTimestamp(response.SuccessBody.CreatedAt).ToLocalTime(); newActivity.BeginTime = DateTimeHelpers.ConvertFromUnixTimestamp(response.SuccessBody.BeginTime).ToLocalTime(); newActivity.DurationSeconds = response.SuccessBody.ActualDuration; if (response.SuccessBody.WorkIntervals != null) { foreach (var interval in activityDto.WorkIntervals) { newActivity.WorkIntervals.Add(new WorkInterval() { Begin = DateTimeHelpers.ConvertFromUnixTimestamp(interval.Begin).ToLocalTime(), End = DateTimeHelpers.ConvertFromUnixTimestamp(interval.End).ToLocalTime() }); } } Activities.Add(newActivity); } } catch (ApplicationException e) { Logger.Log.Debug(e.Message); } catch (Exception e) { Logger.Log.Debug(e.Message); } }
public void NormalUse() { Assert.AreEqual(DateTimeHelpers.FirstDayOfMonth(new DateTime(2018, 2, 26)), new DateTime(2018, 2, 1)); }
private DateTime?ProcessMonthlyPattern(RecurrenceRule recurrence, RecurrenceRuleException[] exceptions, int timeZoneShift) { try { log.LogFunctionStart(); var startDate = recurrence.StartDate ?? DateTime.UtcNow; var userLocalNow = DateTime.UtcNow.AddMinutes(timeZoneShift); var nextMonthlyBase = startDate.AddMinutes(timeZoneShift); DateTime?targetDate = nextMonthlyBase; var occurrenceCount = recurrence.OccurrenceCount; if (occurrenceCount == null) { if (targetDate < userLocalNow) { targetDate = targetDate?.AddDays((int)(userLocalNow - nextMonthlyBase).TotalDays); log.Log($"New target date after jump range: {targetDate}.", LogLevel.Debug); } } else { log.Log($"Remaining occurrences: {occurrenceCount}"); } var months = recurrence.Months.Split(','); var daysOfTheMonth = recurrence.DaysOfTheMonth.Split(','); var occurrences = recurrence.DayOccurrences?.Split(',') .Select(e => (RecurrenceRule.MonthlyDayOccurrenceEnum) RecurrenceRule.Enums.GetValue(RecurrenceRule.Fields.MonthlyDayOccurrence, e.ToTitleCase())).ToArray(); var daysOfWeek = recurrence.WeekDays?.Split(',') .Select(e => (RecurrenceRule.WeekDayEnum) RecurrenceRule.Enums.GetValue(RecurrenceRule.Fields.WeekDay, e.ToTitleCase())) .ToArray(); var isFound = false; var exceptionRetryCount = 5000; while (true) { if (occurrenceCount != null && occurrenceCount <= 0) { log.Log("Occurrences exceeded.", LogLevel.Warning); targetDate = null; break; } if (targetDate > recurrence.EndDate?.AddMinutes(timeZoneShift)) { log.Log("Generated date exceeds the end date.", LogLevel.Warning); targetDate = null; break; } // must be in the future, and month selected if (months.Contains(nextMonthlyBase.ToString("MMMM").ToLower()) && nextMonthlyBase >= userLocalNow) { switch (recurrence.MonthlyPattern) { case RecurrenceRule.MonthlyPatternEnum.SpecificDays: if (daysOfTheMonth.Contains(nextMonthlyBase.Day.ToString())) { isFound = true; } break; case RecurrenceRule.MonthlyPatternEnum.DayOccurrence: if (daysOfWeek == null && occurrences != null) { if (occurrences.Contains(RecurrenceRule.MonthlyDayOccurrenceEnum.Last)) { isFound = nextMonthlyBase.Day == DateTime.DaysInMonth(nextMonthlyBase.Year, nextMonthlyBase.Month); } } for (var j = 0; j < daysOfWeek?.Length && !isFound; j++) { for (var k = 0; k < occurrences?.Length && !isFound; k++) { var isLastOccurrence = occurrences[j] == RecurrenceRule.MonthlyDayOccurrenceEnum.Last; var dateTimeDayOfWeek = GetDayOfWeek(daysOfWeek[j]); var occurrenceDate = DateTimeHelpers.GetDayOccurrenceOfMonth(nextMonthlyBase, dateTimeDayOfWeek, (int)occurrences[j], isLastOccurrence); if (occurrenceDate != null && occurrenceDate == nextMonthlyBase) { isFound = true; } } } break; default: throw new ArgumentOutOfRangeException("MonthlyPattern", $"{recurrence.MonthlyPattern} : {(int) recurrence.MonthlyPattern}", "Pattern value not recognised."); } } if (isFound) { // must not be excluded if (!IsExcluded(nextMonthlyBase, exceptions)) { targetDate = nextMonthlyBase; log.Log("Found!", LogLevel.Debug); break; } // too many exclusion retries could lead to an infinite loop if (--exceptionRetryCount <= 0) { throw new InvalidPluginExecutionException("Couldn't find a target date." + " Please relax the exclusion rules."); } } occurrenceCount--; isFound = false; nextMonthlyBase = nextMonthlyBase.AddDays(1); } log.Log($"Target date: {targetDate}"); return(targetDate?.AddMinutes(-timeZoneShift)); } catch (Exception ex) { log.Log(ex); throw; } finally { log.LogFunctionEnd(); } }
/// <summary> /// /// </summary> /// <param name="json"></param> /// <returns></returns> public static SpeechletRequestEnvelope FromJson(JObject json) { if (json["version"] != null && json["version"].Value <string>() != Sdk.VERSION) { throw new SpeechletException("Request must conform to 1.0 schema."); } SpeechletRequest request; var requestJson = json.Value <JObject>("request"); var requestTypeParts = requestJson?.Value <string>("type")?.Split('.'); if (requestTypeParts == null) { throw new ArgumentException("json"); } var requestType = requestTypeParts[0]; var requestSubType = requestTypeParts.Length > 1 ? requestTypeParts[1] : null; var requestId = requestJson?.Value <string>("requestId"); var timestamp = DateTimeHelpers.FromAlexaTimestamp(requestJson); var locale = requestJson?.Value <string>("locale"); switch (requestType) { case "LaunchRequest": request = new LaunchRequest(requestId, timestamp, locale); break; case "IntentRequest": IntentRequest.DialogStateEnum dialogState = IntentRequest.DialogStateEnum.NONE; Enum.TryParse(requestJson.Value <string>("dialogState"), out dialogState); var intent = Intent.FromJson(requestJson.Value <JObject>("intent")); request = new IntentRequest(requestId, timestamp, locale, intent, dialogState); break; case "SessionStartedRequest": request = new SessionStartedRequest(requestId, timestamp, locale); break; case "SessionEndedRequest": SessionEndedRequest.ReasonEnum reason = SessionEndedRequest.ReasonEnum.NONE; Enum.TryParse(requestJson.Value <string>("reason"), out reason); request = new SessionEndedRequest(requestId, timestamp, locale, reason); break; case "AudioPlayer": var token = requestJson?.Value <string>("token"); var offset = requestJson?.Value <long>("offsetInMilliseconds") ?? 0; var playbackError = Error.FromJson(requestJson?.Value <JObject>("error")); var currentPlaybackState = PlaybackState.FromJson(requestJson?.Value <JObject>("currentPlaybackState")); switch (requestSubType) { case "PlaybackFailed": request = new AudioPlayerPlaybackFailedRequest(requestId, timestamp, locale, requestSubType, token, playbackError, currentPlaybackState); break; default: request = new AudioPlayerRequest(requestId, timestamp, locale, requestSubType, token, offset); break; } break; case "PlaybackController": request = new PlaybackControllerRequest(requestId, timestamp, locale, requestSubType); break; case "Display": var listItemToken = requestJson?.Value <string>("token"); request = new DisplayRequest(requestId, timestamp, locale, requestSubType, listItemToken); break; case "System": switch (requestSubType) { case "ExceptionEncountered": var error = Error.FromJson(requestJson?.Value <JObject>("error")); var cause = Cause.FromJson(requestJson?.Value <JObject>("cause")); request = new SystemExceptionEncounteredRequest(requestId, timestamp, locale, requestSubType, error, cause); break; default: throw new ArgumentException("json"); } break; default: throw new ArgumentException("json"); } return(new SpeechletRequestEnvelope { Request = request, Session = Session.FromJson(json.Value <JObject>("session")), Version = json.Value <string>("version"), Context = Context.FromJson(json.Value <JObject>("context")) }); }
private bool IsExcluded(DateTime utcDate, RecurrenceRuleException[] exceptions, int timeZoneShift = 0) { var userLocalDate = utcDate.AddMinutes(timeZoneShift); foreach (var exception in exceptions) { var isMinuteExcluded = exception.Minutes?.Split(',').Contains(userLocalDate.Minute.ToString()) != false; var isHourExcluded = exception.Hours?.Split(',').Contains(userLocalDate.Hour.ToString()) != false; var isDayExcluded = exception.DaysOfTheMonth?.Split(',').Contains(userLocalDate.Day.ToString()) != false; var isMonthExcluded = exception.Months?.Split(',').Contains(userLocalDate.ToString("MMMM").ToLower()) != false; var isYearExcluded = exception.Years?.Split(',').Contains(userLocalDate.Year.ToString()) != false; var isInRange = (exception.StartDate != null || exception.EndDate != null) && (exception.StartDate == null || userLocalDate >= exception.StartDate?.AddMinutes(timeZoneShift)) && (exception.EndDate == null || userLocalDate <= exception.EndDate?.AddMinutes(timeZoneShift)); var isWeekDayExcluded = true; if (exception.DayOccurrences == null) { isWeekDayExcluded = exception.WeekDays?.Split(',').Contains(userLocalDate.ToString("dddd").ToLower()) != false; } else { var occurrences = exception.DayOccurrences?.Split(',') .Select(e => (RecurrenceRuleException.MonthlyDayOccurrenceEnum) RecurrenceRuleException.Enums.GetValue(RecurrenceRuleException.Fields.MonthlyDayOccurrence, e.ToTitleCase())).ToArray(); if (exception.WeekDays == null) { if (occurrences.Contains(RecurrenceRuleException.MonthlyDayOccurrenceEnum.Last)) { isWeekDayExcluded = userLocalDate.Day == DateTime.DaysInMonth(userLocalDate.Year, userLocalDate.Month); } } else { log.LogLine(); var daysOfWeek = exception.WeekDays?.Split(',') .Select(e => (RecurrenceRule.WeekDayEnum) RecurrenceRule.Enums.GetValue(RecurrenceRule.Fields.WeekDay, e.ToTitleCase())) .ToArray(); if (daysOfWeek.Any()) { var isFound = false; for (var index = 0; index < daysOfWeek.Length && !isFound; index++) { var dayOfWeek = daysOfWeek[index]; for (var i = 0; i < occurrences.Length && !isFound; i++) { var occurrence = occurrences[i]; var dateTimeDayOfWeek = GetDayOfWeek(dayOfWeek); var isLastOccurrence = occurrence == RecurrenceRuleException.MonthlyDayOccurrenceEnum.Last; var occurrenceDate = DateTimeHelpers.GetDayOccurrenceOfMonth(userLocalDate, dateTimeDayOfWeek, (int)occurrence, isLastOccurrence); isFound = isWeekDayExcluded = userLocalDate.Day == occurrenceDate?.Day; } } } } } if (isInRange || (isMinuteExcluded && isHourExcluded && isDayExcluded && isWeekDayExcluded && isMonthExcluded && isYearExcluded)) { return(true); } log.Log($"ID: {exception.Id}", LogLevel.Debug); if (exception.Minutes != null) { log.Log($"Minutes: {exception.Minutes}", LogLevel.Debug); } log.Log($"Minute Excluded: {isMinuteExcluded}", LogLevel.Debug); if (exception.Hours != null) { log.Log($"Hours: {exception.Hours}", LogLevel.Debug); log.Log($"Hour Excluded: {isHourExcluded}", LogLevel.Debug); } if (exception.DaysOfTheMonth != null) { log.Log($"Days of the month: {exception.DaysOfTheMonth}", LogLevel.Debug); } log.Log($"Day Excluded: {isDayExcluded}", LogLevel.Debug); if (exception.WeekDays != null) { log.Log($"Week days: {exception.WeekDays}", LogLevel.Debug); } log.Log($"Week day Excluded: {isWeekDayExcluded}", LogLevel.Debug); if (exception.Months != null) { log.Log($"Months: {exception.Months}", LogLevel.Debug); } log.Log($"Month Excluded: {isMonthExcluded}", LogLevel.Debug); if (exception.Years != null) { log.Log($"Years: {exception.Years}", LogLevel.Debug); } log.Log($"Year Excluded: {isYearExcluded}", LogLevel.Debug); log.Log($"Target Date: {utcDate}", LogLevel.Debug); log.Log($"Start date: {exception.StartDate} UTC", LogLevel.Debug); log.Log($"End date: {exception.EndDate} UTC", LogLevel.Debug); log.Log($"Is in exclusion range: {isInRange}", LogLevel.Debug); } return(false); }
private DoNotCallByCustomerEntity MapCustomerEntity <T>(T request, DoNotCallInterfaceValidateResult validateResult) where T : DoNotCallTransactionInput { DateTime now = DateTime.Now; _commonFacade = new CommonFacade(); string neverExpireDate = _commonFacade.GetCacheParamByName("DNC_NEVER_EXPIRE_DATE").ParamValue; DateTime nonExpireDate = DateTimeHelpers.ParseDateTime(neverExpireDate, "yyyy-MM-dd").Value; bool isActive = request.Status == Constants.DigitTrue; DateTime expireDate = isActive ? request.ExpiryDate.HasValue ? request.ExpiryDate.Value : now.Date.AddYears(1).Date : now.Date; // if inactive set expire date to today bool isBlockAllSalesProducts = validateResult.IsBlockAllSalesProducts; bool isBlockAllInfoProducts = validateResult.IsBlockAllInfoProducts; List <DoNotCallActivityProductInput> blockSalesProducts = isBlockAllSalesProducts ? new List <DoNotCallActivityProductInput>() : validateResult.ActivityProducts .Where(x => x.BlockType == Constants.ActivityProductTypeSales) .ToList(); List <DoNotCallActivityProductInput> blockInfoProducts = isBlockAllInfoProducts ? new List <DoNotCallActivityProductInput>() : validateResult.ActivityProducts .Where(x => x.BlockType == Constants.ActivityProductTypeInformation) .ToList(); // check user exists? _userFacade = new UserFacade(); UserEntity user = _userFacade.GetUserByLogin(request.UpdateUser) ?? new UserEntity { UserId = 0, Username = request.UpdateUser }; var entity = new DoNotCallByCustomerEntity { CurrentUserId = user.UserId, CurrentUsername = user.Username, CurrentUserIpAddress = ApplicationHelpers.GetClientIP(), BasicInfo = new DoNotCallBasicInfoModel { FirstName = request.FirstName, LastName = request.LastName, TransactionId = validateResult.TransactionId ?? 0, EffectiveDate = now.Date, CreateDate = now, UpdateDate = now, IsNeverExpire = expireDate.Date == nonExpireDate.Date, ExpireDate = expireDate, FromSystem = request.SystemCode, IsActive = isActive, Remark = request.Remark }, CardInfo = new DoNotCallCardInfoModel { CardNo = request.CardNo, SubscriptionTypeId = validateResult.SubscriptionTypeId.Value }, ContactDetail = new DoNotCallContactModel { Email = new DoNotCallEmail { EmailList = request.EmailList?.Select(email => new DoNotCallEmailModel { Email = email.Email, Id = email.Id.HasValue? email.Id.Value: 0, IsDeleted = email.IsActive == Constants.FlagN, LastUpdateDate = now }).ToList() ?? new List <DoNotCallEmailModel>() }, Telephone = new DoNotCallTelephone { TelephoneList = request.TelephoneList?.Select(phoneNo => new DoNotCallTelephoneModel { PhoneNo = phoneNo.PhoneNo, Id = phoneNo.Id.HasValue? phoneNo.Id.Value: 0, IsDeleted = phoneNo.IsActive == Constants.FlagN, LastUpdateDate = now }).ToList() ?? new List <DoNotCallTelephoneModel>() } }, BlockSales = new DoNotCallBlockSalesModel { IsBlockAllSalesProducts = isBlockAllSalesProducts, IsBlockSalesEmail = request.SalesBlockInfo.BlockEmail == Constants.DigitTrue, IsBlockSalesSms = request.SalesBlockInfo.BlockSMS == Constants.DigitTrue, IsBlockSalesTelephone = request.SalesBlockInfo.BlockTelephone == Constants.DigitTrue, BlockSalesProductList = blockSalesProducts.Select(product => new DoNotCallProductModel { ActivityProductType = Constants.ActivityProductTypeSales, CreateDate = now, IsDeleted = product.IsActive == Constants.FlagN, Id = product.ProductId.Value, ActivityProductId = product.ActivityProductId, ProductId = product.ProductId.HasValue ? product.ProductId.Value: 0, UpdateDate = now }).ToList() ?? new List <DoNotCallProductModel>() }, BlockInformation = new DoNotCallBlockInformationModel { IsBlockAllInfoProducts = isBlockAllInfoProducts, IsBlockInfoEmail = request.InformationBlockInfo.BlockEmail == Constants.DigitTrue, IsBlockInfoSms = request.InformationBlockInfo.BlockSMS == Constants.DigitTrue, IsBlockInfoTelephone = request.InformationBlockInfo.BlockTelephone == Constants.DigitTrue, BlockInfoProductList = blockInfoProducts.Select(product => new DoNotCallProductModel { ActivityProductType = Constants.ActivityProductTypeInformation, CreateDate = now, IsDeleted = product.IsActive == Constants.FlagN, Id = product.ProductId.Value, ActivityProductId = product.ActivityProductId, ProductId = product.ProductId.HasValue ? product.ProductId.Value: 0, UpdateDate = now }).ToList() ?? new List <DoNotCallProductModel>() } }; return(entity); }
public DateTime?[] GetNextWeekValues(CalendarItem item, DateTime currentDate) { DateTime?[] dates = new DateTime?[7]; if (item.Sunday) { dates[0] = DateTimeHelpers.GetNextWeekday(currentDate, DayOfWeek.Sunday); } else { dates[0] = null; } if (item.Monday) { dates[1] = DateTimeHelpers.GetNextWeekday(currentDate, DayOfWeek.Monday); } else { dates[1] = null; } if (item.Tuesday) { dates[2] = DateTimeHelpers.GetNextWeekday(currentDate, DayOfWeek.Tuesday); } else { dates[2] = null; } if (item.Wednesday) { dates[3] = DateTimeHelpers.GetNextWeekday(currentDate, DayOfWeek.Wednesday); } else { dates[3] = null; } if (item.Thursday) { dates[4] = DateTimeHelpers.GetNextWeekday(currentDate, DayOfWeek.Thursday); } else { dates[4] = null; } if (item.Friday) { dates[5] = DateTimeHelpers.GetNextWeekday(currentDate, DayOfWeek.Friday); } else { dates[5] = null; } if (item.Saturday) { dates[6] = DateTimeHelpers.GetNextWeekday(currentDate, DayOfWeek.Saturday); } else { dates[6] = null; } return(dates); }