Beispiel #1
0
        /// <summary>
        /// Детализация по проверке - история
        /// </summary>
        public ActionResult UnittestDetailsHistory(Guid id)
        {
            var unitTestRepository = CurrentAccountDbContext.GetUnitTestRepository();
            var unittest           = unitTestRepository.GetById(id);

            var model = new UnittestDetailsHistoryModel()
            {
                Id = unittest.Id
            };

            var eventRepository = CurrentAccountDbContext.GetEventRepository();
            var statusEvents    = eventRepository.QueryAll(unittest.Id).Where(t => t.Category == EventCategory.UnitTestStatus).OrderByDescending(t => t.StartDate).Take(10).ToArray();

            var now = MvcApplication.GetServerDateTime();

            model.Statuses = statusEvents.Select(t => new UnittestDetailsHistoryModel.StatusModel()
            {
                EventId    = t.Id,
                StartDate  = t.StartDate,
                Duration   = t.GetDuration(now),
                Message    = t.GetUnitTestMessage(),
                Importance = t.Importance,
                Count      = t.Count
            }).ToArray();

            return(PartialView(model));
        }
        // Рисует диаграмму указанных статусов для типа события по одному компоненту
        public ActionResult ForEventType(Guid id, Guid eventTypeId, DateTime?fromDate, DateTime?toDate, bool?hideUptime)
        {
            var eDate = toDate ?? DateTime.Now;
            var sDate = fromDate ?? eDate.AddHours(-24);

            var eventType       = GetEventTypeById(eventTypeId);
            var eventRepository = CurrentAccountDbContext.GetEventRepository();

            var states = eventRepository.GetTimelineStates(id, eventTypeId, sDate, eDate);
            var items  = this.GetTimelineItemsByStates(states, sDate, eDate);
            var okTime = eventRepository.GetTimelineOkTime(states, sDate, eDate);

            var model = new TimelineModel()
            {
                Category    = eventType.Category,
                OwnerId     = id,
                DateFrom    = sDate,
                DateTo      = eDate,
                Items       = items,
                OkTime      = okTime,
                EventTypeId = eventTypeId,
                HideUptime  = hideUptime ?? false
            };

            return(PartialView("TimelinePartial", model));
        }
        protected ComponentsTreeItemModel GetTreeItemModel(
            SimplifiedComponent component,
            string[] expandedItems,
            DateTime from,
            DateTime to)
        {
            var eventRepository = CurrentAccountDbContext.GetEventRepository();
            var states          = eventRepository.GetTimelineStates(component.Id, EventCategory.ComponentExternalStatus, from, to);
            var okTime          = eventRepository.GetTimelineOkTime(states, from, to);
            var items           = this.GetTimelineItemsByStates(states, from, to);

            var result = new ComponentsTreeItemModel()
            {
                Id              = component.Id,
                ParentId        = component.ParentId,
                ComponentTypeId = component.ComponentTypeId,
                DisplayName     = component.DisplayName,
                SystemName      = component.SystemName,
                Path            = component.Path,
                From            = from,
                To              = to,
                OkTime          = okTime,
                Timeline        = new TimelineModel()
                {
                    Category = EventCategory.ComponentExternalStatus,
                    OwnerId  = component.Id,
                    DateFrom = from,
                    DateTo   = to,
                    Items    = items,
                    OkTime   = okTime
                }
            };

            // Изначально развёрнут только корень дерева
            var expanded = result.IsRoot;

            if (expandedItems.Contains(result.Id.ToString()))
            {
                expanded = true;
            }

            result.Expanded = expanded;

            // Если узел раскрыт, то загрузим содержимое
            if (result.Expanded)
            {
                if (result.Content == null)
                {
                    result.Content = GetTreeItemContentModel(component, expandedItems, from, to);
                }

                if (result.Content.Details == null)
                {
                    result.Content.Details = GetTreeItemDetailsModel(component, expandedItems, from, to);
                }
            }

            return(result);
        }
Beispiel #4
0
        /// <summary>
        /// Детализация по проверке - общее состояние
        /// </summary>
        public ActionResult UnittestDetailsState(Guid id)
        {
            var unitTestRepository = CurrentAccountDbContext.GetUnitTestRepository();
            var unittest           = unitTestRepository.GetById(id);

            var model = new UnittestDetailsStateModel()
            {
                Id                  = id,
                Status              = unittest.Bulb.Status,
                StatusEventId       = unittest.Bulb.StatusEventId,
                StatusDuration      = unittest.Bulb.GetDuration(MvcApplication.GetServerDateTime()),
                CanRun              = unittest.IsSystemType,
                CanEdit             = CurrentUser.CanEditCommonData(),
                IsEnabled           = unittest.Enable,
                TypeId              = unittest.TypeId,
                LastExecutionDate   = unittest.Bulb.EndDate,
                LastExecutionResult = unittest.Bulb.GetUnitTestMessage()
            };

            if (model.TypeId == SystemUnitTestTypes.HttpUnitTestType.Id)
            {
                model.RuleData = unittest.HttpRequestUnitTest?.Rules.FirstOrDefault()?.Url;
            }
            else if (model.TypeId == SystemUnitTestTypes.PingTestType.Id)
            {
                model.RuleData = unittest.PingRule?.Host;
            }
            else if (model.TypeId == SystemUnitTestTypes.DomainNameTestType.Id)
            {
                model.RuleData = unittest.DomainNamePaymentPeriodRule?.Domain;
            }
            else if (model.TypeId == SystemUnitTestTypes.SslTestType.Id)
            {
                model.RuleData = unittest.SslCertificateExpirationDateRule?.Url;
            }
            else if (model.TypeId == SystemUnitTestTypes.SqlTestType.Id)
            {
                model.RuleData = unittest.SqlRule?.Query;
            }

            var eventRepository          = CurrentAccountDbContext.GetEventRepository();
            var lastExecutionResultEvent = eventRepository.QueryAll(unittest.Id).Where(t => t.Category == EventCategory.UnitTestResult).OrderByDescending(t => t.StartDate).FirstOrDefault();

            if (lastExecutionResultEvent != null && lastExecutionResultEvent.Properties.Count > 0)
            {
                model.LastExecutionResultProperties = ExtentionPropertiesModel.Create(lastExecutionResultEvent);
            }

            return(PartialView(model));
        }
Beispiel #5
0
        public ActionResult LastError(Guid eventTypeId)
        {
            var repository = CurrentAccountDbContext.GetEventRepository();
            var lastEvent  = repository.GetLastEventByEndDate(eventTypeId);
            var model      = new DefectLastErrorModel()
            {
                Event = lastEvent
            };

            if (lastEvent != null)
            {
                model.Component = GetComponentById(lastEvent.OwnerId);
            }
            return(PartialView(model));
        }
Beispiel #6
0
        public PartialViewResult LastEventInfo(Guid id)
        {
            var eventRepository = CurrentAccountDbContext.GetEventRepository();
            var lastEvent       = eventRepository.GetLastEventByEndDate(id);

            if (lastEvent == null)
            {
                return(PartialView("NoLastEventInfo"));
            }

            var model = new EventTypeLastEventModel()
            {
                Id      = lastEvent.Id,
                EndDate = lastEvent.EndDate,
                Message = lastEvent.Message
            };

            model.Properties = ExtentionPropertiesModel.Create(lastEvent);

            // событие метрики
            if (lastEvent.Category.IsMetricCategory())
            {
                var metricRepository = CurrentAccountDbContext.GetMetricRepository();
                var metric           = metricRepository.GetById(lastEvent.OwnerId);
                model.Metric    = metric;
                model.Component = metric.Component;
            }
            // событие проверки
            else if (lastEvent.Category.IsUnitTestCategory())
            {
                var unitTestRepository = CurrentAccountDbContext.GetUnitTestRepository();
                var unitTest           = unitTestRepository.GetById(lastEvent.OwnerId);
                model.Unittest  = unitTest;
                model.Component = unitTest.Component;
            }
            else // событие компонента
            {
                var componentRepository = CurrentAccountDbContext.GetComponentRepository();
                model.Component = componentRepository.GetById(lastEvent.OwnerId);
            }

            return(PartialView(model));
        }
Beispiel #7
0
        /// <summary>
        /// Детализация по проверке - результаты
        /// </summary>
        public ActionResult UnittestDetailsResults(Guid id)
        {
            var unitTestRepository = CurrentAccountDbContext.GetUnitTestRepository();
            var unittest           = unitTestRepository.GetById(id);

            var model = new UnittestDetailsResultsModel()
            {
                Id = unittest.Id
            };

            var eventRepository = CurrentAccountDbContext.GetEventRepository();
            var resultEvents    = eventRepository.QueryAll(unittest.Id).Where(t => t.Category == EventCategory.UnitTestResult).OrderByDescending(t => t.StartDate).Take(10).ToArray();

            model.Results = resultEvents.Select(t => new UnittestDetailsResultsModel.ResultModel()
            {
                Date       = t.StartDate,
                Importance = t.Importance,
                Message    = t.GetUnitTestMessage(),
                EventId    = t.Id
            }).ToArray();

            return(PartialView(model));
        }
        // Рисует диаграмму указанных статусов для владельца
        protected ActionResult ForOwner(Guid ownerId, EventCategory category, DateTime?fromDate, DateTime?toDate)
        {
            var eDate = toDate ?? DateTime.Now;
            var sDate = fromDate ?? eDate.AddHours(-24);

            var eventRepository = CurrentAccountDbContext.GetEventRepository();

            var states = eventRepository.GetTimelineStates(ownerId, category, sDate, eDate);
            var items  = this.GetTimelineItemsByStates(states, sDate, eDate);
            var okTime = eventRepository.GetTimelineOkTime(states, sDate, eDate);

            var model = new TimelineModel()
            {
                Category = category,
                OwnerId  = ownerId,
                DateFrom = sDate,
                DateTo   = eDate,
                Items    = items,
                OkTime   = okTime
            };

            return(PartialView("TimelinePartial", model));
        }
        // Рисует диаграмму указанных статусов для типа события независимо от компонента
        public ActionResult ForEventTypeAnyComponents(Guid eventTypeId, DateTime?fromDate, DateTime?toDate)
        {
            var eDate = toDate ?? DateTime.Now;
            var sDate = fromDate ?? eDate.AddHours(-24);

            var eventRepository = CurrentAccountDbContext.GetEventRepository();

            var states = eventRepository.GetTimelineStatesAnyComponents(eventTypeId, sDate, eDate);
            var items  = this.GetTimelineItemsByStates(states, sDate, eDate);
            var okTime = eventRepository.GetTimelineOkTime(states, sDate, eDate);

            var model = new TimelineModel()
            {
                Category    = null,
                OwnerId     = null,
                DateFrom    = sDate,
                DateTo      = eDate,
                Items       = items,
                OkTime      = okTime,
                EventTypeId = eventTypeId
            };

            return(PartialView("TimelinePartial", model));
        }
        protected ComponentsTreeItemDetailsModel GetTreeItemDetailsModel(
            SimplifiedComponent component,
            string[] expandedItems,
            DateTime from,
            DateTime to)
        {
            var eventRepository = CurrentAccountDbContext.GetEventRepository();

            var eventsStates = eventRepository.GetTimelineStates(component.Id, EventCategory.ComponentEventsStatus, from, to);
            var eventsOkTime = eventRepository.GetTimelineOkTime(eventsStates, from, to);
            var eventsItems  = this.GetTimelineItemsByStates(eventsStates, from, to);

            var unittestsStates = eventRepository.GetTimelineStates(component.Id, EventCategory.ComponentUnitTestsStatus, from, to);
            var unittestsOkTime = eventRepository.GetTimelineOkTime(unittestsStates, from, to);
            var unittestsItems  = this.GetTimelineItemsByStates(unittestsStates, from, to);

            var metricsStates = eventRepository.GetTimelineStates(component.Id, EventCategory.ComponentMetricsStatus, from, to);
            var metricsOkTime = eventRepository.GetTimelineOkTime(metricsStates, from, to);
            var metricsItems  = this.GetTimelineItemsByStates(metricsStates, from, to);

            var result = new ComponentsTreeItemDetailsModel()
            {
                Id             = component.Id,
                HasEvents      = component.HasEvents,
                EventsOkTime   = eventsOkTime,
                EventsTimeline = new TimelineModel()
                {
                    Category = EventCategory.ComponentEventsStatus,
                    OwnerId  = component.Id,
                    DateFrom = from,
                    DateTo   = to,
                    Items    = eventsItems,
                    OkTime   = eventsOkTime
                },
                From = from,
                To   = to,
                Path = component.Path,

                Unittests = new ComponentsTreeItemUnittestsDetailsModel()
                {
                    Id    = component.Id,
                    Items = component.Unittests
                            .Select(t => new ComponentsTreeItemUnittestsDetailsItemModel()
                    {
                        Id          = t.Id,
                        DisplayName = t.DisplayName
                    })
                            .ToArray()
                },
                UnittestsOkTime   = unittestsOkTime,
                UnittestsTimeline = new TimelineModel()
                {
                    Category = EventCategory.ComponentUnitTestsStatus,
                    OwnerId  = component.Id,
                    DateFrom = from,
                    DateTo   = to,
                    Items    = unittestsItems,
                    OkTime   = unittestsOkTime
                },

                Metrics = new ComponentsTreeItemMetricsDetailsModel()
                {
                    Id    = component.Id,
                    Items = component.Metrics
                            .Select(t => new ComponentsTreeItemMetricsDetailsItemModel()
                    {
                        Id          = t.Id,
                        DisplayName = t.DisplayName
                    })
                            .ToArray()
                },
                MetricsOkTime   = metricsOkTime,
                MetricsTimeline = new TimelineModel()
                {
                    Category = EventCategory.ComponentMetricsStatus,
                    OwnerId  = component.Id,
                    DateFrom = from,
                    DateTo   = to,
                    Items    = metricsItems,
                    OkTime   = metricsOkTime
                }
            };

            foreach (var unittest in result.Unittests.Items)
            {
                var unittestStates = eventRepository.GetTimelineStates(unittest.Id, EventCategory.UnitTestStatus, from, to);
                unittest.OkTime = eventRepository.GetTimelineOkTime(unittestStates, from, to);
                var unittestItems = this.GetTimelineItemsByStates(unittestStates, from, to);
                unittest.Timeline = new TimelineModel()
                {
                    Category = EventCategory.UnitTestStatus,
                    OwnerId  = unittest.Id,
                    DateFrom = from,
                    DateTo   = to,
                    Items    = unittestItems,
                    OkTime   = unittest.OkTime
                };
            }
            result.Unittests.Items = result.Unittests.Items.OrderBy(t => t.OkTime).ToArray();

            foreach (var metric in result.Metrics.Items)
            {
                var metricStates = eventRepository.GetTimelineStates(metric.Id, EventCategory.MetricStatus, from, to);
                metric.OkTime = eventRepository.GetTimelineOkTime(metricStates, from, to);
                var metricItems = this.GetTimelineItemsByStates(metricStates, from, to);
                metric.Timeline = new TimelineModel()
                {
                    Category = EventCategory.MetricStatus,
                    OwnerId  = metric.Id,
                    DateFrom = from,
                    DateTo   = to,
                    Items    = metricItems,
                    OkTime   = metric.OkTime
                };
            }
            result.Metrics.Items = result.Metrics.Items.OrderBy(t => t.OkTime).ToArray();

            result.Unittests.Expanded = expandedItems.Contains(result.Unittests.HtmlId);
            result.Metrics.Expanded   = expandedItems.Contains(result.Metrics.HtmlId);

            return(result);
        }
Beispiel #11
0
        public ActionResult Index(
            DefectsIndexModel.ShowModeEnum?showMode,
            Guid?userId,
            Guid?componentId,
            string title)
        {
            var model = new DefectsIndexModel()
            {
                ShowMode    = showMode ?? DefectsIndexModel.ShowModeEnum.InWork,
                UserId      = userId,
                ComponentId = componentId,
                Title       = title
            };

            // Подготовим базовый запрос

            var baseQuery = CurrentAccountDbContext.Defects.AsQueryable()
                            .Include("LastChange").Include("ResponsibleUser").Include("EventType");

            if (!string.IsNullOrEmpty(model.Title))
            {
                baseQuery = baseQuery.Where(t => t.Title.Contains(model.Title));
            }

            // Получим базовую информацию по дефектам
            var defects = baseQuery.Select(t => new DefectsIndexItemModel()
            {
                Id                = t.Id,
                EventTypeId       = t.EventTypeId,
                LastChangeDate    = t.LastChange.Date,
                Status            = t.LastChange.Status,
                ResponsibleUserId = t.ResponsibleUserId,
                Code              = t.Number.ToString(),
                Comment           = t.LastChange.Comment,
                Title             = t.Title,
                ResponsibleUser   = t.ResponsibleUser,
                OldVersion        = t.EventType.OldVersion
            }).ToArray();

            // Отфильтруем дефекты по компоненту
            var filteredDefects = new List <DefectsIndexItemModel>();
            var eventRepository = CurrentAccountDbContext.GetEventRepository();

            // Если заполнен фильтр по компоненту и это не Root, то получим Id по этого компонента и всех вложенных
            var useComponentFilter = model.ComponentId.HasValue && model.ComponentId.Value != GetCurrentAccount().RootId;

            Guid[] componentIds = null;
            if (useComponentFilter)
            {
                componentIds = GetDispatcherClient().GetComponentAndChildIds(CurrentUser.AccountId, model.ComponentId.Value).Data;
            }

            foreach (var defect in defects)
            {
                // Посчитаем, сколько раз случался дефект
                var query = eventRepository.QueryAllByAccount();
                query = query.Where(t => t.EventTypeId == defect.EventTypeId);

                // Если настроена версионность, то посчитаем только "новые" события
                if (defect.OldVersion != null)
                {
                    var oldVersion = VersionHelper.FromString(defect.OldVersion) ?? -1;
                    query = query.Where(t => (t.VersionLong ?? long.MaxValue) > oldVersion);
                }

                // Группируем по компоненту, чтобы посчитать количество для выбранного компонента и вложенных
                var resultQuery = query.GroupBy(t => t.OwnerId).Select(t => new { ComponentId = t.Key, Count = t.Sum(x => x.Count) }).ToArray();

                if (useComponentFilter)
                {
                    defect.Count = resultQuery.Where(t => componentIds.Contains(t.ComponentId)).Sum(t => t.Count);

                    // Если заполнен фильтр по компоненту и таких событий нет, то этот дефект не показываем
                    if (defect.Count == 0)
                    {
                        continue;
                    }
                }
                else
                {
                    defect.Count = resultQuery.Sum(t => t.Count);
                }

                filteredDefects.Add(defect);
            }

            // Подготовим условия для каждого фильтра

            Expression <Func <DefectsIndexItemModel, bool> > inWorkFilter  = x => DefectsIndexModel.InWorkStatuses.Contains(x.Status);
            Expression <Func <DefectsIndexItemModel, bool> > testingFilter = x => x.Status == DefectStatus.Testing;
            Expression <Func <DefectsIndexItemModel, bool> > closedFilter  = x => x.Status == DefectStatus.Closed;

            Expression <Func <DefectsIndexItemModel, bool> > modeFilter = null;

            if (model.ShowMode == DefectsIndexModel.ShowModeEnum.InWork)
            {
                modeFilter = inWorkFilter;
            }
            else if (model.ShowMode == DefectsIndexModel.ShowModeEnum.Testing)
            {
                modeFilter = testingFilter;
            }
            else if (model.ShowMode == DefectsIndexModel.ShowModeEnum.Closed)
            {
                modeFilter = closedFilter;
            }

            Expression <Func <DefectsIndexItemModel, bool> > userFilter = null;

            if (model.UserId.HasValue)
            {
                userFilter = x => x.ResponsibleUserId == model.UserId;
            }

            // Посчитаем количество для каждого варианта фильтра по статусу

            var modeFilterCountQuery = filteredDefects.AsQueryable();

            if (userFilter != null)
            {
                modeFilterCountQuery = modeFilterCountQuery.Where(userFilter);
            }

            model.InWorkCount  = modeFilterCountQuery.Count(inWorkFilter);
            model.TestingCount = modeFilterCountQuery.Count(testingFilter);
            model.ClosedCount  = modeFilterCountQuery.Count(closedFilter);

            // Отберём данные по фильтрам

            var defectsQuery = filteredDefects.AsQueryable();

            if (userFilter != null)
            {
                defectsQuery = defectsQuery.Where(userFilter);
            }

            if (modeFilter != null)
            {
                defectsQuery = defectsQuery.Where(modeFilter);
            }

            model.Items = defectsQuery.ToArray();

            model.Items      = model.Items.OrderByDescending(t => t.Count).ToArray();
            model.TotalCount = model.InWorkCount + model.TestingCount + model.ClosedCount;

            return(View(model));
        }
Beispiel #12
0
        /// <summary>
        /// Вывод списка событий
        /// </summary>
        public ActionResult Index(
            Guid?componentId               = null,
            Guid?componentTypeId           = null,
            ColorStatusSelectorValue color = null,
            Guid?eventTypeId               = null,
            EventCategory?category         = null,
            string search      = null,
            DateTime?fromDate  = null,
            DateTime?toDate    = null,
            Guid?unitTestId    = null,
            Guid?metricId      = null,
            string dataType    = null,
            string versionFrom = null)
        {
            var model = new EventsListModel()
            {
                ComponentId = componentId,
                Color       = color ?? new ColorStatusSelectorValue(),
                EventTypeId = eventTypeId,
                Category    = category,
                Search      = search,
                FromDate    = fromDate,
                ToDate      = toDate,
                VersionFrom = versionFrom
            };

            IQueryable <Event> eventsQuery;

            var componentRepository = CurrentAccountDbContext.GetComponentRepository();
            var eventRepository     = CurrentAccountDbContext.GetEventRepository();

            if (componentId.HasValue)
            {
                eventsQuery = eventRepository.QueryAll(componentId.Value);
            }
            else if (unitTestId.HasValue)
            {
                model.UnitTest = CurrentAccountDbContext.GetUnitTestRepository().GetById(unitTestId.Value);
                eventsQuery    = eventRepository.QueryAll(unitTestId.Value);
            }
            else if (metricId.HasValue)
            {
                model.Metric = CurrentAccountDbContext.GetMetricRepository().GetById(metricId.Value);
                eventsQuery  = eventRepository.QueryAll(metricId.Value);
            }
            else
            {
                if (componentTypeId.HasValue)
                {
                    // поиск по типу компонента
                    var componentIds = componentRepository
                                       .QueryAll()
                                       .Where(t => t.ComponentTypeId == componentTypeId)
                                       .Select(t => t.Id)
                                       .ToArray();
                    eventsQuery = eventRepository.QueryAllByComponentId(componentIds);
                }
                else
                {
                    //  все события аккаунта
                    eventsQuery = eventRepository.QueryAllByAccount();
                }
            }

            if (eventTypeId.HasValue)
            {
                eventsQuery = eventsQuery.Where(t => t.EventTypeId == eventTypeId.Value);
            }

            if (category.HasValue)
            {
                eventsQuery = eventsQuery.Where(t => t.Category == category.Value);
            }
            else
            {
                var categories = new[]
                {
                    EventCategory.ApplicationError,
                    EventCategory.ComponentEvent
                };
                eventsQuery = eventsQuery.Where(t => categories.Contains(t.Category));
            }

            if (model.Color.Checked)
            {
                var importanceLevels = color.GetSelectedEventImportances();
                eventsQuery = eventsQuery.Where(t => importanceLevels.Contains(t.Importance));
            }

            if (fromDate.HasValue)
            {
                eventsQuery = eventsQuery.Where(t => t.ActualDate >= fromDate.Value);
            }

            if (toDate.HasValue)
            {
                eventsQuery = eventsQuery.Where(t => t.StartDate <= toDate.Value);
            }

            if (!string.IsNullOrEmpty(search))
            {
                eventsQuery = eventsQuery.Where(t => t.Message != null && t.Message.Contains(search));
            }

            if (!string.IsNullOrEmpty(versionFrom))
            {
                var versionFromLong = VersionHelper.FromString(versionFrom) ?? -1;
                eventsQuery = eventsQuery.Where(t => (t.VersionLong ?? long.MaxValue) > versionFromLong);
            }

            eventsQuery = eventsQuery.OrderByDescending(t => t.StartDate);

            var eventsModel = eventsQuery.Select(t => new EventsListItemModel()
            {
                Id          = t.Id,
                Message     = t.Message,
                OwnerId     = t.OwnerId,
                Category    = t.Category,
                EventTypeId = t.EventTypeId,
                StartDate   = t.StartDate,
                Importance  = t.Importance,
                EndDate     = t.EndDate,
                ActualDate  = t.ActualDate,
                Count       = t.Count,
                JoinKey     = t.JoinKeyHash
            });

            model.Events = eventsModel;

            model.Components = componentRepository
                               .QueryAllWithDeleted()
                               .ToArray()
                               .Select(t => new EventsListComponentModel()
            {
                Id          = t.Id,
                DisplayName = t.DisplayName,
                SystemName  = t.SystemName,
                FullName    = t.GetFullDisplayName()
            })
                               .ToDictionary(t => t.Id, t => t);

            var eventTypeRepository = CurrentAccountDbContext.GetEventTypeRepository();

            model.EventTypes = eventTypeRepository
                               .QueryAllWithDeleted()
                               .Select(t => new EventsListEventTypeModel()
            {
                Id          = t.Id,
                DisplayName = t.DisplayName,
                SystemName  = t.SystemName,
                Code        = t.Code,
                Category    = t.Category
            })
                               .ToDictionary(t => t.Id, t => t);


            if (dataType == "xml")
            {
                var xmlEvents = model.GetXmlEvents(CurrentAccountDbContext);
                return(new ActionXmlFileResult(xmlEvents, "events.xml"));
            }

            return(View(model));
        }
Beispiel #13
0
        public PartialViewResult ShowTimelinesEventsPartial(Guid id, TimelineInterval interval, bool all = false)
        {
            var toDate   = MvcApplication.GetServerDateTime();
            var fromDate = TimelineHelper.IntervalToStartDate(toDate, interval);

            var eventTypeRepository = CurrentAccountDbContext.GetEventTypeRepository();
            var eventTypes          = eventTypeRepository.QueryAll().Select(t => new { t.Id, t.DisplayName }).ToDictionary(t => t.Id, t => t);
            var eventRepository     = CurrentAccountDbContext.GetEventRepository();

            var query = eventRepository.QueryAllByAccount()
                        .Where(t => t.OwnerId == id && t.StartDate <= toDate && t.ActualDate >= fromDate);

            if (all)
            {
                query = query.Where(t => t.Category == EventCategory.ApplicationError || t.Category == EventCategory.ComponentEvent);
            }
            else
            {
                query = query.Where(t => t.Category == EventCategory.ApplicationError);
            }

            var events = query
                         .GroupBy(t => t.EventTypeId)
                         .Select(t => new
            {
                Id          = t.Key,
                Importance  = t.Max(z => z.Importance),
                Count       = t.Sum(z => z.Count),
                LastMessage = t.OrderByDescending(z => z.StartDate).FirstOrDefault().Message
            })
                         .ToArray();

            var model = new ComponentShowTimelinesGroupModel()
            {
                FromDate   = fromDate,
                ToDate     = toDate,
                HideUptime = true,
                Items      = events
                             .Select(t => new
                {
                    Id          = t.Id,
                    Importance  = t.Importance,
                    Count       = t.Count,
                    Name        = eventTypes[t.Id].DisplayName,
                    LastMessage = t.LastMessage
                })
                             .OrderByDescending(t => t.Importance)
                             .ThenByDescending(t => t.Count)
                             .ThenBy(t => t.Name)
                             .Take(MaxEventTimelineCount)
                             .Select(t => new ComponentShowTimelinesGroupItemModel()
                {
                    Action      = "ForEventType",
                    Category    = null,
                    OwnerId     = id,
                    EventTypeId = t.Id,
                    Importance  = t.Importance,
                    Name        = t.Name,
                    Count       = t.Count,
                    Comment     = t.LastMessage,
                    Url         = Url.Action("Show", "EventTypes", new { Id = t.Id })
                })
                             .ToArray()
            };

            return(PartialView("~/Views/Components/ShowTimelinesPartialGroup.cshtml", model));
        }
Beispiel #14
0
        /// <summary>
        /// Статистика запусков
        /// </summary>
        public ActionResult Starts(Guid?componentTypeId = null, Guid?componentId = null, string fromDate = null, string toDate = null)
        {
            var sDate = !string.IsNullOrEmpty(fromDate) ? DecodeDateTimeParameter(fromDate) : (DateTime?)null;
            var eDate = !string.IsNullOrEmpty(toDate) ? DecodeDateTimeParameter(toDate) : (DateTime?)null;

            Component component           = null;
            var       componentRepository = CurrentAccountDbContext.GetComponentRepository();

            if (componentId.HasValue)
            {
                component = componentRepository.GetById(componentId.Value);
            }

            ComponentType componentType           = null;
            var           componentTypeRepository = CurrentAccountDbContext.GetComponentTypeRepository();

            if (componentTypeId.HasValue)
            {
                componentType = componentTypeRepository.GetById(componentTypeId.Value);
            }
            else
            {
                componentType = componentTypeRepository.QueryAll().Where(t => t.IsDeleted == false).OrderBy(t => t.DisplayName).FirstOrDefault();
            }

            EventType startEventType = null;

            Component[] components;
            var         items = new List <StartsReportItemModel>();
            var         graph = new List <StartsReportGrapthItemModel>();
            string      error = null;

            if (componentType != null)
            {
                if (component != null)
                {
                    components = new[] { component }
                }
                ;
                else
                {
                    components =
                        componentRepository.QueryAll()
                        .Where(t => t.ComponentTypeId == componentType.Id && t.IsDeleted == false)
                        .ToArray();
                }

                var componentsIds = components.Select(t => t.Id).ToArray();

                var eventTypeRepository = CurrentAccountDbContext.GetEventTypeRepository();
                startEventType = eventTypeRepository.GetOneOrNullBySystemName(SystemEventType.ComponentStart);
                if (startEventType != null)
                {
                    var startEventTypeId = startEventType.Id;
                    var listLockObject   = new Object();

                    var eventRepository = CurrentAccountDbContext.GetEventRepository();

                    // Все события запуска за указанный интервал
                    var allEventsQuery = eventRepository.QueryAllByComponentId(componentsIds)
                                         .Where(t => t.EventTypeId == startEventTypeId);
                    if (sDate.HasValue)
                    {
                        allEventsQuery = allEventsQuery.Where(t => t.StartDate >= sDate.Value);
                    }
                    if (eDate.HasValue)
                    {
                        allEventsQuery = allEventsQuery.Where(t => t.StartDate <= eDate.Value);
                    }

                    // События запуска по компонентам
                    var startEventsQuery =
                        allEventsQuery.Select(
                            t => new { Id = t.Id, StartDate = t.StartDate, ComponentId = t.OwnerId, Count = t.Count });
                    var startEvents = startEventsQuery.GroupBy(t => t.ComponentId).ToArray();

                    var list =
                        startEvents.Join(components, a => a.Key, b => b.Id, (a, b) => new { Component = b, Events = a })
                        .Select(t => new StartsReportItemModel()
                    {
                        ComponentId          = t.Component.Id,
                        ComponentDisplayName = t.Component.DisplayName,
                        ComponentSystemName  = t.Component.SystemName,
                        CreateDate           = t.Component.CreatedDate,
                        Version    = t.Component.Version,
                        FirstStart =
                            t.Events.OrderBy(x => x.StartDate).Select(x => x.StartDate).FirstOrDefault(),
                        FirstStartId = t.Events.OrderBy(x => x.StartDate).Select(x => x.Id).FirstOrDefault(),
                        LastStart    =
                            t.Events.OrderByDescending(x => x.StartDate)
                            .Select(x => x.StartDate)
                            .FirstOrDefault(),
                        LastStartId =
                            t.Events.OrderByDescending(x => x.StartDate).Select(x => x.Id).FirstOrDefault(),
                        Count = t.Events.Sum(x => x.Count)
                    }).ToList();

                    // События запуска по датам
                    var statsEventsQuery = allEventsQuery.Select(t => new { StartDate = t.StartDate, Count = t.Count });
                    var stats            =
                        statsEventsQuery.GroupBy(t => DbFunctions.TruncateTime(t.StartDate))
                        .Select(t => new StartsReportGrapthItemModel()
                    {
                        Date  = t.Key.Value,
                        Count = t.Sum(x => x.Count)
                    }).ToList();

                    lock (listLockObject)
                    {
                        items.AddRange(list);
                        graph.AddRange(stats);
                    }
                }
                else
                {
                    error = "У выбранного типа компонента нет типа события с системным именем '" +
                            SystemEventType.ComponentStart + "'";
                }
            }

            var model = new StartsReportModel()
            {
                AccountId        = CurrentUser.AccountId,
                ComponentId      = componentId,
                ComponentTypeId  = componentTypeId,
                FromDate         = sDate,
                ToDate           = eDate,
                Items            = items.OrderBy(t => t.ComponentDisplayName).ToList(),
                Graph            = graph.OrderBy(t => t.Date).ToList(),
                Error            = error,
                StartEventTypeId = startEventType != null ? startEventType.Id : (Guid?)null,
                Total            = items.Sum(t => t.Count)
            };

            return(View(model));
        }