/// <summary>
        /// A helper method to retreive all time information for the input intra day filters
        /// </summary>
        /// <param name="intraDayFilters">List of intra day filters</param>
        /// <returns>List of instances of IntraDayDetails</returns>
        public async Task <List <IntraDayDetails> > GetTimeDetails(List <IntraDayFilter> intraDayFilters)
        {
            List <IntraDayDetails> selectedTimes = new List <IntraDayDetails>();
            var timezones = await _timezoneRepository.GetTimezones();

            intraDayFilters.ForEach(intraDayFilter =>
            {
                var timeDetails = (from t in timezones
                                   where (!intraDayFilter.Include.Any() || intraDayFilter.Include.Contains(t.TimezoneId)) &&
                                   (!intraDayFilter.Exclude.Any() || !intraDayFilter.Exclude.Contains(t.TimezoneId))
                                   select new IntraDayDetails
                {
                    TimezoneId = t.TimezoneId,
                    CurrentDate = DateTime.UtcNow.Add(TimezoneHelper.GetOffset(t.Abbreviation).Value).Date,
                    CurrentDateTime = DateTime.UtcNow.Add(TimezoneHelper.GetOffset(t.Abbreviation).Value),
                    StartDate = DateTime.UtcNow.Add(TimezoneHelper.GetOffset(t.Abbreviation).Value).Date.AddDays(intraDayFilter.RelativeStartDay),
                    EndDate = DateTime.UtcNow.Add(TimezoneHelper.GetOffset(t.Abbreviation).Value).Date.AddDays(intraDayFilter.RelativeEndDay),
                    RecentlyUpdatedInDays = intraDayFilter.PickRecentlyUpdatedInDays
                }).ToList();

                if (timeDetails.Any())
                {
                    selectedTimes.AddRange(timeDetails);
                }
            });
            return(selectedTimes);
        }
Exemple #2
0
        public void AllWindowsTimezonesShouldBeConvertableToIana()
        {
            var allTimezones = TimeZoneInfo.GetSystemTimeZones();

            Should.NotThrow(() =>
            {
                var exceptions = new List <string>();

                foreach (var timezone in allTimezones)
                {
                    try
                    {
                        TimezoneHelper.WindowsToIana(timezone.Id);
                    }
                    catch (Exception ex)
                    {
                        exceptions.Add(ex.Message);
                    }
                }

                if (exceptions.Any())
                {
                    throw new Exception(exceptions.JoinAsString(Environment.NewLine));
                }
            });
        }
        public async Task <IActionResult> SendPost([FromRoute] int id, [FromForm, Bind(nameof(PostsSendViewModel.ChannelId), nameof(PostsSendViewModel.Schedule), nameof(PostsSendViewModel.ScheduleDate))] PostsSendViewModel model)
        {
            if (model.Schedule && model.ScheduleDate.HasValue)
            {
                model.ScheduleDate = TimezoneHelper.ConvertTimeToUtcByIanaTimeZoneId(
                    DateTime.SpecifyKind(model.ScheduleDate.Value, DateTimeKind.Unspecified),
                    TimezoneHelper.WindowsToIana(
                        await SettingManager.GetSettingValueAsync(TimingSettingNames.TimeZone)));

                await _scheduleService.Create(new ScheduleItemDto {
                    PostId       = id,
                    ChannelId    = model.ChannelId,
                    ScheduleDate = model.ScheduleDate.Value
                });

                return(RedirectToAction(nameof(Index)));
            }
            var post = await _postApplicationService.GetById(id);

            if (post == null)
            {
                return(NotFound());
            }
            var channel = await _channelApplicationService.Get(new EntityDto <long>(model.ChannelId));

            if (channel == null)
            {
                return(NotFound());
            }
            await _bot.Client.SendTextMessageAsync(new ChatId(channel.Id), post.Body);

            return(RedirectToAction(nameof(Index)));
        }
 public void Should_Throw_Exception_For_Unknown_Windows_Timezone_Id()
 {
     Should.Throw <Exception>(() =>
     {
         TimezoneHelper.WindowsToIana("abc");
     });
 }
Exemple #5
0
        public void ConvertByIanaTimezoneShouldBeConvertByWindowsTimezone()
        {
            var now = DateTime.UtcNow;

            TimezoneHelper.ConvertTimeFromUtcByIanaTimeZoneId(now, "Asia/Shanghai")
            .ShouldBe(TimezoneHelper.ConvertFromUtc(now, "China Standard Time"));
        }
Exemple #6
0
 public void ShouldThrowExceptionForUnknownIanaTimezoneId()
 {
     Should.Throw <Exception>(() =>
     {
         TimezoneHelper.IanaToWindows("cba");
     });
 }
        /// <summary>
        /// A helper method to retreive all time information for the input span filters
        /// </summary>
        /// <param name="spanFilters">List of span filters</param>
        /// <returns>List of instances of SpanDetails</returns>
        public async Task <List <SpanDetails> > GetTimeDetails(List <SpanFilter> spanFilters)
        {
            List <SpanDetails> selectedTimes = new List <SpanDetails>();
            var timezones = await _timezoneRepository.GetTimezones();

            spanFilters.ForEach(spanFilter =>
            {
                var timeDetails = (from t in timezones
                                   where DateTime.UtcNow.Add(TimezoneHelper.GetOffset(t.Abbreviation).Value).TimeOfDay >= spanFilter.Start &&
                                   DateTime.UtcNow.Add(TimezoneHelper.GetOffset(t.Abbreviation).Value).TimeOfDay < spanFilter.End &&
                                   (!spanFilter.Include.Any() || spanFilter.Include.Contains(t.TimezoneId)) &&
                                   (!spanFilter.Exclude.Any() || !spanFilter.Exclude.Contains(t.TimezoneId))
                                   select new SpanDetails
                {
                    Days = spanFilter.DaysOfData,
                    CurrentDate = DateTime.UtcNow.Add(TimezoneHelper.GetOffset(t.Abbreviation).Value).Date,
                    CurrentDateTime = DateTime.UtcNow.Add(TimezoneHelper.GetOffset(t.Abbreviation).Value),
                    TimezoneId = t.TimezoneId
                }).ToList();

                if (timeDetails.Any())
                {
                    selectedTimes.AddRange(timeDetails);
                }
            });

            return(selectedTimes);
        }
 public void Should_Throw_Exception_For_Unknown_Iana_Timezone_Id()
 {
     Should.Throw <Exception>(() =>
     {
         TimezoneHelper.IanaToWindows("cba");
     });
 }
Exemple #9
0
 public void ShouldThrowExceptionForUnknownWindowsTimezoneId()
 {
     Should.Throw <Exception>(() =>
     {
         TimezoneHelper.WindowsToIana("abc");
     });
 }
Exemple #10
0
        public static async Task <string> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage Request, TraceWriter log, ExecutionContext context)
        {
            try
            {
                // Get request body
                dynamic requestData = await Request.Content.ReadAsAsync <object>();

                //var objectIdentifier = data.userContext.Principal.FindFirst(ObjectIdentifierType).Value;
                Helpers.HelperMethods helperMethods  = new Helpers.HelperMethods(context);
                TimezoneHelper        timezoneHelper = new TimezoneHelper(helperMethods.getTimeTrackerOptions());
                var    editedHours    = requestData.data;
                string userIdentifier = Request.Headers.Authorization.Parameter.ToString();

                WorkHours           workHours           = editedHours.ToObject <WorkHours>();
                WorkHoursRepository workHoursRepository = helperMethods.GetWorkHoursRepository(userIdentifier);
                await workHoursRepository.SaveItemAsync(workHours);

                return("Procesed");
            }
            catch (Exception ex)
            {
                string message = ex.InnerException != null?ex.InnerException.ToString() : ex.Message;

                log.Info(message + " occurred in SaveHoursByDate : " + DateTime.Now);
                return(message);
            }
        }
 public List <NameValueDto> GetWindowsTimezones()
 {
     return(TimezoneHelper.GetWindowsTimeZoneInfos().OrderBy(tz => tz.BaseUtcOffset)
            .Select(tz => new NameValueDto
     {
         Value = tz.Id,
         Name = tz.DisplayName
     }).ToList());
 }
 public TimerHoursService(
     ILogger <TimerHoursService> logger,
     ITimerHoursRepository timerHoursRepository,
     TimezoneHelper timezoneHelper)
 {
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
     _timerhoursRepository = timerHoursRepository ?? throw new ArgumentNullException(nameof(timerHoursRepository));
     _timezoneHelper       = timezoneHelper ?? throw new ArgumentNullException(nameof(timezoneHelper));
 }
Exemple #13
0
        public void ConvertToDateTimeOffset_Date_With_America_NewYork_TimeZone_Should_Return_Correct_DateTimeOffset()
        {
            var testDate = new DateTime(1980, 11, 20);
            var timeSpan = new TimeSpan(-5, 0, 0);

            DateTimeOffset?dateTimeOffset = TimezoneHelper.ConvertToDateTimeOffset(testDate, "America/New_York");

            dateTimeOffset.ShouldNotBe(null);
            dateTimeOffset.Value.Offset.ShouldBe(timeSpan);
            dateTimeOffset.Value.DateTime.ShouldBe(testDate);
        }
        public void ConvertToDateTimeOffset_Date_With_America_NewYork_TimeZone_Should_Return_Correct_DateTimeOffset_With_DaylightSavings()
        {
            var testDate = new DateTime(1980, 5, 20);
            var timeSpan = new TimeSpan(-4, 0, 0);

            var dateTimeOffset = TimezoneHelper.ConvertToDateTimeOffset(testDate, "America/New_York");

            dateTimeOffset.ShouldNotBeNull();
            dateTimeOffset.Offset.ShouldBe(timeSpan);
            dateTimeOffset.DateTime.ShouldBe(testDate);
        }
 /// <summary>
 /// Constructor
 /// </summary>
 public GraphCalendarService(
     IGraphAuthProvider authProvider,
     IUserContext userContext,
     ILogger <GraphCalendarService> logger,
     IOptionsSnapshot <TimeTrackerOptions> timeTrackerOptions,
     TimezoneHelper timezoneHelper) : base(authProvider, userContext)
 {
     _logger             = logger ?? throw new ArgumentNullException(nameof(logger));
     _timeTrackerOptions = timeTrackerOptions.Value ?? throw new ArgumentNullException(nameof(timeTrackerOptions));
     _timezoneHelper     = timezoneHelper;
 }
Exemple #16
0
 /// <summary>
 /// Constructor
 /// </summary>
 public GraphAppCalendarService(
     IGraphAuthProvider authProvider,
     IUserContext userContext,
     // ILogger<GraphAppCalendarService> logger,
     TimeTrackerOptions timeTrackerOptions,
     TimezoneHelper timezoneHelper, string userObjectIdentifier) : base(authProvider, userContext)
 {
     //_logger = logger ?? throw new ArgumentNullException(nameof(logger));
     _timeTrackerOptions   = timeTrackerOptions ?? throw new ArgumentNullException(nameof(timeTrackerOptions));
     _timezoneHelper       = timezoneHelper;
     _userObjectIdentifier = userObjectIdentifier;
 }
        public void All_Windows_Timezones_Should_Be_Convertable_To_Iana()
        {
            var allTimezones = TimeZoneInfo.GetSystemTimeZones();

            foreach (var timezone in allTimezones)
            {
                Should.NotThrow(() =>
                {
                    TimezoneHelper.WindowsToIana(timezone.Id);
                });
            }
        }
        public async Task SetUserTimezone(CommandContext context, string timezoneName)
        {
            var timezone = TimezoneHelper.Find(timezoneName);

            if (timezone != null)
            {
                var now = Instant.FromDateTimeUtc(DateTime.UtcNow);
                this._repository.SetUserTimezone(context.User.Id, timezone);
                await context.RespondAsync($"Saved {timezone.Id}: {timezone.GetUtcOffset(now).ToTimeSpan()}");
            }
            else
            {
                await context.RespondAsync("Use a timezone from this list: <https://en.wikipedia.org/wiki/List_of_tz_database_time_zones>");
            }
            return;
        }
        private async Task <string> GetUsersTimezoneScriptsAsync()
        {
            var timezoneId = await _settingManager.GetSettingValueAsync(TimingSettingNames.TimeZone);

            var timezone = TimeZoneInfo.FindSystemTimeZoneById(timezoneId);

            return(" {" +
                   "        windows: {" +
                   "            timeZoneId: '" + timezoneId + "'," +
                   "            baseUtcOffsetInMilliseconds: '" + timezone.BaseUtcOffset.TotalMilliseconds + "'," +
                   "            currentUtcOffsetInMilliseconds: '" + timezone.GetUtcOffset(Clock.Now).TotalMilliseconds + "'," +
                   "            isDaylightSavingTimeNow: '" + timezone.IsDaylightSavingTime(Clock.Now) + "'" +
                   "        }," +
                   "        iana: {" +
                   "            timeZoneId:'" + TimezoneHelper.WindowsToIana(timezoneId) + "'" +
                   "        }," +
                   "    }");
        }
        public void ConvertToDateTimeOffset_Dates_With_America_Phoenix_TimeZone_Should_Return_Correct_DateTimeOffsests_With_No_DaylightSavings()
        {
            var testDate = new DateTime(1980, 5, 20);
            var timeSpan = new TimeSpan(-7, 0, 0);

            var dateTimeOffset = TimezoneHelper.ConvertToDateTimeOffset(testDate, "America/Phoenix");

            dateTimeOffset.ShouldNotBeNull();
            dateTimeOffset.Offset.ShouldBe(timeSpan);
            dateTimeOffset.DateTime.ShouldBe(testDate);

            var testDate2 = new DateTime(1980, 11, 20);

            var dateTimeOffset2 = TimezoneHelper.ConvertToDateTimeOffset(testDate2, "America/Phoenix");

            dateTimeOffset2.ShouldNotBeNull();
            dateTimeOffset2.Offset.ShouldBe(timeSpan); // should be the same timespan as previous date
            dateTimeOffset2.DateTime.ShouldBe(testDate2);
        }
Exemple #21
0
        public static DateTime?ConvertForUtcUsingUserConfiguration(DateTime?date)
        {
            if (!date.HasValue)
            {
                return(null);
            }

            var applicationContext = DependencyResolver.Resolve <IApplicationContext>();

            if (applicationContext.Configuration.Clock.Provider != "utcClockProvider")
            {
                return(date);
            }

            if (applicationContext.Configuration.Timing.TimeZoneInfo?.Windows?.TimeZoneId == null)
            {
                return(date);
            }

            return(TimezoneHelper.ConvertFromUtc(date.Value.ToUniversalTime(), applicationContext.Configuration.Timing.TimeZoneInfo.Windows.TimeZoneId));
        }
        public async Task ConvertTime(
            CommandContext context,
            [Description("Name of the timezone")]
            string timezoneName
            )
        {
            var timezone = TimezoneHelper.Find(timezoneName);

            if (timezone == null)
            {
                return;
            }

            var zonedDateTime = Instant.FromDateTimeUtc(DateTime.UtcNow).InZone(timezone);
            var embed         = new DiscordEmbedBuilder()
                                .WithColor(DiscordColor.None)
                                .WithFooter($"Current time: {zonedDateTime:yyyy-MM-dd HH:mm} {timezone.Id}")
                                .WithTimestamp(zonedDateTime.ToDateTimeUtc())
                                .Build();

            await context.RespondAsync(embed : embed);
        }
 public WorkHoursRepository(
     // IOptions<TimeTrackerOptions> timeTrackerOptions,
     TimeTrackerOptions timeTrackerOptions,
     IUserContext userContext,
     GraphAppUserService graphUserService,
     GraphAppSharePointService graphSharePointService,
     GraphAppCalendarService graphCalendarService,
     GraphAppTasksService graphTasksService,
     GraphAppMailService graphMailService,
     TimezoneHelper timezoneHelper,
     String objectIdentifier
     )
 {
     _timeTrackerOptions     = timeTrackerOptions ?? throw new ArgumentNullException(nameof(timeTrackerOptions));
     _userContext            = userContext ?? throw new ArgumentNullException(nameof(userContext));
     _graphUserService       = graphUserService ?? throw new ArgumentNullException(nameof(graphUserService));
     _graphSharePointService = graphSharePointService ?? throw new ArgumentNullException(nameof(graphSharePointService));
     _graphCalendarService   = graphCalendarService ?? throw new ArgumentNullException(nameof(graphCalendarService));
     _graphTasksService      = graphTasksService ?? throw new ArgumentNullException(nameof(graphTasksService));
     _graphMailService       = graphMailService ?? throw new ArgumentNullException(nameof(graphMailService));
     this.timezoneHelper     = timezoneHelper ?? throw new ArgumentNullException(nameof(timezoneHelper));
     _objectIdentifier       = objectIdentifier;      //?? throw new ArgumentNullException(nameof(userContext));
 }
        public async Task ConvertTime(CommandContext context,
                                      [Description("Time (or date and time) you want to convert.")]
                                      DateTime datetime,
                                      [Description("Name of the timezone.")]
                                      string timezoneName
                                      )
        {
            var timezone = TimezoneHelper.Find(timezoneName);

            if (timezone == null)
            {
                return;
            }

            var zonedDateTime = datetime.InTimeZone(timezone);
            await context.RespondAsync(
                embed : new DiscordEmbedBuilder()
                .WithColor(DiscordColor.None)
                .WithFooter($"{zonedDateTime:yyyy-MM-dd HH:mm} {timezone.Id} in your local time:")
                .WithTimestamp(zonedDateTime.ToDateTimeUtc())
                .Build()
                );
        }
Exemple #25
0
        private async Task <UserTimingConfigDto> GetUserTimingConfig()
        {
            var timezoneId = await _settingManager.GetSettingValueAsync(TimingSettingNames.TimeZone);

            var timezone = TimeZoneInfo.FindSystemTimeZoneById(timezoneId);

            return(new UserTimingConfigDto
            {
                TimeZoneInfo = new UserTimeZoneConfigDto
                {
                    Windows = new UserWindowsTimeZoneConfigDto
                    {
                        TimeZoneId = timezoneId,
                        BaseUtcOffsetInMilliseconds = timezone.BaseUtcOffset.TotalMilliseconds,
                        CurrentUtcOffsetInMilliseconds = timezone.GetUtcOffset(Clock.Now).TotalMilliseconds,
                        IsDaylightSavingTimeNow = timezone.IsDaylightSavingTime(Clock.Now)
                    },
                    Iana = new UserIanaTimeZoneConfigDto
                    {
                        TimeZoneId = TimezoneHelper.WindowsToIana(timezoneId)
                    }
                }
            });
        }
        private TimeSeriesPoint ParseExcelRow(DataRow row)
        {
            Instant?      time       = null;
            double?       value      = null;
            int?          gradeCode  = null;
            List <string> qualifiers = null;
            DateTimeZone  zone       = null;

            if (!string.IsNullOrEmpty(Context.CsvComment) && ((row[0] as string)?.StartsWith(Context.CsvComment) ?? false))
            {
                return(null);
            }

            try
            {
                ParseExcelStringColumn(row, Context.CsvTimezoneField?.ColumnIndex, text =>
                {
                    if (Context.TimezoneAliases.TryGetValue(text, out var alias))
                    {
                        text = alias;
                    }

                    TimezoneHelper.TryParseDateTimeZone(text, out zone);
                });

                if (Context.CsvDateOnlyField != null)
                {
                    var dateOnly = DateTime.MinValue;
                    var timeOnly = DefaultTimeOfDay;

                    ParseExcelColumn <DateTime>(row, Context.CsvDateOnlyField.ColumnIndex, dateTime => dateOnly = dateTime.Date);

                    if (Context.CsvTimeOnlyField != null)
                    {
                        ParseExcelColumn <DateTime>(row, Context.CsvTimeOnlyField.ColumnIndex, dateTime => timeOnly = dateTime.TimeOfDay);
                    }

                    time = InstantFromDateTime(dateOnly.Add(timeOnly), () => zone);
                }
                else
                {
                    ParseExcelColumn <DateTime>(row, Context.CsvDateTimeField.ColumnIndex, dateTime => time = InstantFromDateTime(dateTime, () => zone));
                }

                if (string.IsNullOrEmpty(Context.CsvNanValue))
                {
                    ParseExcelColumn <double>(row, Context.CsvValueField.ColumnIndex, number => value = number);
                }
                else
                {
                    // Detecting the NaN value is a bit more tricky.
                    // The column might have been converted as a pure string like "NA" or it could be a double like -9999.0
                    ParseValidExcelColumn(row, Context.CsvValueField.ColumnIndex, item =>
                    {
                        if (!(item is string itemText))
                        {
                            itemText = Convert.ToString(item);
                        }

                        if (Context.CsvNanValue == itemText)
                        {
                            return;
                        }

                        if (item is double number)
                        {
                            value = number;
                        }
                    });
                }
        public async Task <IEnumerable <WorkHours> > ComputeHours(
            DateTime date, IEnumerable <GraphResultItem> results,
            SiteList siteList,
            string userObjectIdentifier,
            TimeTrackerOptions timeTrackerOptions,
            GraphAppSharePointService graphSharePointService,
            GraphAppCalendarService graphCalendarService,
            GraphAppTasksService graphTasksService,
            GraphAppMailService graphMailService,
            TimezoneHelper timezoneHelper,
            List <string> categoryFilter,
            List <string> showAsFilter,
            int allDayCountHours)
        {
            try
            {
                var workHoursList = new List <WorkHours>();

                // Create a variable to track last day retrieved from SharePoint
                var lastDay = new DateTime(date.Year, date.Month, 1);

                foreach (var item in results)
                {
                    var workHoursFields = ConvertToWorkHours(item, userObjectIdentifier);

                    lastDay = DateTime.ParseExact(workHoursFields.Date, "yyyyMMdd", CultureInfo.InvariantCulture);

                    workHoursList.Add(new WorkHours
                    {
                        Id     = item.Id,
                        Fields = workHoursFields
                    });
                }

                // WorkHours Compute Logic
                //
                // New Logic - retrieve 1 week at a time then pause & repeat.
                // Create Arrays[] to hold partial results.
                // Calculate:   1. BeginDate = beginning of Month
                //              2. EndOfWeek - BeginDate +7 days
                //                  (if EndOfWeek => Now, EndOfWeek = Now, finishWeeks = true)
                //              3. BeginDate = EndOfWeek date +1
                //              4. if !(finishWeeks), pause - to avoid throttling
                //              5. Repeat 2-4.

                var  fullCalendar  = new List <GraphResultItem>();
                var  fullMail      = new List <GraphResultItem>();
                var  fullTaskItems = new List <JToken>();
                bool finishWeeks   = false;

                // Add remaining days till today for calendar
                var endOfMonth = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));

                if (lastDay.Date != endOfMonth.Date)
                {
                    // Ensure we only calculate until today
                    if (DateTime.Now.Month == date.Month && endOfMonth > DateTime.Now)
                    {
                        endOfMonth = DateTime.Now;
                    }
                    endOfMonth = new DateTime(endOfMonth.Year, endOfMonth.Month, endOfMonth.Day, 23, 59, 59, 999);

                    // Skip lastDay TODO: test when today is the first
                    if (endOfMonth.Date > lastDay.Date && lastDay.Day != 1)
                    {
                        lastDay = lastDay.AddDays(1);
                    }
                    lastDay = new DateTime(lastDay.Year, lastDay.Month, lastDay.Day, 0, 0, 0, 0);

                    // Get calendar items
                    //var calendarResults = await graphCalendarService.GetCalendarEventsAsync(lastDay, endOfMonth);
                    var taskCalendar     = Task.Run(() => graphCalendarService.GetCalendarEventsAsync(lastDay, endOfMonth));
                    var weeklyCalResults = await taskCalendar;
                    if (weeklyCalResults != null)
                    {
                        foreach (var item in weeklyCalResults)
                        {
                            fullCalendar.Add(item);
                        }
                    }

                    // Get Emails in inbox for count
                    //var emailResults = await graphMailService.GetMailItemsAsync(lastDay, endOfMonth);
                    var taskMail          = Task.Run(() => graphMailService.GetMailItemsAsync(lastDay, endOfMonth));
                    var weeklyMailResults = await taskMail;
                    if (weeklyMailResults != null)
                    {
                        foreach (var item in weeklyMailResults)
                        {
                            fullMail.Add(item);
                        }
                    }

                    // Get task items for count
                    //var tasksResults = await graphTasksService.GetUserTasksAsync(lastDay, endOfMonth);

                    // TODO:  Varma:  uncomment the following after ensuring app context is supported
                    //var taskTasksItems = Task.Run(() => graphTasksService.GetUserTasksAsync(lastDay, endOfMonth));
                    //var weeklyTaskItemsResults = await taskTasksItems;
                    //if (weeklyTaskItemsResults != null)
                    //{
                    //    foreach (var item in weeklyTaskItemsResults)
                    //    {
                    //        fullTaskItems.Add(item);
                    //    }
                    //}

                    // *** Loop Back and do more weeks *** //


                    // To track the day that is being calculated in the while
                    var dateToCalculate = lastDay;

                    while (dateToCalculate.Date <= endOfMonth.Date)
                    {
                        var workHoursFields = new WorkHoursFields
                        {
                            Date                   = dateToCalculate.ToString("yyyyMMdd"),
                            ObjectIdentifier       = userObjectIdentifier,
                            TeamHoursItemState     = ItemState.NotSubmitted,
                            ItemState              = ItemState.NotSubmitted,
                            AdjustedHoursReason    = "",
                            TeamHoursSubmittedDate = new DateTime(),
                            SubmittedDate          = new DateTime(),
                            MeetingHours           = 0,
                            MeetingMinutes         = 0,
                            EmailHours             = 0,
                            EmailMinutes           = 0,
                            OtherHours             = 0,
                            OtherMinutes           = 0,
                            OtherTimerHours        = 0,
                            OtherTimerMinutes      = 0,
                            EmailTimerHours        = 0,
                            EmailTimerMinutes      = 0,
                            MeetingTimerHours      = 0,
                            MeetingTimerMinutes    = 0
                        };

                        #region calendar items
                        // var calendarResults = await taskCalendar;

                        // Variables needed for calculating sum for calendar events
                        double totalTimeSpan = 0;
                        var    span          = TimeSpan.FromHours(0);

                        // Calculate time spent in calendar events ////////
                        if (fullCalendar != null)
                        {
                            // TODO: can refactor into a select type statement and remove foreach? var calendarEventsToSum = calendarResults.Select<>
                            foreach (var item in fullCalendar)
                            {
                                // Filter out rules
                                var includeItem = true;
                                var categories  = (List <string>)item.Properties["Categories"];
                                foreach (var value in categories)
                                {
                                    if (categoryFilter.Contains(value))
                                    {
                                        includeItem = false;
                                    }
                                }

                                if (showAsFilter.Contains(item.Properties["ShowAs"].ToString()))
                                {
                                    includeItem = false;
                                }

                                if (includeItem && !Convert.ToBoolean(item.Properties["IsCancelled"]))
                                {
                                    if (Convert.ToBoolean(item.Properties["IsAllDay"]))
                                    {
                                        if (allDayCountHours > 0)
                                        {
                                            totalTimeSpan = totalTimeSpan + allDayCountHours;
                                        }
                                    }
                                    else
                                    {
                                        var startTime = Convert.ToDateTime(item.Properties["Start"]);
                                        var endTime   = Convert.ToDateTime(item.Properties["End"]);

                                        if (startTime.Date == dateToCalculate.Date)
                                        {
                                            span          = endTime.Subtract(startTime);
                                            totalTimeSpan = totalTimeSpan + span.TotalHours;
                                        }
                                    }
                                }
                            }

                            span = TimeSpan.FromHours(totalTimeSpan);

                            workHoursFields.MeetingHours   = Convert.ToInt16(span.Hours);
                            workHoursFields.MeetingMinutes = Convert.ToInt16(span.Minutes);
                        }

                        #endregion

                        #region mail items
                        // var emailResults = await taskMail;

                        // Variables needed for calculating counts of emails
                        var sentEmailCount     = 0;
                        var receivedEmailCount = 0;

                        // Calculate time spent in email //////////////
                        if (fullMail != null)
                        {
                            foreach (var item in fullMail)
                            {
                                // Filter out rules
                                var includeItem = true;
                                var categories  = (List <string>)item.Properties["Categories"];
                                foreach (var category in categories)
                                {
                                    if (categoryFilter.Contains(category))
                                    {
                                        includeItem = false;
                                    }
                                }

                                if (includeItem)
                                {
                                    if (Convert.ToDateTime(item.Properties["DateTime"]).Date == dateToCalculate.Date)
                                    {
                                        if (item.Properties["EmailType"].ToString() == "received")
                                        {
                                            if (Convert.ToBoolean(item.Properties["IsRead"]))
                                            {
                                                receivedEmailCount = receivedEmailCount + 1;
                                            }
                                        }
                                        else if (item.Properties["EmailType"].ToString() == "sent")
                                        {
                                            sentEmailCount = sentEmailCount + 1;
                                        }
                                    }
                                }
                            }

                            // Calculate total time in minutes
                            span = TimeSpan.FromMinutes((sentEmailCount * timeTrackerOptions.SentEmailTime) + (receivedEmailCount * timeTrackerOptions.ReceivedEmailTime));
                            workHoursFields.EmailHours   = Convert.ToInt16(span.Hours);
                            workHoursFields.EmailMinutes = Convert.ToInt16(span.Minutes);
                        }

                        #endregion

                        #region task items
                        // var tasksResults = await taskTasksItems;

                        // Variables needed for calculating counts of tasks
                        var tasksCount = 0;

                        if (fullTaskItems?.Count > 0)
                        {
                            // Initialize the Time Zone based on appSettings value.
                            var definedZone = timezoneHelper.timeZoneInfo;
                            // TODO: can refactor into a select type statement and remove foreach? var calendarEventsToSum = calendarResults.Select<>
                            foreach (var item in fullTaskItems)
                            {
                                var dateTime = DateTime.Parse(item["startDateTime"]["dateTime"].ToString());
                                // Adjust for TimeZone stored in appSettings.
                                var adjustedDateTime = TimeZoneInfo.ConvertTime(dateTime, definedZone);
                                if (adjustedDateTime.Date == dateToCalculate.Date)
                                {
                                    tasksCount = tasksCount + 1;
                                }
                            }

                            // Calculate total time in minutes
                            span = TimeSpan.FromMinutes(tasksCount * timeTrackerOptions.TaskTime);
                            workHoursFields.OtherHours   = Convert.ToInt16(span.Hours);
                            workHoursFields.OtherMinutes = Convert.ToInt16(span.Minutes);
                        }

                        #endregion

                        var workHours = new WorkHours
                        {
                            Id     = "",
                            Fields = workHoursFields
                        };

                        // Persist to SharePoint
                        if (dateToCalculate.Date < DateTime.Now.Date)
                        {
                            // Create JSON object
                            dynamic fieldsObject = new JObject();
                            fieldsObject.ObjectIdentifier       = workHoursFields.ObjectIdentifier;
                            fieldsObject.Date                   = workHoursFields.Date;
                            fieldsObject.MeetingHours           = workHoursFields.MeetingHours;
                            fieldsObject.MeetingMinutes         = workHoursFields.MeetingMinutes;
                            fieldsObject.MeetingAdjustedHours   = workHoursFields.MeetingAdjustedHours;
                            fieldsObject.MeetingAdjustedMinutes = workHoursFields.MeetingAdjustedMinutes;
                            fieldsObject.EmailHours             = workHoursFields.EmailHours;
                            fieldsObject.EmailMinutes           = workHoursFields.EmailMinutes;
                            fieldsObject.EmailAdjustedHours     = workHoursFields.EmailAdjustedHours;
                            fieldsObject.EmailAdjustedMinutes   = workHoursFields.EmailAdjustedMinutes;
                            fieldsObject.OtherHours             = workHoursFields.OtherHours;
                            fieldsObject.OtherMinutes           = workHoursFields.OtherMinutes;
                            fieldsObject.OtherAdjustedHours     = workHoursFields.OtherAdjustedHours;
                            fieldsObject.OtherAdjustedMinutes   = workHoursFields.OtherAdjustedMinutes;
                            fieldsObject.AdjustedHoursReason    = workHoursFields.AdjustedHoursReason;
                            fieldsObject.TeamHoursItemState     = workHoursFields.TeamHoursItemState.ToString();
                            fieldsObject.ItemState              = workHoursFields.ItemState.ToString();
                            fieldsObject.MeetingTimerHours      = workHoursFields.MeetingTimerHours.ToString();
                            fieldsObject.MeetingTimerMinutes    = workHoursFields.MeetingTimerMinutes.ToString();
                            fieldsObject.EmailTimerHours        = workHoursFields.EmailTimerHours.ToString();
                            fieldsObject.EmailTimerMinutes      = workHoursFields.EmailTimerMinutes.ToString();
                            fieldsObject.OtherTimerHours        = workHoursFields.OtherTimerHours.ToString();
                            fieldsObject.OtherTimerMinutes      = workHoursFields.OtherTimerMinutes.ToString();


                            dynamic jsonObject = new JObject();
                            jsonObject.fields = fieldsObject;

                            // Call graph to create the item in the SHarePoint List
                            var saveResults = await graphSharePointService.CreateSiteListItemAsync(siteList, jsonObject.ToString());

                            workHours.Id = saveResults;
                            workHoursList.Add(workHours);
                        }


                        dateToCalculate = dateToCalculate.AddDays(1);
                    }
                }

                return(workHoursList);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemple #28
0
        private TimeSeriesPoint ConvertRowToPoint(DataRow row)
        {
            Instant?      time       = null;
            double?       value      = null;
            int?          gradeCode  = null;
            List <string> qualifiers = null;
            DateTimeZone  zone       = null;

            ParseNullableColumn <string>(row, Context.CsvTimezoneField?.ColumnIndex, text =>
            {
                if (Context.TimezoneAliases.TryGetValue(text, out var alias))
                {
                    text = alias;
                }

                TimezoneHelper.TryParseDateTimeZone(text, out zone);
            });

            if (Context.CsvDateOnlyField != null)
            {
                var dateOnly = DateTime.MinValue;
                var timeOnly = DefaultTimeOfDay;

                ParseColumn <DateTime>(row, Context.CsvDateOnlyField.ColumnIndex, dateTime => dateOnly = dateTime.Date);

                if (Context.CsvTimeOnlyField != null)
                {
                    ParseColumn <DateTime>(row, Context.CsvDateOnlyField.ColumnIndex, dateTime => timeOnly = dateTime.TimeOfDay);
                }

                time = InstantFromDateTime(dateOnly.Add(timeOnly), () => zone);
            }
            else
            {
                ParseColumn <DateTime>(row, Context.CsvDateTimeField.ColumnIndex, dateTime => time = InstantFromDateTime(dateTime));
            }

            ParseColumn <double>(row, Context.CsvValueField.ColumnIndex, number => value = number);

            ParseColumn <int>(row, Context.CsvGradeField?.ColumnIndex, grade => gradeCode = grade);

            ParseNullableColumn <string>(row, Context.CsvQualifiersField?.ColumnIndex, text => qualifiers = QualifiersParser.Parse(text));

            if (time == null)
            {
                return(null);
            }

            ParseNullableColumn <string>(row, Context.CsvNotesField?.ColumnIndex, text =>
            {
                if (time.HasValue)
                {
                    AddRowNote(time.Value, text);
                }
            });

            return(new TimeSeriesPoint
            {
                Time = time,
                Value = value,
                GradeCode = gradeCode,
                Qualifiers = qualifiers
            });
        }
Exemple #29
0
 public void WindowsTimezoneIdToIanaTests(string windowsTimezoneId, string ianaTimezoneId)
 {
     TimezoneHelper.WindowsToIana(windowsTimezoneId).ShouldBe(ianaTimezoneId);
 }
Exemple #30
0
 public void IanaTimezoneIdToWindowsTests(string ianaTimezoneId, string windowsTimezoneId)
 {
     TimezoneHelper.IanaToWindows(ianaTimezoneId).ShouldBe(windowsTimezoneId);
 }