예제 #1
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = StartUtc.GetHashCode();
         hashCode = (hashCode * 397) ^ EndUtc.GetHashCode();
         hashCode = (hashCode * 397) ^ (DateRangeType != null ? DateRangeType.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (DesignUid != null ? DesignUid.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (DesignFileName != null ? DesignFileName.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (ContributingMachines != null ? ContributingMachines.GetListHashCode() : 397);
         hashCode = (hashCode * 397) ^ (OnMachineDesignId != null ? OnMachineDesignId.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (OnMachineDesignName != null ? OnMachineDesignName.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (ElevationType != null ? ElevationType.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (VibeStateOn != null ? VibeStateOn.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (PolygonUid != null ? PolygonUid.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (PolygonName != null ? PolygonName.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (PolygonLL != null ? PolygonLL.GetListHashCode() : 397);
         hashCode = (hashCode * 397) ^ (PolygonType != null ? PolygonType.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (ForwardDirection != null ? ForwardDirection.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (LayerNumber != null ? LayerNumber.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (AlignmentUid != null ? AlignmentUid.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (AlignmentFileName != null ? AlignmentFileName.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (StartStation != null ? StartStation.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (EndStation != null ? EndStation.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (LeftOffset != null ? LeftOffset.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (RightOffset != null ? RightOffset.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (AsAtDate != null ? AsAtDate.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (AutomaticsType != null ? AutomaticsType.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (TemperatureRangeMin != null ? TemperatureRangeMin.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (TemperatureRangeMax != null ? TemperatureRangeMax.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (PassCountRangeMin != null ? PassCountRangeMin.GetHashCode() : 397);
         hashCode = (hashCode * 397) ^ (PassCountRangeMax != null ? PassCountRangeMax.GetHashCode() : 397);
         return(hashCode);
     }
 }
예제 #2
0
 /// <summary>
 /// Returns the name of the stats table or view we need to query
 /// to satisfy the provided temporal aggregation and date range.
 /// </summary>
 public abstract string GetStatsTableName(
     string table,
     string joinTable,
     TemporalAggregation temporalAggregation,
     DateRangeType dateRangeType,
     DateTime?startDate,
     DateTime?endDate);
예제 #3
0
        public void Should_not_set_dates_based_on_DateRangeType_When_using_Custom(DateRangeType dateRangeType,
                                                                                  bool asAtDate)
        {
            var startUtc = dateRangeType == DateRangeType.Custom ? new DateTime(2017, 11, 5) : (DateTime?)null;
            var endUtc   = dateRangeType == DateRangeType.Custom ? new DateTime(2017, 11, 6) : (DateTime?)null;


            //Json deserialize interprets date as mm/dd/yyyy so format date that way
            var startUtcStr      = startUtc?.ToString("MM/dd/yyyy");
            var endUtcStr        = endUtc?.ToString("MM/dd/yyyy");
            var filterDescriptor = new FilterDescriptor
            {
                FilterJson =
                    $"{{\"dateRangeType\":\"{dateRangeType}\",\"asAtDate\":\"{asAtDate}\",\"startUTC\":\"{startUtcStr}\",\"endUTC\":\"{endUtcStr}\",\"elevationType\":null}}"
            };

            FilterJsonHelper.ParseFilterJson(
                new ProjectData {
                IanaTimeZone = "America/Los_Angeles", ProjectUID = _projectGuid.ToString()
            }, filterDescriptor,
                _mockedProductivity3dV2ProxyCompaction.Object, new HeaderDictionary());

            Abstractions.Models.Filter filterObj =
                JsonConvert.DeserializeObject <Abstractions.Models.Filter>(filterDescriptor.FilterJson);
            Assert.Equal(asAtDate ? MockedStartTime : startUtc, filterObj.StartUtc);
            Assert.Equal(endUtc, filterObj.EndUtc);
        }
예제 #4
0
        public void Should_return_project_extents_for_project_extents(DateRangeType dateRangeType, bool useNullDate)
        {
            var startUtc = useNullDate ? (DateTime?)null : new DateTime(2017, 11, 5);
            var endUtc   = useNullDate ? (DateTime?)null : new DateTime(2017, 11, 6);

            //Json deserialize interprets date as mm/dd/yyyy so format date that way
            var startUtcStr      = startUtc?.ToString("MM/dd/yyyy");
            var endUtcStr        = endUtc?.ToString("MM/dd/yyyy");
            var filterDescriptor = new FilterDescriptor
            {
                FilterJson =
                    $"{{\"dateRangeType\":\"{dateRangeType}\",\"asAtDate\":\"false\",\"startUTC\":\"{startUtcStr}\",\"endUTC\":\"{endUtcStr}\",\"elevationType\":null}}"
            };

            FilterJsonHelper.ParseFilterJson(
                new ProjectData {
                IanaTimeZone = "America/Los_Angeles", ProjectUID = _projectGuid.ToString()
            }, filterDescriptor,
                productivity3dV2ProxyCompaction: _mockedProductivity3dV2ProxyCompaction.Object, customHeaders: new HeaderDictionary());

            Abstractions.Models.Filter filterObj =
                JsonConvert.DeserializeObject <Abstractions.Models.Filter>(filterDescriptor.FilterJson);
            Assert.Equal(MockedStartTime, filterObj.StartUtc);
            Assert.Equal(_mockedEndTime, filterObj.EndUtc);
        }
예제 #5
0
        protected static Func <hcc_OrderTransactions, int> GetRangeFunction(DateRangeType rangeType)
        {
            Func <hcc_OrderTransactions, int> separationFunc;

            switch (rangeType)
            {
            case DateRangeType.AllDates:
                separationFunc = null;
                break;

            case DateRangeType.Today:
                separationFunc = ot => ot.Timestamp.Hour;
                break;

            case DateRangeType.ThisMonth:
                separationFunc = ot => ot.Timestamp.Day;
                break;

            case DateRangeType.YearToDate:
                separationFunc = ot => ot.Timestamp.Month;
                break;

            case DateRangeType.ThisWeek:
            default:
                separationFunc = ot => (int)ot.Timestamp.DayOfWeek;
                break;
            }

            return(separationFunc);
        }
예제 #6
0
        public async Task Should_not_set_dates_based_on_DateRangeType(DateRangeType dateRangeType, bool asAtDate)
        {
            var startUtc = dateRangeType == DateRangeType.Custom ? new DateTime(2017, 11, 5) : (DateTime?)null;
            var endUtc   = dateRangeType == DateRangeType.Custom ? new DateTime(2017, 11, 6) : (DateTime?)null;
            //Json deserialize interprets date as mm/dd/yyyy so format date that way
            var startUtcStr = startUtc?.ToString("MM/dd/yyyy");
            var endUtcStr   = endUtc?.ToString("MM/dd/yyyy");
            var filter      = new MasterData.Repositories.DBModels.Filter
            {
                FilterJson =
                    $"{{\"dateRangeType\":\"{dateRangeType}\",\"asAtDate\":\"{asAtDate}\",\"startUTC\":\"{startUtcStr}\",\"endUTC\":\"{endUtcStr}\",\"elevationType\":null}}"
            };

            await FilterJsonHelper.ParseFilterJson(
                new ProjectData { IanaTimeZone = "America/Los_Angeles", ProjectUID = _projectGuid.ToString() }, filter,
                productivity3dV2ProxyCompaction : _mockedProductivity3dV2ProxyCompaction.Object, customHeaders : new HeaderDictionary());

            Abstractions.Models.Filter filterObj =
                JsonConvert.DeserializeObject <Abstractions.Models.Filter>(filter.FilterJson);
            Assert.Equal(dateRangeType, filterObj.DateRangeType);
            if (asAtDate)
            {
                Assert.Equal(MockedStartTime, filterObj.StartUtc);
            }
            else
            {
                Assert.Equal(startUtc, filterObj.StartUtc);
            }
            Assert.Equal(endUtc, filterObj.EndUtc);
        }
예제 #7
0
        public virtual void WriteTo(XElement xE)
        {
            XElement xItem = null;

            if (Id != null)
            {
                xItem = new XElement(XName.Get("id", "https://adwords.google.com/api/adwords/cm/v201609"));
                xItem.Add(Id.Value.ToString());
                xE.Add(xItem);
            }
            xItem = new XElement(XName.Get("selector", "https://adwords.google.com/api/adwords/cm/v201609"));
            Selector.WriteTo(xItem);
            xE.Add(xItem);
            xItem = new XElement(XName.Get("reportName", "https://adwords.google.com/api/adwords/cm/v201609"));
            xItem.Add(ReportName);
            xE.Add(xItem);
            xItem = new XElement(XName.Get("reportType", "https://adwords.google.com/api/adwords/cm/v201609"));
            xItem.Add(ReportType.ToXmlValue());
            xE.Add(xItem);
            xItem = new XElement(XName.Get("dateRangeType", "https://adwords.google.com/api/adwords/cm/v201609"));
            xItem.Add(DateRangeType.ToXmlValue());
            xE.Add(xItem);
            xItem = new XElement(XName.Get("downloadFormat", "https://adwords.google.com/api/adwords/cm/v201609"));
            xItem.Add(DownloadFormat.ToXmlValue());
            xE.Add(xItem);
        }
        [InlineData(DateRangeType.Last30Days, "2019-04-01Z", "2019-05-01Z")] //BST
        public async Task PostCreateViewModelAsync_ShouldUseCorrectTimespan(DateRangeType dateRangeType, string fromDate, string toDate)
        {
            var mockClient   = new Mock <IQaVacancyClient>();
            var orchestrator = GetOrchestrator(mockClient.Object, $"{toDate}");

            var fromDateUtc = DateTimeOffset.Parse(fromDate).UtcDateTime;
            var toDateUtc   = DateTimeOffset.Parse(toDate).UtcDateTime;

            var model = new ApplicationsReportCreateEditModel
            {
                DateRange = dateRangeType
            };

            var user = new VacancyUser();

            await orchestrator.PostCreateViewModelAsync(model, user);

            string expectedReportName = $"{fromDateUtc.AsGdsDate()} to {toDateUtc.AsGdsDate()}";

            mockClient.Verify(c => c.CreateApplicationsReportAsync(
                                  fromDateUtc,
                                  toDateUtc.AddDays(1).AddTicks(-1),
                                  user,
                                  expectedReportName),
                              Times.Once);
        }
예제 #9
0
        public static IEnumerable <DateTime> Create(DateTime start, int length, DateRangeType type)
        {
            if (type is DateRangeType.Unset)
            {
                throw new ArgumentException("Please specify the DateRangeType.", nameof(type));
            }

            var value = start;

            for (int i = 0; i < length; i++)
            {
                yield return(value);

                switch (type)
                {
                case DateRangeType.Year: value = value.AddYears(1); break;

                case DateRangeType.Month: value = value.AddMonths(1); break;

                case DateRangeType.Day: value = value.AddDays(1); break;

                case DateRangeType.Hour: value = value.AddHours(1); break;

                case DateRangeType.Minute: value = value.AddMinutes(1); break;

                case DateRangeType.Second: value = value.AddSeconds(1); break;
                }
            }
        }
예제 #10
0
        public void ApplyDateRange_null_project_start_when_asAtDate(DateRangeType dateRangeType)
        {
            var filter =
                JsonConvert.DeserializeObject <Abstractions.Models.Filter>($"{{\"dateRangeType\":\"{dateRangeType}\",\"asAtDate\":\"true\"}}");

            filter.ApplyDateRange("UTC");
            Assert.Null(filter.StartUtc);
            Assert.Equal(DateTime.UtcNow.Date, filter.EndUtc.Value.Date);
        }
예제 #11
0
 protected string GetStatsTableName(
     string table, string joinTable,
     TemporalAggregation temporalAggregation,
     DateRangeType dateRangeType,
     DateTime?startDate,
     DateTime?endDate)
 {
     return(_tableMappings.GetStatsTableName(table, joinTable, temporalAggregation, dateRangeType, startDate, endDate));
 }
예제 #12
0
        public static List <DateTime> GetDateRangeArray(DateTime date, DateRangeType dateRangeType, DayOfWeek firstDayOfWeek, List <DayOfWeek> workWeekDays, int daysToSelectInDayView = 1)
        {
            var      datesArray = new List <DateTime>();
            DateTime startDate;
            DateTime endDate;

            if (workWeekDays == null)
            {
                workWeekDays = new List <DayOfWeek>()
                {
                    DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday
                };
            }

            daysToSelectInDayView = Math.Max(daysToSelectInDayView, 1);

            switch (dateRangeType)
            {
            case DateRangeType.Day:
                startDate = date.Date;
                endDate   = startDate.AddDays(daysToSelectInDayView);
                break;

            case DateRangeType.Week:
            case DateRangeType.WorkWeek:
                startDate = GetStartDateOfWeek(date.Date, firstDayOfWeek);
                endDate   = startDate.AddDays(7);
                break;

            case DateRangeType.Month:
                startDate = new DateTime(date.Year, date.Month, 1);
                endDate   = startDate.AddMonths(1);
                break;

            default:
                throw new Exception("This should never be reached.");
            }

            // Populate the dates array with the dates in range
            var nextDate = startDate;

            do
            {
                if (dateRangeType != DateRangeType.WorkWeek)
                {
                    // push all days not in work week view
                    datesArray.Add(nextDate);
                }
                else if (workWeekDays.IndexOf(nextDate.DayOfWeek) != -1)
                {
                    datesArray.Add(nextDate);
                }
                nextDate = nextDate.AddDays(1);
            } while (nextDate != endDate);

            return(datesArray);
        }
예제 #13
0
        public void ApplyDateRange_null_project_extents(DateRangeType dateRangeType)
        {
            var filter = JsonConvert.DeserializeObject <Abstractions.Models.Filter>($"{{\"dateRangeType\":\"{dateRangeType}\"}}");

            filter.ApplyDateRange("UTC");
            if (dateRangeType == DateRangeType.ProjectExtents)
            {
                Assert.Null(filter.StartUtc);
                Assert.Null(filter.EndUtc);
            }
        }
예제 #14
0
        public async Task Should_set_dates_based_on_DateRangeType_When_using_Filter(DateRangeType dateRangeType, bool asAtDate)
        {
            var filter = new MasterData.Repositories.DBModels.Filter
            {
                FilterJson = $"{{\"dateRangeType\":\"{dateRangeType}\",\"asAtDate\":\"{asAtDate}\",\"elevationType\":null}}"
            };

            await FilterJsonHelper.ParseFilterJson(
                new ProjectData { IanaTimeZone = "America/Los_Angeles", ProjectUID = _projectGuid.ToString() }, filter,
                _mockedProductivity3dV2ProxyCompaction.Object, new HeaderDictionary());

            ValidateDates(filter.FilterJson, asAtDate);
        }
예제 #15
0
        /// <summary>
        /// Get the start or end date time in UTC for the specified date range type in the specified time zone.
        /// </summary>
        /// <param name="dateRangeType">The date range type (today, current week etc.)</param>
        /// <param name="ianaTimeZoneName">The IANA time zone name</param>
        /// <param name="isStart">True for start and false for end of date range</param>
        /// <param name="useEndOfCurrentDay">Flag to indicate if end of current periods are now or the end of the current day</param>
        /// <returns>The start or end UTC for the range in the time zone</returns>
        public static DateTime?UtcForDateRangeType(this DateRangeType dateRangeType, string ianaTimeZoneName, bool isStart, bool useEndOfCurrentDay = false)
        {
            if (dateRangeType == DateRangeType.Custom || dateRangeType == DateRangeType.ProjectExtents || string.IsNullOrEmpty(ianaTimeZoneName))
            {
                return(null);
            }

            DateTimeZone  timeZone = DateTimeZoneProviders.Tzdb[ianaTimeZoneName];
            ZonedClock    clock    = SystemClock.Instance.InZone(timeZone);
            LocalDateTime localNow = clock.GetCurrentLocalDateTime();
            var           local    = localNow.LocalDateTimeForDateRangeType(dateRangeType, isStart);
            var           zoned    = timeZone.AtLeniently(local);

            return(zoned.ToDateTimeUtc());
        }
예제 #16
0
        /// <summary>
        ///     Wird per ApplyTemplate ein neues Template zugewiesen, so stellen wir hier
        ///     sicher, dass unser Button_Click noch korrekt funktioniert.
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            // Wichtig: PART_Selector MUSS zwingend als TemplatePartAttribute der Klasse
            //          deklariert worden sein!
            this.selectorControl = this.GetTemplateChild("PART_Selector") as Selector;
            if (this.selectorControl != null)
            {
                if (this.DateRangeList == null)
                {
                    this.DateRangeList = new DateRangeTypes
                    {
                        new DateRangeType("MonthToDay", "Laufender Monat", DateRanges.MonthToDay),
                        new DateRangeType("CurrentMonth", "Aktueller Monat", DateRanges.CurrentMonth),
                        new DateRangeType("PreviousMonth", "Vorheriger Monat", DateRanges.PreviousMonth),
                        new DateRangeType("YearToDay", "Laufendes Jahr", DateRanges.YearToDay),
                        new DateRangeType("CurrentYear", "Aktuelles Jahr", DateRanges.CurrentYear),
                        new DateRangeType("PreviousYear", "Vorheriges Jahr", DateRanges.PreviousYear),
                        new DateRangeType("Last12Months", "Letzte 12 Monate", DateRanges.Last12Months),
                        DateRangeType.CreateUserDefinedType("Benutzerdefiniert", DateTime.Today, DateTime.Today)
                    }
                }
                ;

                // und dem Selector-Control als Datenquelle anhängen
                this.selectorControl.ItemsSource       = this.DateRangeList;
                this.selectorControl.DisplayMemberPath = "Description";
                this.selectorControl.SelectedValuePath = "RangeType";

                this.selectorControl.SelectionChanged += this.SelectionChanged;

                if (this.DateRange != null)
                {
                    var rangeType = this.DateRangeList.FindMatchingType(this.DateRange);
                    if (rangeType != null)
                    {
                        this.selectorControl.SelectedValue = rangeType.RangeType;
                    }
                    else
                    {
                        this.selectorControl.SelectedValue = "UserDefined";
                    }
                }
            }
        }
예제 #17
0
파일: Log.cs 프로젝트: AndyAn/Miiror
        public List<string> GetLogs(string logName, DateTime date, DateRangeType dateRangeType)
        {
            List<string> logs = null;
            switch (dateRangeType)
            {
                case DateRangeType.BeforeTheDate:
                    logs = GetLogs(logName, DateTime.Parse("1900-01-01"), date.AddDays(-1));
                    break;
                case DateRangeType.AfterTheDate:
                    logs = GetLogs(logName, date.AddDays(1), DateTime.Now);
                    break;
                default:
                    break;
            }

            return logs;
        }
예제 #18
0
 public void ApplyDateRange(string ianaTimeZoneName)
 {
     if (!string.IsNullOrEmpty(ianaTimeZoneName) &&
         DateRangeType != null &&
         DateRangeType != MasterData.Models.Internal.DateRangeType.Custom)
     {
         // Force date range filters to be null if ProjectExtents is specified.
         if (DateRangeType == MasterData.Models.Internal.DateRangeType.ProjectExtents)
         {
             StartUtc = null;
             EndUtc   = null;
         }
         else
         {
             StartUtc = DateRangeType?.UtcForDateRangeType(ianaTimeZoneName, true, true);
             EndUtc   = DateRangeType?.UtcForDateRangeType(ianaTimeZoneName, false, true);
         }
     }
     //For as-at dates only use EndUTC, so make sure StartUTC is null
     if (AsAtDate == true)
     {
         StartUtc = null;
     }
 }
예제 #19
0
        private void ValidateDateRange(DateTime?dateStart, DateTime?dateEnd, DateRangeType dateRangeType, TemporalAggregation temporalAggregation)
        {
            // If no date range has been specified - we're good. We're querying lifetimes.
            if (!dateStart.HasValue && !dateEnd.HasValue)
            {
                return;
            }

            // A date range must have a start date
            if (!dateStart.HasValue)
            {
                throw new Exception(String.Format("Invalid date range: an end date was provided ([{0}]) but the start date was missing. If you specify an end date, you must also specify a start date. If you wish to query lifetime stats, omit both the start and the end date.", dateEnd.Value.ToString("yyyy-MM-dd HH:mm")));
            }

            // The end date can't be earlier than the start date
            // (the date range is inclusive/inclusive so it's valid to have start == end)
            if (dateEnd.HasValue && dateEnd.Value < dateStart.Value)
            {
                throw new Exception(String.Format("Invalid date range: [{0}] -> [{1}]. The end date must be greater than or equal to the start date. If you wish to query stats up until now, you can omit the end date altogether.",
                                                  dateStart.Value.ToString("yyyy-MM-dd HH:mm"),
                                                  dateEnd.Value.ToString("yyyy-MM-dd HH:mm")));
            }

            // We don't allow querying daily stats using a UTC date range
            // (because our daily stats are stored against the day expressed in the ad account timezone,
            // which means that we can't query them for a UTC date range).
            if (dateRangeType == DateRangeType.Utc && temporalAggregation != TemporalAggregation.ByHour && temporalAggregation != TemporalAggregation.Total)
            {
                throw new Exception(String.Format("Invalid combination of dateRangeType ([{0}]) and temporalAggregation ([{1}]). Express your date range in AccountTime instead. Unfortunately, due to the limitations of our stats data set, we are unable to query daily stats using a UTC date range.", dateRangeType, temporalAggregation));
            }

            // Check that the dates are UTC dates if the date range was meant to be a UTC date range
            // or are in an unspecified timezone if the date range was meant to be in account time.

            /*
             * This is really just to catch buggy upstream code. We could of course just force the DateTime Kind value to whatever
             * we need it to be. But if someone said they were sending us a date range in Account Time and yet specified their dates
             * as absolute instants in time (or vice-versa), it most likely means that there is something wrong
             * in the way they handle date/time values. Which means that there is a good chance that the values they sent us will be off.
             * Rather than being tolerant and ending up in a huge mess in a few months time when people start to complain that dates are
             * off-by-one due to a buggy client that doesn't handle their dates properly, enfore a very strict contract for the Reporting
             * service when it comes to date/time values. It will force clients to be explicit when handling and serializing date/times
             * instead of relying on auto-magical behaviour (which, when is comes to date and times, always leads to a huge mess).
             */

            // Refer to our JSON.NET config in the WebApiConfig class of the Reporting Service WebAPI project for all the details
            // on how we deserialize date/time values.

            if (dateRangeType == DateRangeType.Utc)
            {
                if (dateStart.Value.Kind != DateTimeKind.Utc)
                {
                    throw new Exception("Invalid value provided for dateStart. The provided value was missing its UTC offset. When specifying a dateRangeType of 'Utc', you must include the UTC offset in your date value. For example: '2015-06-19T13:00Z' or '2015-06-19T13:00+00:00' or '2015-06-19T15:00+02:00'. Otherwise, we have no way to know what instant in time the date you provided is supposed to represent.");
                }

                if (dateEnd.HasValue && dateEnd.Value.Kind != DateTimeKind.Utc)
                {
                    throw new Exception("Invalid value provided for dateEnd. The provided value was missing its UTC offset. When specifying a dateRangeType of 'Utc', you must include the UTC offset in your date value. For example: '2015-06-19T13:00Z' or '2015-06-19T13:00+00:00' or '2015-06-19T15:00+02:00'. Otherwise, we have no way to know what instant in time the date you provided is supposed to represent.");
                }
            }
            else if (dateRangeType == DateRangeType.AccountTime)
            {
                if (dateStart.Value.Kind != DateTimeKind.Unspecified)
                {
                    throw new Exception("Invalid value provided for dateStart. Was expecting to receive a Local Date, i.e. a date value with no UTC offset provided. But got an absolute date instead (a date with a UTC offset provided). When specifying a dateRangeType of 'AccountTime', you must specify your date values as Local Date (as per the ISO 8601 definition). I.e. you must not specify a UTC offset. For example: '2015-06-19T13:00'. This is because different ad accounts have different timezones, i.e. the timezone is unspecified. Specifying the UTC offset of such a date doesn't make sense and would be misleading.");
                }

                if (dateEnd.HasValue && dateEnd.Value.Kind != DateTimeKind.Unspecified)
                {
                    throw new Exception("Invalid value provided for dateStart. Was expecting to receive a Local Date, i.e. a date value with no UTC offset provided. But got an absolute date instead (a date with a UTC offset provided). When specifying a dateRangeType of 'AccountTime', you must specify your date values as Local Date (as per the ISO 8601 definition). I.e. you must not specify a UTC offset. For example: '2015-06-19T13:00'. This is because different ad accounts have different timezones, i.e. the timezone is unspecified. Specifying the UTC offset of such a date doesn't make sense and would be misleading.");
                }
            }
            else
            {
                throw new Exception("Unknown value provided for dateRangeType: " + dateRangeType);
            }
        }
예제 #20
0
 public override string GetStatsTableName(string table, string joinTable, TemporalAggregation temporalAggregation,
                                          DateRangeType dateRangeType, DateTime?startDate, DateTime?endDate)
 {
     return(PlayerMatchStatisticsTable.DbTableName);
 }
예제 #21
0
        public ActionResult Search(string platform, string q, int group, int sort, bool sortDesc, DateTime?startDate, DateTime?endDate, TemporalAggregation temporalAggregation, DateRangeType dateRangeType, int[] status, int[] column, int pageIndex, int pageSize, bool debug, bool excludeRecordsWithNoStats, int summarize = 0, bool export = false, int orgId = 0)
        {
            if (column == null || !column.Any())
            {
                return(View(new SearchResponse {
                    Error = new ResponseError()
                    {
                        Message = "No Columns Selected"
                    }
                }));
            }

            var filters = new List <SearchRequestFilter>();

            LoadFilters(filters);
            var textFilterColumns = LoadTextColumns();

            var selectedCols = new List <SelectedColumn>();

            if (column == null || !column.Any())
            {
                throw new Exception("No Columns Selected");
            }

            foreach (var col in column)
            {
                var sCol = new SelectedColumn(col);
                selectedCols.Add(sCol);
            }

            var searchRequest = new SearchRequest()
            {
                GetCount                  = pageIndex == 0,
                Query                     = q,
                PageIndex                 = pageIndex,
                PageSize                  = pageSize,
                GroupByColumn             = new SelectedColumn(group),
                SummarizeByColumn         = summarize > 0 ? new SelectedColumn(summarize) : null,
                SortByColumn              = new SelectedColumn(sort),
                SortDescending            = sortDesc,
                SelectedColumns           = selectedCols,
                Filters                   = filters,
                TemporalAggregation       = temporalAggregation,
                ExcludeRecordsWithNoStats = excludeRecordsWithNoStats,
                DebugMode                 = debug,
                DateRangeType             = dateRangeType,
                TextFilterColumns         = textFilterColumns
            };

            searchRequest.DateStart = startDate;
            searchRequest.DateEnd   = endDate;

            if (dateRangeType == DateRangeType.Utc)
            {
                // In our test UI, we ask the user to enter a UTC date so no User timezone to UTC conversion required here.
                if (searchRequest.DateStart.HasValue)
                {
                    searchRequest.DateStart = DateTime.SpecifyKind(searchRequest.DateStart.Value, DateTimeKind.Utc);
                }
                if (searchRequest.DateEnd.HasValue)
                {
                    searchRequest.DateEnd = DateTime.SpecifyKind(searchRequest.DateEnd.Value, DateTimeKind.Utc);
                }
            }
            else
            {
                // The date range is in Account Time, i.e. the dates are not instants in time. They're just a day and a time in some unspecified timezone.
                if (searchRequest.DateStart.HasValue)
                {
                    searchRequest.DateStart = DateTime.SpecifyKind(searchRequest.DateStart.Value, DateTimeKind.Unspecified);
                }
                if (searchRequest.DateEnd.HasValue)
                {
                    searchRequest.DateEnd = DateTime.SpecifyKind(searchRequest.DateEnd.Value, DateTimeKind.Unspecified);
                }
            }

            if (export)
            {
                return(Export(platform, searchRequest));
            }

            var sw = new Stopwatch();

            sw.Start();

            var result = _reportsService.Search(platform, orgId, Configuration.UserId, searchRequest);

            sw.Stop();
            ViewBag.SearchElapsedMilliseconds = sw.ElapsedMilliseconds;

            return(View(result));
        }
예제 #22
0
        private static string ListOfRecordingsAsHTML(ref List<RPRecording> recs, DateRangeType dateRangeToShow, bool showTitle, bool showStartTime, bool showChannel, bool linkToPage)
        {
            string txtShowings = "";
            bool hasShownAnyEvents = false;

            bool fallsWithinDateRange;
            foreach (RPRecording rec in recs)
            {
                // Get associated TV Programme
                TVProgramme tvp = rec.TVProgramme();
                if (tvp == null) continue;

                TVService tvs = tvp.TVService();
                if (tvs == null) continue;

                // Include this showing?
                fallsWithinDateRange = (dateRangeToShow == DateRangeType.All);

                if (dateRangeToShow == DateRangeType.FutureOnly)
                    if (tvp.StopTimeDT().ToLocalTime() >= DateTime.Now)
                        fallsWithinDateRange = true;

                if (dateRangeToShow == DateRangeType.PastOnly)
                    if (tvp.StopTimeDT().ToLocalTime() < DateTime.Now)
                        fallsWithinDateRange = true;

                if (fallsWithinDateRange)
                {
                    if (!hasShownAnyEvents)
                    {
                        txtShowings += "<ul>";
                        hasShownAnyEvents = true;
                    }

                    txtShowings += "<li class='";
                    // style
                    if ( (rec.State ==  RPRecordingStates.Scheduled) ||
                        (rec.State == RPRecordingStates.Recording ) ||
                        (rec.State == RPRecordingStates.Recorded) )
                            txtShowings += "upcomingwillrecord";
                    else
                        txtShowings += "upcomingwontrecord";
                    txtShowings += "'>";
                    if (linkToPage) txtShowings += "<a href='viewepgprogramme?programmeid=" + tvp.Id + "'>";
                    if (showTitle) txtShowings += tvp.Title + ": ";
                    if (showStartTime) txtShowings += tvp.ToPrettyDate() + ", " + tvp.StartTimeDT().ToLocalTime().ToShortTimeString();

                    if (showChannel)
                        if (tvs != null)
                            txtShowings += " (" + tvs.Callsign + ")";
                    if (linkToPage) txtShowings += "</a>";
                    txtShowings += "</li>";
                }
            }

            if (hasShownAnyEvents)
                txtShowings += "</ul>";
            else
                txtShowings += "None found.";

            return txtShowings;
        }
        private void GenerateWeeks()
        {
            DateTime date       = new(NavigatedDate.Year, NavigatedDate.Month, 1);
            DateTime todaysDate = DateTime.Now;

            Weeks = new List <List <DayInfo> >();

            // cycle backwards to get first day of week
            while (date.DayOfWeek != FirstDayOfWeek)
            {
                date -= TimeSpan.FromDays(1);
            }

            // a flag to indicate whether all days of the week are in the month
            bool isAllDaysOfWeekOutOfMonth = false;

            // in work week view we want to select the whole week
            //DateRangeType selecteDateRangeType = DateRangeType == DateRangeType.WorkWeek ? DateRangeType.Week : DateRangeType;
            DateRangeType   selecteDateRangeType = DateRangeType;
            List <DateTime>?selectedDates        = SelectedDate == null ? new List <DateTime>() : DateUtilities.GetDateRangeArray((DateTime)SelectedDate, selecteDateRangeType, FirstDayOfWeek, WorkWeekDays);

            if (DateRangeType != DateRangeType.Day)
            {
                selectedDates = GetBoundedDateRange(selectedDates, MinDate, MaxDate);
            }

            bool shouldGetWeeks = true;

            for (int weekIndex = 0; shouldGetWeeks; weekIndex++)
            {
                List <DayInfo> week = new();
                isAllDaysOfWeekOutOfMonth = true;

                for (int dayIndex = 0; dayIndex < 7; dayIndex++)
                {
                    DateTime originalDate = new(date.Year, date.Month, date.Day);
                    DayInfo? dayInfo      = new()
                    {
                        Key                  = date.ToString(),
                        Date                 = date.Date.ToString("D"),
                        OriginalDate         = originalDate,
                        WeekIndex            = weekIndex,
                        IsInMonth            = date.Month == NavigatedDate.Month,
                        IsToday              = DateTime.Compare(DateTime.Now.Date, originalDate) == 0,
                        IsSelected           = IsInDateRangeArray(date, selectedDates),
                        IsHighlightedOnHover = IsInWorkweekRange(date),
                        OnSelected           = () => OnSelectDateInternal(originalDate, false),
                        IsInBounds           =
                            (DateTime.Compare(MinDate, date) < 1) &&
                            (DateTime.Compare(date, MaxDate) < 1) &&
                            !GetIsRestrictedDate(date)
                    };

                    week.Add(dayInfo);
                    if (dayInfo.IsInMonth)
                    {
                        isAllDaysOfWeekOutOfMonth = false;
                    }

                    date = date.AddDays(1);
                }

                // We append the condition of the loop depending upon the ShowSixWeeksByDefault parameter.
                shouldGetWeeks = ShowSixWeeksByDefault ? !isAllDaysOfWeekOutOfMonth || weekIndex <= 5 : !isAllDaysOfWeekOutOfMonth;
                if (shouldGetWeeks)
                {
                    Weeks.Add(week);
                }
            }
        }
예제 #24
0
        /// <summary>
        /// API call example for SearchInvoices
        /// </summary>
        /// <param name="context"></param>
        private void SearchInvoices(HttpContext context)
        {
            // Collect input params
            String merchantEmail = context.Request.Params["merchantEmail"];
            int    page          = Int32.Parse(context.Request.Params["page"]);
            int    pageSize      = Int32.Parse(context.Request.Params["pageSize"]);
            SearchParametersType  searchParams = new SearchParametersType();
            SearchInvoicesRequest request      = new SearchInvoicesRequest(
                new RequestEnvelope(ERROR_LANGUAGE), merchantEmail, searchParams, page, pageSize);

            if (context.Request.Params["email"] != "")
            {
                searchParams.email = context.Request.Params["email"];
            }
            if (context.Request.Params["recipientName"] != "")
            {
                searchParams.recipientName = context.Request.Params["recipientName"];
            }
            if (context.Request.Params["businessName"] != "")
            {
                searchParams.businessName = context.Request.Params["businessName"];
            }
            if (context.Request.Params["invoiceNumber"] != "")
            {
                searchParams.invoiceNumber = context.Request.Params["invoiceNumber"];
            }
            if (context.Request.Params["status0"] != "")
            {
                // You can add upto 10 status to do a 'OR' search on multiple status types
                searchParams.status.Add(
                    (StatusType)Enum.Parse(typeof(StatusType), context.Request.Params["status0"]));
            }
            if (context.Request.Params["status1"] != "")
            {
                // You can add upto 10 status to do a 'OR' search on multiple status types
                searchParams.status.Add(
                    (StatusType)Enum.Parse(typeof(StatusType), context.Request.Params["status1"]));
            }
            if (context.Request.Params["status2"] != "")
            {
                // You can add upto 10 status to do a 'OR' search on multiple status types
                searchParams.status.Add(
                    (StatusType)Enum.Parse(typeof(StatusType), context.Request.Params["status2"]));
            }
            if (context.Request.Params["lowerAmount"] != "")
            {
                searchParams.lowerAmount = decimal.Parse(context.Request.Params["lowerAmount"]);
            }
            if (context.Request.Params["upperAmount"] != "")
            {
                searchParams.upperAmount = decimal.Parse(context.Request.Params["upperAmount"]);
            }
            if (context.Request.Params["memo"] != "")
            {
                searchParams.memo = context.Request.Params["memo"];
            }
            if (context.Request.Params["currencyCode"] != "")
            {
                searchParams.currencyCode = context.Request.Params["currencyCode"];
            }
            if (context.Request.Params["origin"] != "")
            {
                searchParams.origin = (OriginType)
                                      Enum.Parse(typeof(OriginType), context.Request.Params["origin"]);
            }
            if (context.Request.Params["invoiceDateStart"] != "" || context.Request.Params["invoiceDateEnd"] != "")
            {
                DateRangeType dateRange = new DateRangeType();
                dateRange.startDate      = context.Request.Params["invoiceDateStart"];
                dateRange.endDate        = context.Request.Params["invoiceDateEnd"];
                searchParams.invoiceDate = dateRange;
            }
            if (context.Request.Params["dueDateStart"] != "" || context.Request.Params["dueDateEnd"] != "")
            {
                DateRangeType dateRange = new DateRangeType();
                dateRange.startDate  = context.Request.Params["dueDateStart"];
                dateRange.endDate    = context.Request.Params["dueDateEnd"];
                searchParams.dueDate = dateRange;
            }
            if (context.Request.Params["paymentDateStart"] != "" || context.Request.Params["paymentDateEnd"] != "")
            {
                DateRangeType dateRange = new DateRangeType();
                dateRange.startDate      = context.Request.Params["paymentDateStart"];
                dateRange.endDate        = context.Request.Params["paymentDateEnd"];
                searchParams.paymentDate = dateRange;
            }
            if (context.Request.Params["creationDateStart"] != "" || context.Request.Params["creationDateEnd"] != "")
            {
                DateRangeType dateRange = new DateRangeType();
                dateRange.startDate       = context.Request.Params["creationDateStart"];
                dateRange.endDate         = context.Request.Params["creationDateEnd"];
                searchParams.creationDate = dateRange;
            }

            // Create service object and make the API call
            InvoiceService         service;
            SearchInvoicesResponse response;

            try
            {
                service  = getService(context);
                response = service.SearchInvoices(request);
            }
            catch (Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary <string, string> keyResponseParams = new Dictionary <string, string>();

            keyResponseParams.Add("API status", response.responseEnvelope.ack.ToString());
            keyResponseParams.Add("correlationId", response.responseEnvelope.correlationId);
            keyResponseParams.Add("invoice count", response.count.ToString());
            keyResponseParams.Add("hasNextPage", response.hasNextPage.ToString());
            keyResponseParams.Add("hasPreviousPage", response.hasPreviousPage.ToString());

            if (response.invoiceList != null && response.invoiceList.invoice != null)
            {
                int idx = 0;
                foreach (InvoiceSummaryType invoice in response.invoiceList.invoice)
                {
                    keyResponseParams.Add(idx + " invoice Id", invoice.invoiceID);
                    keyResponseParams.Add(idx + " invoice status", invoice.status.ToString());
                    idx++;
                }
            }
            displayResponse(context, "UpdateInvoice", keyResponseParams, service.getLastRequest(),
                            service.getLastResponse(), response.error, null);
        }
예제 #25
0
 public override string GetStatsTableName(string table, string joinTable, TemporalAggregation temporalAggregation,
                                          DateRangeType dateRangeType, DateTime?startDate, DateTime?endDate)
 {
     throw new NotImplementedException();
 }
예제 #26
0
        /// <summary>
        /// Get the start or end date time in a time zone for the specified date range type.
        /// </summary>
        /// <param name="nowInTimeZone">Now in time zone</param>
        /// <param name="dateRangeType">The date range type (today, current week etc.)</param>
        /// <param name="isStart">True for start and false for end of date range</param>
        /// <param name="useEndOfCurrentDay">Flag to indicate if end of current periods are now or the end of the current day</param>
        /// <returns>The start or end date time for the range in the time zone</returns>
        public static LocalDateTime LocalDateTimeForDateRangeType(this LocalDateTime nowInTimeZone, DateRangeType dateRangeType, bool isStart, bool useEndOfCurrentDay = false)
        {
            LocalDateTime startToday = nowInTimeZone.PlusTicks(-nowInTimeZone.TickOfDay);
            LocalDateTime endToday   = startToday.PlusDays(1).PlusSeconds(-1);
            var           currentEnd = useEndOfCurrentDay ? endToday : nowInTimeZone;

            var startThisWeek  = startToday.With(DateAdjusters.PreviousOrSame(IsoDayOfWeek.Monday));
            var startThisMonth = startToday.With(DateAdjusters.StartOfMonth);

            LocalDateTime dateTimeInTimeZone = nowInTimeZone;

            switch (dateRangeType)
            {
            case DateRangeType.Today:
                dateTimeInTimeZone = isStart ? startToday : currentEnd;
                break;

            case DateRangeType.Yesterday:
            case DateRangeType.PriorToYesterday:
                dateTimeInTimeZone = isStart ? startToday.PlusDays(-1) : startToday.PlusSeconds(-1);
                if (dateRangeType == DateRangeType.PriorToYesterday)
                {
                    dateTimeInTimeZone = dateTimeInTimeZone.PlusDays(-1);
                }
                break;

            case DateRangeType.CurrentWeek:
                dateTimeInTimeZone = isStart ? startThisWeek : currentEnd;
                break;

            case DateRangeType.PreviousWeek:
            case DateRangeType.PriorToPreviousWeek:
                dateTimeInTimeZone = isStart ? startThisWeek.PlusDays(-7) : startThisWeek.PlusSeconds(-1);
                if (dateRangeType == DateRangeType.PriorToPreviousWeek)
                {
                    dateTimeInTimeZone = dateTimeInTimeZone.PlusDays(-7);
                }
                break;

            case DateRangeType.CurrentMonth:
                dateTimeInTimeZone = isStart ? startThisMonth : currentEnd;
                break;

            case DateRangeType.PreviousMonth:
            case DateRangeType.PriorToPreviousMonth:
                dateTimeInTimeZone = isStart ? startThisMonth.PlusMonths(-1) : startThisMonth.PlusSeconds(-1);
                if (dateRangeType == DateRangeType.PriorToPreviousMonth)
                {
                    dateTimeInTimeZone = dateTimeInTimeZone.PlusMonths(-1);
                }
                break;

            case DateRangeType.ProjectExtents:
            case DateRangeType.Custom:
                //do nothing
                break;
            }
            return(dateTimeInTimeZone);
        }
예제 #27
0
        private void AddWeekData(WeeklySummary result, DateRangeType weekRangeType)
        {
            var rangeData = new DateRange();

            rangeData.RangeType = weekRangeType;
            rangeData.CalculateDatesFromType(DateHelper.ConvertUtcToStoreTime(_hccApp));

            var totalCount = 0;
            var storeId    = _hccApp.CurrentStore.Id;

            var data = _hccApp.OrderServices.Transactions
                       .FindForReportByDateRange(rangeData.StartDate.ToUniversalTime(), rangeData.EndDate.ToUniversalTime(),
                                                 storeId, int.MaxValue, 1, ref totalCount);

            decimal m = 0;
            decimal t = 0;
            decimal w = 0;
            decimal r = 0;
            decimal f = 0;
            decimal s = 0;
            decimal y = 0;

            foreach (var ot in data)
            {
                var timeStamp = DateHelper.ConvertUtcToStoreTime(_hccApp, ot.TimeStampUtc);

                switch (timeStamp.DayOfWeek)
                {
                case DayOfWeek.Monday:
                    m += ot.AmountAppliedToOrder;
                    break;

                case DayOfWeek.Tuesday:
                    t += ot.AmountAppliedToOrder;
                    break;

                case DayOfWeek.Wednesday:
                    w += ot.AmountAppliedToOrder;
                    break;

                case DayOfWeek.Thursday:
                    r += ot.AmountAppliedToOrder;
                    break;

                case DayOfWeek.Friday:
                    f += ot.AmountAppliedToOrder;
                    break;

                case DayOfWeek.Saturday:
                    s += ot.AmountAppliedToOrder;
                    break;

                case DayOfWeek.Sunday:
                    y += ot.AmountAppliedToOrder;
                    break;
                }
            }

            result.Monday    = m;
            result.Tuesday   = t;
            result.Wednesday = w;
            result.Thursday  = r;
            result.Friday    = f;
            result.Saturday  = s;
            result.Sunday    = y;
        }
예제 #28
0
        public void DateRangeName_returns_correct_string_representation(DateRangeType dateRangeType, string expectedResult)
        {
            var filter = JsonConvert.DeserializeObject <Abstractions.Models.Filter>($"{{\"dateRangeType\":\"{dateRangeType}\"}}");

            Assert.Equal(expectedResult, filter.DateRangeName);
        }
예제 #29
0
		public void Filter (DateRangeType dateRange, string rangeElements, Series inputSeries)
		{
			throw new NotImplementedException ();
		}
예제 #30
0
        public static List<DataManagerData> GetDataForSensor(long componentSensorId, DateTime startTime, TimeSpan timeRange, DateRangeType minResolution, DateRangeType maxResolution, out double average, out double min, out double max, out double stddev)
        {
            if (maxResolution > minResolution)
            {
                throw new ArgumentException("max resolution must be finer (less) than the min resolution!");
            }

            if (maxResolution > DateRangeType.hour)
            {
                throw new ArgumentException("We don't aggregate hours into days dynamically yet!");
            }

            max = Double.MinValue;
            min = Double.MaxValue;
            average = 0;
            stddev = 0;

            double sum = 0;
            double sumOfSquares = 0;
            long count = 0;

            List<DataManagerData> retVal = new List<DataManagerData>();

            lock (s_lockObject)
            {
                DateTime timeCutoff = RoundDownToHour(DateTime.UtcNow.AddHours(-1));

                // Let's see if we need to grab the historical data
                if (startTime < timeCutoff)
                {
                    const string c_selecttHistoricalData = "SELECT Count,Sum,DateRange,Date,SumOfSquares,Min,Max FROM HistoricalAggregation WHERE ComponentSensorID = @componentSensorId AND Date >= @minDate AND Date < @maxDate AND DateRange >= @maxResolution AND DateRange <= @minResolution ORDER BY Date ASC, DateRange DESC";

                    // If the row already exists, we need to add the data together
                    using (SQLiteCommand sqlSelectCommand = new SQLiteCommand(s_dataManager._sqliteConnection))
                    {
                        sqlSelectCommand.CommandText = c_selecttHistoricalData;
                        sqlSelectCommand.Parameters.Add(new SQLiteParameter("@componentSensorId", componentSensorId));
                        sqlSelectCommand.Parameters.Add(new SQLiteParameter("@minDate", startTime));

                        // Only pull coarse grain info up to the cutoff. We have fine grained info above the cutoff
                        DateTime maxDate = (startTime + timeRange < timeCutoff) ? startTime + timeRange : timeCutoff;
                        sqlSelectCommand.Parameters.Add(new SQLiteParameter("@maxDate", maxDate));
                        sqlSelectCommand.Parameters.Add(new SQLiteParameter("@maxResolution", maxResolution));
                        sqlSelectCommand.Parameters.Add(new SQLiteParameter("@minResolution", minResolution));

                        using (SQLiteDataReader reader = sqlSelectCommand.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                DataManagerData data = new DataManagerData();
                                DateRangeType currentRangeType = (DateRangeType)Convert.ToInt32(reader["DateRange"]);
                                data.TimeSpan = GetTimeSpanFromDateRangeType(currentRangeType);
                                data.TimeStamp = DateTime.SpecifyKind(Convert.ToDateTime(reader["Date"]), DateTimeKind.Local).ToUniversalTime();

                                // We'll always assume Count != 0 for this project
                                data.Measure = Convert.ToDouble(reader["Sum"]) / (double)(Convert.ToInt64(reader["Count"]));
                                retVal.Add(data);

                                min = Math.Min(min, Convert.ToDouble(reader["Min"]));
                                max = Math.Max(max, Convert.ToDouble(reader["Max"]));
                                sumOfSquares += Convert.ToDouble(reader["SumOfSquares"]);
                                sum += Convert.ToDouble(reader["Sum"]);
                                count += Convert.ToInt64(reader["Count"]);
                            }
                        }
                    }
                }

                // Let's see if we need to grab from the fine grain data
                if (startTime + timeRange > timeCutoff)
                {
                    const string c_selectSensorData = "SELECT Date,Value FROM SensorData WHERE Date < @maxTime AND Date >= @minTime AND ComponentSensorId = @componentSensorId ORDER BY Date ASC";

                    using (SQLiteCommand sqlSelectCommand = new SQLiteCommand(s_dataManager._sqliteConnection))
                    {
                        sqlSelectCommand.CommandText = c_selectSensorData;
                        sqlSelectCommand.Parameters.Add(new SQLiteParameter("@minTime", startTime));
                        sqlSelectCommand.Parameters.Add(new SQLiteParameter("@maxTime", startTime + timeRange));
                        sqlSelectCommand.Parameters.Add(new SQLiteParameter("@componentSensorId", componentSensorId));

                        using (SQLiteDataReader reader = sqlSelectCommand.ExecuteReader())
                        {
                            DateTime lastTime = DateTime.MinValue;
                            double tempSum = 0;
                            double tempCount = 0;

                            // We need to aggregate the seconds together if the max resolution is coarser than a second
                            while (reader.Read())
                            {
                                DataManagerData data = new DataManagerData();
                                data.TimeStamp = Convert.ToDateTime(reader["Date"]);
                                data.Measure = Convert.ToDouble(reader["Value"]);

                                DateTime currentTime = RoundDownToDateRangeType(data.TimeStamp, maxResolution);
                                if (currentTime > lastTime || maxResolution <= DateRangeType.second)
                                {
                                    if (lastTime > DateTime.MinValue)
                                    {
                                        DataManagerData newData = new DataManagerData();
                                        newData.TimeStamp = lastTime;
                                        newData.TimeSpan = GetTimeSpanFromDateRangeType(maxResolution);
                                        newData.Measure = (tempSum / (double)tempCount);
                                        retVal.Add(newData);
                                        min = Math.Min(min, newData.Measure);
                                        max = Math.Max(max, newData.Measure);
                                        sumOfSquares += newData.Measure * newData.Measure;
                                        sum += newData.Measure;
                                        count++;
                                        tempSum = 0;
                                        tempCount = 0;
                                    }

                                    lastTime = currentTime;
                                }

                                tempSum += data.Measure;
                                tempCount++;
                            }

                            if (lastTime > DateTime.MinValue)
                            {
                                DataManagerData newData = new DataManagerData();
                                newData.TimeStamp = lastTime;
                                newData.TimeSpan = GetTimeSpanFromDateRangeType(maxResolution);
                                newData.Measure = (tempSum / (double)tempCount);
                                retVal.Add(newData);
                                min = Math.Min(min, newData.Measure);
                                max = Math.Max(max, newData.Measure);
                                sumOfSquares += newData.Measure * newData.Measure;
                                sum += newData.Measure;
                                count++;
                                tempSum = 0;
                                tempCount = 0;
                            }
                        }
                    }
                }
            }

            if (count > 0)
            {
                average = sum / count;
                stddev = Math.Sqrt((sumOfSquares / count) - (average * average));
            }

            return retVal;
        }
예제 #31
0
 private static DateTime RoundDownToDateRangeType(DateTime dt, DateRangeType drt)
 {
     switch (drt)
     {
         case DateRangeType.day:
             return RoundDownToDay(dt);
         case DateRangeType.hour:
             return RoundDownToHour(dt);
         case DateRangeType.minute:
             return RoundDownToMinute(dt);
         case DateRangeType.second:
         default:
             return RoundDownToSecond(dt);
     }
 }
예제 #32
0
        public async Task Should_set_dates_based_on_DateRangeType_When_using_collection_of_Filters(DateRangeType dateRangeType,
                                                                                                   bool asAtDate)
        {
            var filters = new List <MasterData.Repositories.DBModels.Filter>();

            for (int i = 0; i < 10; i++)
            {
                filters.Add(new MasterData.Repositories.DBModels.Filter
                {
                    FilterJson = $"{{\"dateRangeType\":\"{dateRangeType}\",\"asAtDate\":\"{asAtDate}\",\"elevationType\":null}}"
                });
            }

            await FilterJsonHelper.ParseFilterJson(
                new ProjectData { IanaTimeZone = "America/Los_Angeles", ProjectUID = _projectGuid.ToString() }, filters,
                _mockedProductivity3dV2ProxyCompaction.Object, new HeaderDictionary());

            foreach (var filter in filters)
            {
                ValidateDates(filter.FilterJson, asAtDate);
            }
        }
예제 #33
0
 private static TimeSpan GetTimeSpanFromDateRangeType(DateRangeType drt)
 {
     switch (drt)
     {
         case DateRangeType.second:
             return TimeSpan.FromSeconds(1);
         case DateRangeType.minute:
             return TimeSpan.FromMinutes(1);
         case DateRangeType.hour:
             return TimeSpan.FromHours(1);
         case DateRangeType.day:
         default:
             return TimeSpan.FromDays(1);
     }
 }
예제 #34
0
 public void Filter(DateRangeType dateRange, string rangeElements, Series inputSeries)
 {
     throw new NotImplementedException();
 }
예제 #35
0
        private static void InsertHistoricalData(long componentSensorId, DateTime measureTime, DateRangeType dateRangeType, long count, double sum, double sumOfSquares, double min, double max)
        {
            const string c_selecttHistoricalData = "SELECT Count,Sum,SumOfSquares,Min,Max FROM HistoricalAggregation WHERE ComponentSensorID = @componentSensorId AND Date = @date AND DateRange = @dateRange";

            bool alreadyExists = false;

            // If the row already exists, we need to add the data together
            using (SQLiteCommand sqlSelectCommand = new SQLiteCommand(s_dataManager._sqliteConnection))
            {
                sqlSelectCommand.CommandText = c_selecttHistoricalData;
                sqlSelectCommand.Parameters.Add(new SQLiteParameter("@componentSensorId", componentSensorId));
                sqlSelectCommand.Parameters.Add(new SQLiteParameter("@date", measureTime));
                sqlSelectCommand.Parameters.Add(new SQLiteParameter("@dateRange", dateRangeType));

                using (SQLiteDataReader reader = sqlSelectCommand.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        alreadyExists = true;
                        count += Convert.ToInt64(reader["Count"]);
                        sum += Convert.ToDouble(reader["Sum"]);
                        sumOfSquares += Convert.ToDouble(reader["SumOfSquares"]);
                        double tempMin = Convert.ToDouble(reader["Min"]);
                        min = Math.Min(min, tempMin);
                        double tempMax = Convert.ToDouble(reader["Max"]);
                        max = Math.Max(max, tempMax);
                    }
                }
            }

            // If a row does already exist, it's equivalent and easier to delete and reinsert rather than update since
            // we're updating most of the row. This can almost never happen
            if (alreadyExists)
            {
                const string c_deleteSensorData = "DELETE FROM HistoricalAggregation WHERE ComponentSensorID = @componentSensorId AND Date = @date AND DateRange = @dateRange";
                using (SQLiteCommand sqlDeleteCommand = new SQLiteCommand(s_dataManager._sqliteConnection))
                {
                    sqlDeleteCommand.CommandText = c_deleteSensorData;

                    sqlDeleteCommand.Parameters.Add(new SQLiteParameter("@componentSensorId", componentSensorId));
                    sqlDeleteCommand.Parameters.Add(new SQLiteParameter("@date", measureTime));
                    sqlDeleteCommand.Parameters.Add(new SQLiteParameter("@dateRange", dateRangeType));

                    sqlDeleteCommand.ExecuteNonQuery();
                }
            }

            const string c_insertHistoricalData = "INSERT INTO HistoricalAggregation (ComponentSensorID,Date,DateRange,Count,Sum,SumOfSquares,Min,Max) values (@componentSensorId,@date,@dateRange,@count,@sum,@sumOfSquares,@min,@max)";

            using (SQLiteCommand sqlInsertCommand = new SQLiteCommand(s_dataManager._sqliteConnection))
            {
                sqlInsertCommand.CommandText = c_insertHistoricalData;
                sqlInsertCommand.Parameters.Add(new SQLiteParameter("@componentSensorId", componentSensorId));
                sqlInsertCommand.Parameters.Add(new SQLiteParameter("@date", measureTime));
                sqlInsertCommand.Parameters.Add(new SQLiteParameter("@dateRange", dateRangeType));
                sqlInsertCommand.Parameters.Add(new SQLiteParameter("@count", count));
                sqlInsertCommand.Parameters.Add(new SQLiteParameter("@sum", sum));
                sqlInsertCommand.Parameters.Add(new SQLiteParameter("@sumOfSquares", sumOfSquares));
                sqlInsertCommand.Parameters.Add(new SQLiteParameter("@min", min));
                sqlInsertCommand.Parameters.Add(new SQLiteParameter("@max", max));

                sqlInsertCommand.ExecuteNonQuery();
            }
        }
예제 #36
0
        /// <summary>
        /// Applies the appropriate WHERE clauses to restrict the query to the provided date range.
        /// </summary>
        public static void AddDateFilters(
            SelectQuery query,
            string statsTableAlias,
            TemporalAggregation temporalAggregation,
            DateRangeType dateRangeType,
            string dateTimeField,
            DateTime?startDate,
            DateTime?endDate)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }
            if (String.IsNullOrWhiteSpace(statsTableAlias))
            {
                throw new ArgumentException("Invalid value provided for 'statsTableAlias'. 'statsTableAlias' cannot be null or empty.");
            }
            if (endDate.HasValue && !startDate.HasValue)
            {
                throw new ArgumentException("Invalid value provided for startDate and endDate. An endDate was provided but startDate was null. When an endDate is provided, a startDate must also be provided.");
            }

            if (!startDate.HasValue) // No date filtering
            {
                return;
            }

            query.Where(Combine.And);

            if (temporalAggregation == TemporalAggregation.ByHour ||
                (temporalAggregation == TemporalAggregation.Total && dateRangeType == DateRangeType.Utc))
            {
                // We're querying the Hourly stats table.
                //
                // The *Hourly tables should store both the UTC hour (in the DateTime column) and the Account Timezone Hour
                // (in the LocalTime column) for each record. So we can select using either a UTC date range or a date range
                // expressed in the account timezone.
                //
                // IMPORTANT NOTE: in the *Hourly tables, stats are stored against the *end value* of the date range they cover.
                // E.g. the stats for hour 13:00 -> 14:00 will be stored against 14:00.
                //
                // So we must adjust the date range we've been asked to retrieve to fit with the way
                // our data is stored.

                var hourlyStartDbFormat = startDate.Value.AddHours(1);

                if (dateRangeType == DateRangeType.Utc)
                {
                    query.WhereColumnValue(statsTableAlias, dateTimeField, Compare.GreaterThanOrEqual, hourlyStartDbFormat);
                }
                else if (dateRangeType == DateRangeType.AccountTime)
                {
                    query.WhereColumnValue(statsTableAlias, "LocalTime", Compare.GreaterThanOrEqual, hourlyStartDbFormat);
                }
                else
                {
                    throw new ArgumentException(String.Format("Unexpected value provided for request.DateRangeType: [{0}]. Don't know how to handle this type of date range.", dateRangeType));
                }
            }
            else
            {
                // We're querying the Daily stats table.
                query.WhereColumnValue(statsTableAlias, dateTimeField, Compare.GreaterThanOrEqual, startDate.Value);
            }

            if (endDate.HasValue)
            {
                if (temporalAggregation == TemporalAggregation.ByHour ||
                    (temporalAggregation == TemporalAggregation.Total && dateRangeType == DateRangeType.Utc))
                {
                    var hourlyEndDbFormat = endDate.Value.AddHours(1);

                    if (dateRangeType == DateRangeType.Utc)
                    {
                        query.WhereColumnValue(statsTableAlias, dateTimeField, Compare.LessThanOrEqual, hourlyEndDbFormat);
                    }
                    else if (dateRangeType == DateRangeType.AccountTime)
                    {
                        query.WhereColumnValue(statsTableAlias, "LocalTime", Compare.LessThanOrEqual, hourlyEndDbFormat);
                    }
                    else
                    {
                        throw new ArgumentException(String.Format("Unexpected value provided for request.DateRangeType: [{0}]. Don't know how to handle this type of date range.", dateRangeType));
                    }
                }
                else
                {
                    query.WhereColumnValue(statsTableAlias, dateTimeField, Compare.LessThanOrEqual, endDate.Value);
                }
            }
        }