private bool TimeSpanTooLarge(DateTime start, DateTime?end, TimeGroup timeGroup)
        {
            var timeSpan = (end ?? DateTime.UtcNow) - start;

            switch (timeGroup)
            {
            case TimeGroup.None:
            case TimeGroup.TenSeconds:
                return(timeSpan > TimeSpan.FromHours(3));

            case TimeGroup.Minutes:
                return(timeSpan > TimeSpan.FromHours(12));

            case TimeGroup.Hours:
                return(timeSpan > TimeSpan.FromDays(30));

            case TimeGroup.Days:
                return(timeSpan > TimeSpan.FromDays(700));

            case TimeGroup.Weeks:
            case TimeGroup.Months:
            case TimeGroup.Years:
                return(false);

            default:
                throw new ArgumentOutOfRangeException(nameof(timeGroup), timeGroup, null);
            }
        }
示例#2
0
        public static float GetDeltaTime(TimeGroup timeGroup = TimeGroup.DEFAULT)
        {
            float deltaTime = Otter.Game.Instance.DeltaTime * 0.01f;

            switch (timeGroup)
            {
                case TimeGroup.DEFAULT:
                    deltaTime *= deltaTimeDefaultScale;
                    break;
                case TimeGroup.UITHINK:
                    deltaTime *= deltaTimeUIThinkScale;
                    break;
                case TimeGroup.UIRENDER:
                    deltaTime *= deltaTimeUIRenderScale;
                    break;
                case TimeGroup.WORLDTHINK:
                    deltaTime *= deltaTimeWorldThinkScale;
                    break;
                case TimeGroup.WORLDRENDER:
                    deltaTime *= deltaTimeWorldRenderScale;
                    break;
            }

            return deltaTime;
        }
        public Task <IActionResult> GetMetrics(
            [FromQuery] DateTime from,
            [FromQuery] DateTime?to         = null,
            [FromRoute] TimeGroup timeGroup = TimeGroup.None)
        {
            from = from.ToUniversalTime();
            to   = to?.ToUniversalTime();

            switch (timeGroup)
            {
            case TimeGroup.None:
            case TimeGroup.TenSeconds:
                return(GetMetrics(tenSecondMetricRepository, from, to, timeGroup));

            case TimeGroup.Minutes:
                return(GetMetrics(minuteMetricRepository, from, to, timeGroup));

            case TimeGroup.Hours:
            case TimeGroup.Days:
            case TimeGroup.Weeks:
            case TimeGroup.Months:
            case TimeGroup.Years:
                return(GetMetrics(hourMetricRepository, from, to, timeGroup));

            default:
                throw new ArgumentOutOfRangeException(nameof(timeGroup), timeGroup, null);
            }
        }
示例#4
0
        public TimeGroupViewModel(TimeGroup timeGroup)
        {
            ViewModelAttachment = new ViewModelAttachment <TimeGroup>();
            SaveCmd             = new RelayCommand(Save);
            CancelCmd           = new RelayCommand(() => Close(""));

            TimeSegmentDtos = new ObservableCollection <SelectableItem>();
            foreach (var timeSegment in AllTimeSegments)
            {
                TimeSegmentDtos.Add(new ListBoxItem {
                    ID = timeSegment.TimeSegmentID, DisplayName = timeSegment.TimeSegmentName, IsSelected = false
                });
            }

            CurrentTimeGroup = timeGroup;
            if (timeGroup.TimeGroupID != 0)
            {
                TimeGroupID = timeGroup.TimeGroupID;
                Name        = timeGroup.TimeGroupName;
                Code        = timeGroup.TimeGroupCode;

                foreach (var timeSegment in timeGroup.TimeSegments)
                {
                    TimeSegmentDtos.First(t => t.ID == timeSegment.TimeSegmentID).IsSelected = true;
                }
            }
        }
示例#5
0
 /// <summary>
 /// Returns the delta time for the group that is passed in
 /// </summary>
 /// <param name="Group"></param>
 /// <returns></returns>
 public static float DeltaTimeGroup(TimeGroup Group = TimeGroup.NONE)
 {
     if (TimeGroupTimeScaleDictionary.ContainsKey(Group))
     {
         return(DeltaTime * TimeGroupTimeScaleDictionary[Group]);
     }
     Debug.LogWarning("There is no group assigned to our dictionary");
     return(DeltaTime);
 }
示例#6
0
 /// <summary>
 /// Sets the time scale for a specific time group
 /// NOTE: Not entirely sure if we will use thsi system yet. Remove if we do not
 /// </summary>
 /// <param name="Group"></param>
 /// <param name="TimeScale"></param>
 public static void SetTimeScaleForGroup(TimeGroup Group, float TimeScale)
 {
     if (TimeGroupTimeScaleDictionary.ContainsKey(Group))
     {
         TimeGroupTimeScaleDictionary[Group] = TimeScale;
         return;
     }
     Debug.LogWarning("There is no group assigned to our Time Manager");
 }
示例#7
0
 public dtoProjectsGroup(TimeGroup timeline, long from, long to)
 {
     Projects          = new List <dtoPlainProject>();
     PreviousPageIndex = -1;
     NextPageIndex     = -1;
     Time           = new dtoTimeGroup();
     Time.TimeLine  = timeline;
     Time.FromTicks = from;
     Time.ToTicks   = to;
 }
示例#8
0
        private List <dtoProjectsGroup> GenerateEndDateTree(List <dtoPlainProject> projects, Int32 idContainerCommunity, PageListType currentPage, SummaryTimeLine timeline, Int32 pageIndex, Int32 pageSize, PagerBase pager)
        {
            List <dtoProjectsGroup> items = new List <dtoProjectsGroup>();
            String cssClass = View.GetContainerCssClass(ItemsGroupBy.EndDate);
            Int32  cCount   = View.GetCellsCount(currentPage);
            String sRow     = View.GetStartRowId(ItemsGroupBy.EndDate);

            Dictionary <TimeGroup, String> timeTranslations = View.GetTimeTranslations();
            List <dtoTimeGroup>            timegroups       = GetAvailableTimeGroups(projects.Select(p => p.VirtualEndDate).ToList());

            foreach (dtoPlainProject p in projects)
            {
                p.TimeGroup = GetTimeGroupByDate(timegroups, p.VirtualEndDate);
            }
            if (pageIndex == -1 && pager != null)
            {
                pageIndex       = GetCurrentPageIndex(pageSize, projects);
                pager.PageIndex = pageIndex;// Me.View.CurrentPageIndex
                View.Pager      = pager;
            }
            String dateTimePattern = View.GetDateTimePattern();
            Dictionary <Int32, String> monthNames = View.GetMonthNames();

            if (projects.Skip(pageIndex * pageSize).Take(pageSize).Any())
            {
                foreach (dtoTimeGroup t in GetAvailableTimeGroups(timegroups, projects.Skip(pageIndex * pageSize).Take(pageSize).Select(p => p.VirtualEndDate).ToList()))
                {
                    items.Add(new dtoProjectsGroup()
                    {
                        Id             = ((long)t.TimeLine),
                        Name           = GetTimeGroupDisplayName(timeTranslations[t.TimeLine], t, dateTimePattern, monthNames),
                        Projects       = projects.Where(p => p.VirtualEndDate.Ticks >= t.FromTicks && p.VirtualEndDate.Ticks <= t.ToTicks).ToList(),
                        CssClass       = cssClass,
                        CellsCount     = cCount,
                        IdRowFirstItem = sRow + projects.Where(p => p.VirtualEndDate.Ticks >= t.FromTicks && p.VirtualEndDate.Ticks <= t.ToTicks).First().Id.ToString(),
                        IdRowLastItem  = sRow + projects.Where(p => p.VirtualEndDate.Ticks >= t.FromTicks && p.VirtualEndDate.Ticks <= t.ToTicks).Last().Id.ToString(),
                        IdRow          = sRow + ((long)t.TimeLine).ToString(),
                        Time           = t
                    });
                }
                items.ForEach(i => UpdateProjects(i.IdRow, i.Projects, idContainerCommunity, currentPage, timeline));
                TimeGroup firstTimeGroup = items.First().Time.TimeLine;
                TimeGroup lastTimeGroup  = items.Last().Time.TimeLine;
                if (pageIndex > 0 && projects.OrderBy(p => p.VirtualEndDate).Skip((pageIndex - 1) * pageSize).Where(p => p.TimeGroup.TimeLine == firstTimeGroup).Any())
                {
                    items.First().PreviousPageIndex = pageIndex - 1;
                }
                if (projects.OrderBy(p => p.VirtualEndDate).Skip((pageIndex + 1) * pageSize).Where(p => p.TimeGroup.TimeLine == lastTimeGroup).Any())
                {
                    items.Last().NextPageIndex = pageIndex + 1;
                }
            }
            return(items);
        }
        private Int32 GetCurrentPageIndex(Int32 pageSize, List <dtoPlainTask> tasks, TimeGroup timeGroup)
        {
            Int32 pageIndex = 0;

            if (tasks.Where(p => p.TimeGroup != null && p.TimeGroup.TimeLine == timeGroup).Any())
            {
                while (tasks.Skip(pageIndex * pageSize).Take(pageSize).Any() && !tasks.Skip(pageIndex * pageSize).Take(pageSize).Where(p => p.TimeGroup != null && p.TimeGroup.TimeLine == timeGroup).Any())
                {
                    pageIndex++;
                }
                return(tasks.Skip(pageIndex * pageSize).Take(pageSize).Any() ? pageIndex : -1);
            }
            else
            {
                return(-1);
            }
        }
示例#10
0
        private TimeZoneGroupMappingInfo BuildMappingInfo(RldModel.TimeZone timeZone, int index)
        {
            int       id        = 0;
            string    name      = "";
            TimeGroup timeGroup = new TimeGroup();

            var association = timeZone.TimeGroupAssociations.FirstOrDefault(t => t.DisplayOrder == index);

            if (association != null)
            {
                id        = association.TimeZoneGroupID;
                timeGroup = AllTimeGroups.FirstOrDefault(t => t.TimeGroupID == association.TimeGroupID);
            }
            else
            {
                timeGroup = AllTimeGroups.First();
            }

            switch (index)
            {
            case 1: name = "星期一"; break;

            case 2: name = "星期二"; break;

            case 3: name = "星期三"; break;

            case 4: name = "星期四"; break;

            case 5: name = "星期五"; break;

            case 6: name = "星期六"; break;

            case 7: name = "星期日"; break;
            }

            return(new TimeZoneGroupMappingInfo()
            {
                ID = id,
                DisplayOrder = index,
                Name = name,
                SelectedTimeGroupName = timeGroup.TimeGroupName,
                TimeGroupViewModel = new TimeGroupViewModel(timeGroup),
            });
        }
示例#11
0
        // POST api/customers
        public HttpResponseMessage Post([FromBody] TimeGroup timeGroupInfo)
        {
            return(ActionWarpper.Process(timeGroupInfo, OperationCodes.ATMGP, () =>
            {
                var timeGroupRepo = RepositoryManager.GetRepository <ITimeGroupRepository>();
                var timeGroupSegmentRepo = RepositoryManager.GetRepository <ITimeGroupSegmentRepository>();
                var timeSegmentRepo = RepositoryManager.GetRepository <ITimeSegmentRepository>();

                if (timeGroupInfo == null)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, "TimeGroupInfo is null");
                }

                if (timeGroupInfo.TimeSegments != null && timeGroupInfo.TimeSegments.Any())
                {
                    foreach (var timeSegment in timeGroupInfo.TimeSegments.Where(s => timeSegmentRepo.GetByKey(s.TimeSegmentID) == null))
                    {
                        return Request.CreateResponse(HttpStatusCode.BadRequest, string.Format("TimeSegment Id = {0} does not exist yet.", timeSegment.TimeSegmentID));
                    }
                }

                if (timeGroupRepo.Query(new Hashtable()
                {
                    { "TimeGroupCode", timeGroupInfo.TimeGroupCode }
                }).Any())
                {
                    return new HttpResponseMessage(HttpStatusCode.BadRequest)
                    {
                        Content = new StringContent(string.Format("系统中已经存在编号为{0}的时间组", timeGroupInfo.TimeGroupCode)),
                        ReasonPhrase = ConstStrings.BusinessLogicError,
                    };
                }

                timeGroupRepo.Insert(timeGroupInfo);
                timeGroupInfo.TimeSegments.ForEach(g => timeGroupSegmentRepo.Insert(new TimeGroupSegment {
                    TimeGroupID = timeGroupInfo.TimeGroupID, TimeSegmentID = g.TimeSegmentID
                }));


                return Request.CreateResponse(HttpStatusCode.OK, timeGroupInfo);
            }, this));
        }
        private async Task <IActionResult> GetMetrics(
            IMetricRepository metricRepository,
            DateTime start,
            DateTime?end        = null,
            TimeGroup timeGroup = TimeGroup.None)
        {
            if (TimeSpanTooLarge(start, end, timeGroup))
            {
                return(BadRequest("Time range is too large for the current resolution"));
            }

            if (end.HasValue && end.Value < start)
            {
                return(BadRequest("Time range is negative (To is smaller than From)"));
            }

            var user = await userManager.GetUserAsync(User);

            var raspberryPiId = await GetRaspberryPiId(user);

            if (!raspberryPiId.HasValue)
            {
                return(NotFound("Either the user does not exist or the user does not have a raspberry pi"));
            }

            var settings = await dbSettingsRepository.GetSettingsAsync(user.Id) ?? new Settings();

            var dbMetrics = (await metricRepository.GetMetrics(raspberryPiId.Value, start, end, settings.TimeZoneId))
                            .ToList();

            if (!dbMetrics.Any())
            {
                return(Ok(new
                {
                    QueryTimestamp = DateTime.UtcNow.AddSeconds(1).ToString("o"),
                    Timestamps = new string[0],
                    Usage = new int[0],
                    Solar = new int[0],
                    Redelivery = new int[0],
                    Intake = new int[0],
                }));
            }

            var format = "";
            List <OutMetricModel> metrics;

            switch (timeGroup)
            {
            case TimeGroup.TenSeconds:
            case TimeGroup.Minutes:
                format = "HH:mm:ss";

                metrics = dbMetrics
                          .Select(d => new OutMetricModel
                {
                    DateTime   = d.Created,
                    Gas        = d.UsageGasNow,
                    Intake     = d.UsageNow,
                    Redelivery = d.RedeliveryNow,
                    Solar      = d.SolarNow,
                    Usage      = d.UsageNow + d.SolarNow - d.RedeliveryNow
                })
                          .ToList();
                break;

            case TimeGroup.Hours:
                format = "MM-dd HH:mm";

                metrics = dbMetrics
                          .Select(d => new OutMetricModel
                {
                    DateTime   = d.Created,
                    Gas        = d.UsageGasNow,
                    Intake     = d.UsageNow,
                    Redelivery = d.RedeliveryNow,
                    Solar      = d.SolarNow,
                    Usage      = d.UsageNow + d.SolarNow - d.RedeliveryNow
                })
                          .ToList();
                break;

            case TimeGroup.Days:
                metrics = dbMetrics
                          .GroupBy(m => m.Created.Date)
                          .Select(m => new
                {
                    First         = m.First(),
                    Last          = m.Last(),
                    SolarTotalMin = m.Any(a => a.SolarTotal > 0) ? m.Where(a => a.SolarTotal > 0).Min(a => a.SolarTotal) : 0,
                    SolarTotalMax = m.Any(a => a.SolarTotal > 0) ? m.Where(a => a.SolarTotal > 0).Max(a => a.SolarTotal) : 0
                })
                          .SelectWithNextOrDefault((c, n) =>
                {
                    var current        = c.First;
                    var next           = n?.First ?? c.Last;
                    current.SolarTotal = c.SolarTotalMin > 0 ? c.SolarTotalMin : n?.SolarTotalMin ?? 0;
                    next.SolarTotal    = n?.SolarTotalMin > 0 ? n.SolarTotalMin : c.SolarTotalMax;

                    return(current.ToOutMetricModel(next, settings));
                })
                          .ToList();

                format = user.Settings.ShowDayName ? "yyyy-MM-dd (dddd)" : "yyyy-MM-dd";
                break;

            // case TimeGroup.Weeks:
            // break;
            case TimeGroup.Months:
                metrics = dbMetrics
                          .GroupBy(m => new
                {
                    m.Created.Date.Year,
                    m.Created.Month
                })
                          .Select(m => new
                {
                    First         = m.First(),
                    Last          = m.Last(),
                    SolarTotalMin = m.Any(a => a.SolarTotal > 0) ? m.Where(a => a.SolarTotal > 0).Min(a => a.SolarTotal) : 0,
                    SolarTotalMax = m.Any(a => a.SolarTotal > 0) ? m.Where(a => a.SolarTotal > 0).Max(a => a.SolarTotal) : 0
                })
                          .SelectWithNextOrDefault((c, n) =>
                {
                    var current        = c.First;
                    var next           = n?.First ?? c.Last;
                    current.SolarTotal = c.SolarTotalMin > 0 ? c.SolarTotalMin : n?.SolarTotalMin ?? 0;
                    next.SolarTotal    = n?.SolarTotalMin > 0 ? n.SolarTotalMin : c.SolarTotalMax;

                    return(current.ToOutMetricModel(next, settings));
                })
                          .ToList();

                format = "yyyy-MM";
                break;

            case TimeGroup.Years:
                metrics = dbMetrics
                          .GroupBy(m => new
                {
                    m.Created.Date.Year
                })
                          .Select(m => new
                {
                    First         = m.First(),
                    Last          = m.Last(),
                    SolarTotalMin = m.Any(a => a.SolarTotal > 0) ? m.Where(a => a.SolarTotal > 0).Min(a => a.SolarTotal) : 0,
                    SolarTotalMax = m.Any(a => a.SolarTotal > 0) ? m.Where(a => a.SolarTotal > 0).Max(a => a.SolarTotal) : 0
                })
                          .SelectWithNextOrDefault((c, n) =>
                {
                    var current        = c.First;
                    var next           = n?.First ?? c.Last;
                    current.SolarTotal = c.SolarTotalMin > 0 ? c.SolarTotalMin : n?.SolarTotalMin ?? 0;
                    next.SolarTotal    = n?.SolarTotalMin > 0 ? n.SolarTotalMin : c.SolarTotalMax;

                    return(current.ToOutMetricModel(next, settings));
                })
                          .ToList();

                format = "yyyy";
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(timeGroup), timeGroup, null);
            }

            var cultureInfo     = new System.Globalization.CultureInfo("nl-NL");
            var timestamps      = metrics.Select(m => m.DateTime.ToString(format, cultureInfo)).ToList();
            var usageList       = metrics.Select(m => m.Usage.DivideByThousand()).ToList();
            var intakeList      = metrics.Select(m => m.Intake.DivideByThousand()).ToList();
            var solarList       = metrics.Select(m => m.Solar.DivideByThousand()).ToList();
            var redeliveryList  = metrics.Select(m => m.Redelivery.DivideByThousand()).ToList();
            var gasList         = metrics.Select(m => m.Gas.DivideByThousand()).ToList();
            var usageCosts      = metrics.Select(m => m.UsageCost).ToList();
            var intakeCosts     = metrics.Select(m => m.IntakeCost).ToList();
            var redeliveryCosts = metrics.Select(m => m.RedeliveryCost).ToList();
            var gasCosts        = metrics.Select(m => m.GasCost).ToList();

            var lastDateTime = metrics
                               .OrderBy(m => m.DateTime)
                               .Select(m => m.DateTime)
                               .LastOrDefault();

            lastDateTime = lastDateTime.ConvertToUtc(settings.TimeZoneId);

            return(Ok(new
            {
                QueryTimestamp = lastDateTime.AddSeconds(1).ToString("o"),
                Timestamps = timestamps,
                Usage = usageList,
                Solar = solarList,
                Redelivery = redeliveryList,
                Intake = intakeList,
                Gas = gasList,
                UsageCosts = usageCosts,
                IntakeCosts = intakeCosts,
                RedeliveryCosts = redeliveryCosts,
                GasCosts = gasCosts
            }));
        }
示例#13
0
 public IEnumerable<int> GetApplicationErrorAggregate(TimeGroup timefilter, DateTime fromDate, DateTime toDate)
 {
     var domainResult = aggregationEngine.GetApplicationErrorAggregate(timefilter, fromDate, toDate).ToList();
     //return domainResult.Select(mapping.Map<Domain.ApplicationErrorAggregate, Model.ApplicationErrorAggregate>);
     return new List<int> ();
 }
示例#14
0
        // PUT api/customers/5
        public HttpResponseMessage Put(int id, [FromBody] TimeGroup timeGroupInfo)
        {
            return(ActionWarpper.Process(timeGroupInfo, OperationCodes.MTMGP, () =>
            {
                if (timeGroupInfo == null)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, "timeGroupInfo is null");
                }
                timeGroupInfo.TimeGroupID = id;

                var timeGroupRepo = RepositoryManager.GetRepository <ITimeGroupRepository>();
                var timeGroupSegmentRepo = RepositoryManager.GetRepository <ITimeGroupSegmentRepository>();
                var timeSegmentRepo = RepositoryManager.GetRepository <ITimeSegmentRepository>();

                var originaltimeGroupInfo = timeGroupRepo.GetByKey(id);
                if (originaltimeGroupInfo == null)
                {
                    return Request.CreateResponse(HttpStatusCode.BadRequest, string.Format("TimeGroup Id={0} does not exist.", id));
                }

                if (timeGroupRepo.Query(new Hashtable()
                {
                    { "TimeGroupCode", timeGroupInfo.TimeGroupCode }
                }).Any(x => x.TimeGroupID != id))
                {
                    return new HttpResponseMessage(HttpStatusCode.BadRequest)
                    {
                        Content = new StringContent(string.Format("系统中已经存在编号为{0}的时间组", timeGroupInfo.TimeGroupCode)),
                        ReasonPhrase = ConstStrings.BusinessLogicError,
                    };
                }

                IList <TimeSegment> addedTimeSegments = new List <TimeSegment>();
                IList <TimeSegment> deletedTimeSegments = new List <TimeSegment>();

                if (timeGroupInfo.TimeSegments != null && timeGroupInfo.TimeSegments.Any())
                {
                    var originalTimeSegmentIds = originaltimeGroupInfo.TimeSegments.Select(s => s.TimeSegmentID);
                    var targetTimeSegmentds = timeGroupInfo.TimeSegments.Select(s => s.TimeSegmentID);

                    addedTimeSegments =
                        timeGroupInfo.TimeSegments.FindAll(s => originalTimeSegmentIds.Contains(s.TimeSegmentID) == false);

                    deletedTimeSegments =
                        originaltimeGroupInfo.TimeSegments.FindAll(s => targetTimeSegmentds.Contains(s.TimeSegmentID) == false);

                    foreach (var addedtimeSegment in addedTimeSegments.Where(s => timeSegmentRepo.GetByKey(s.TimeSegmentID) == null))
                    {
                        return Request.CreateResponse(HttpStatusCode.BadRequest, string.Format("TimeSegment Id = {0} does not exist yet.", addedtimeSegment.TimeSegmentID));
                    }
                }
                else
                {
                    deletedTimeSegments = originaltimeGroupInfo.TimeSegments;
                }

                foreach (var deletedTimeSegment in deletedTimeSegments)
                {
                    var binding = timeGroupSegmentRepo.Query(new Hashtable {
                        { "TimeGroupID", id }, { "TimeSegmentID", deletedTimeSegment.TimeSegmentID }
                    }).ToList();
                    binding.ForEach(b => timeGroupSegmentRepo.Delete(b.TimeGroupSegmentID));
                }
                foreach (var addedTimeSegment in addedTimeSegments)
                {
                    timeGroupSegmentRepo.Insert(new TimeGroupSegment()
                    {
                        TimeGroupID = id, TimeSegmentID = addedTimeSegment.TimeSegmentID
                    });
                }
                timeGroupRepo.Update(timeGroupInfo);

                return Request.CreateResponse(HttpStatusCode.OK);
            }, this));
        }