示例#1
0
        /// <summary>
        /// Converts a competition domain entity to the response object (GetCompetition).
        /// </summary>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="GetCompetition"/>.
        /// </returns>
        public GetCompetition Convert(ResolutionContext context)
        {
            var competition = (Competition)context.SourceValue;
            var item = new GetCompetition();
            var statistics = new StatisticsItem();

            item.ClosingDate = competition.ClosingDate;
            item.CompetitionKey = competition.CompetitionKey;
            item.CreatedBy = Mapper.Map<User, GetUser>(competition.CreatedBy).Username;
            item.CreatedDate = competition.CreatedDate;
            item.Id = competition.ID;
            item.PossibleAnswers =
                Mapper.Map<PossibleAnswers, IEnumerable<PossibleAnswerItem>>(competition.PossibleAnswers);
            item.Question = competition.Question;
            item.Status = competition.Status.ToString();

            statistics.CorrectCount = competition.CorrectEntrants.Count();
            statistics.IncorrectCount = competition.IncorrectEntrants.Count();
            statistics.AnswerAPercentage = competition.GetPercentageOfEntrants(CompetitionAnswer.A);
            statistics.AnswerBPercentage = competition.GetPercentageOfEntrants(CompetitionAnswer.B);
            statistics.AnswerCPercentage = competition.GetPercentageOfEntrants(CompetitionAnswer.C);
            statistics.AnswerDPercentage = competition.GetPercentageOfEntrants(CompetitionAnswer.D);

            statistics.AnswerACount = competition.GetNumberOfEntrants(CompetitionAnswer.A);
            statistics.AnswerBCount = competition.GetNumberOfEntrants(CompetitionAnswer.B);
            statistics.AnswerCCount = competition.GetNumberOfEntrants(CompetitionAnswer.C);
            statistics.AnswerDCount = competition.GetNumberOfEntrants(CompetitionAnswer.D);

            item.Statistics = statistics;

            return item;
        }
示例#2
0
        private void EventTriggered(object sender, EventsArgs <ScenarioValueChangedEventArgs> args)
        {
            if (args.Value.Scenario is RemoteScenario == false)
            {
                var newVal = args.Value.Scenario.GetCurrentValue();
                AddValueCache(args.Value.Scenario.Id, newVal);

                var item = new StatisticsItem();
                item.DateTime = DateTime.Now;

                item.Source = new StatisticsItemSource()
                {
                    ID         = args.Value.Source.User?.Id,
                    Name       = args.Value.Source.User?.Name,
                    SourceType = GetStartupSourceName(args.Value.Source.Source)
                };

                item.Target = new StatisticsScenarioInfo()
                {
                    ID            = args.Value.Scenario.Id,
                    Name          = args.Value.Scenario.Name,
                    ValueTypeName = ActionsDomain.Utils.GetValueTypeClassName(args.Value.Scenario.ValueType.GetType())
                };

                item.Value = newVal;

                AddItem(item);
            }
        }
示例#3
0
            public StatisticItemView(StatisticsItem item, StatisticsScenarioInfo info)
            {
                string getUnit()
                {
                    if (info.ValueTypeName == FloatValueTypeName)
                    {
                        return(((FloatValueType)Scenarios[info.ID].ValueType).Unit);
                    }
                    return(string.Empty);
                }

                string getValue()
                {
                    if (info.ValueTypeName == ToggleValueTypeName)
                    {
                        if (Value == ToggleValueType.ValueON)
                        {
                            return("Вкл.");
                        }
                        else
                        {
                            return("Выкл.");
                        }
                    }
                    return(item.Value + getUnit());
                }

                ScenarioName = info.Name;
                UserName     = item.SourceName;
                SourceType   = item.SourceType;
                DateTime     = item.DateTime;
                Value        = getValue();
            }
示例#4
0
        private void TimerTick()
        {
            //force update values
            if (DateTime.Now >= RefreshDate)
            {
                RefreshDate = DateTime.Now.AddDays(1);
                _scenariosValuesCache.Clear();
            }

            var statisticsScenarios = ScenariosRepository.Scenarios.Where(x => _statisticsScenariosInfos.Any(z => z.ScenarioId == x.Id)).ToArray();

            foreach (var scenario in statisticsScenarios.ToArray())
            {
                if (scenario.ValueType is ButtonValueType == false)
                {
                    var prevVal = GetValueCache(scenario.Id);
                    var newVal  = scenario.CalculateCurrentValue(SystemActionSource, null);
                    if (newVal != prevVal)
                    {
                        AddValueCache(scenario.Id, newVal);
                        var item = new StatisticsItem();
                        item.Value    = newVal;
                        item.DateTime = DateTime.Now;
                        AddItem(item, scenario, string.Empty);
                    }
                }
            }
        }
示例#5
0
 public void DeleteItem(StatisticsItem item)
 {
     if (items == null || items.Count == 0 || !items.Contains(item))
     {
         return;
     }
     items.Remove(item);
 }
示例#6
0
        public StatisticsItem[] GetItems(StatisticsScenarioInfo info, DateTime since, DateTime to, ScenarioActionSource source)
        {
            var scenario = ScenariosRepository.Scenarios.FirstOrDefault(x => x.Id == info.ID && ActionsDomain.Utils.GetValueTypeClassName(x.ValueType.GetType()) == info.ValueTypeName);

            if (scenario?.SecuritySettings.IsAvailableForUser(source.User, source.Source, source.Action) ?? false)
            {
                if (scenario is RemoteScenario remoteScenario)
                {
                    try
                    {
                        if (!scenario.GetIsAvailable())
                        {
                            throw new ScenarioExecutionException(ScenarioExecutionError.NotAvailable);
                        }
                        var remoteScenarioInfo = new StatisticsScenarioInfo()
                        {
                            Name          = remoteScenario.Name,
                            ID            = remoteScenario.RemoteScenarioId,
                            ValueTypeName = ActionsDomain.Utils.GetValueTypeClassName(remoteScenario.ValueType.GetType()),
                            Since         = DateTime.Now,
                            To            = DateTime.Now,
                        };
                        var server     = ClientFactory.GetServer(remoteScenario.Credentials);
                        var statistics = server.GetStatistics(since, to, new Encrypted <StatisticsScenarioInfo>(remoteScenarioInfo, remoteScenario.Credentials.SecretKey))
                                         .Decrypt(remoteScenario.Credentials.SecretKey)
                                         .ToArray();
                        foreach (var item in statistics)
                        {
                            //crutch
                            item.Target.ID   = remoteScenario.Id;
                            item.Target.Name = remoteScenario.Name;
                        }
                        return(statistics);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
                else
                {
                    return(_dataManager.GetDataItems(info.ID, info.ValueTypeName, since, to)
                           .Select(x =>
                    {
                        var item = new StatisticsItem();
                        item.Source = new StatisticsItemSource();
                        item.Source.SourceType = x.SourceType;
                        item.Source.Name = x.SourceName;
                        item.Source.ID = x.SourceId;
                        item.DateTime = new DateTime(x.Year, x.Month, x.Day, x.Hour, x.Minute, x.Second);
                        item.Value = x.Value;
                        item.Target = info;
                        return item;
                    }).ToArray());
                }
            }
            throw new ScenarioExecutionException(ScenarioExecutionError.AccessDenied);
        }
        /// <summary>
        /// Change metric value for the item
        /// </summary>
        /// <param name="framework">The framework name which statistics is being collected</param>
        /// <param name="item">The item which metrics value is changing</param>
        /// <param name="metrics">The metrics which value is changing</param>
        /// <param name="delta">The value by which the metrics value should be changed</param>
        public void AddMetric(string framework, StatisticsItem item, StatisticsMetrics metrics, int delta = 1)
        {
            if (!Storages.ContainsKey(framework))
            {
                Storages[framework] = new StatisticsStorage();
            }

            Storages[framework].AddMetric(item, metrics, delta);
        }
示例#8
0
    public List<StatisticsItem> FormSurveyStatisticsList()
    {
        List<StatisticsItem> statisticsItems = new List<StatisticsItem>();
        List<String> users = PollDAL.GetUsers();
        int surveyID = Convert.ToInt32(Request["id"]);
        Survey survey = PollDAL.GetSurvey(surveyID);
        foreach (String user in users)
        {
            List<DateTime> datesOfAttempts = new List<DateTime>();
            datesOfAttempts = PollDAL.GetDatesOfAttempts(user, surveyID);

            if (datesOfAttempts.Count != 0)
            {
                StatisticsItem curStatisticsItem = new StatisticsItem();
                curStatisticsItem.name = user;
                curStatisticsItem.ID = user;
                curStatisticsItem.attemptsCount = datesOfAttempts.Count();

                // Calculate count of scores
                List<Double> scoresOfAttempts = new List<Double>();

                foreach (DateTime curDate in datesOfAttempts)
                {
                    SurveyResults resultsList = new SurveyResults();
                    resultsList = PollDAL.GetSurveyResults(surveyID, user, curDate);

                    int countOfCorrectAnswers = 0;

                    foreach (PollResult curResult in resultsList.results)
                    {
                        Poll currentPoll = survey.Polls.Find(delegate(Poll poll) { return poll.Id == curResult.questionId; });
                        if (currentPoll.CorrectChoiceID == curResult.answerId)
                            countOfCorrectAnswers++;
                    }

                    Double curScores = Convert.ToDouble(countOfCorrectAnswers) / Convert.ToDouble(resultsList.results.Count);
                    scoresOfAttempts.Add(curScores);
                }

                Double scores = 0;

                foreach (Double curScores in scoresOfAttempts)
                {
                    scores += curScores;
                }

                scores /= Convert.ToDouble(datesOfAttempts.Count) / 100;
                curStatisticsItem.scores = scores;
                statisticsItems.Add(curStatisticsItem);
            }
        }

        // Sort by scores
        statisticsItems.Sort();

        return statisticsItems;
    }
        public Statistics GetStatisticsByLogin(string login, StatisticsOptions options)
        {
            using (var context = new HsrTechContext())
            {
                HsrTechADO connection = new HsrTechADO(context.Database.Connection.ConnectionString);
                var        clientId   = getClientIdByLogin(login, connection);

                var select = $@"
                    COUNT(*) AS 'Count',
                    DATEPART(YEAR, OpenDate) AS 'Year',
                    DATEPART(MONTH, OpenDate) AS 'Month',
                    DATEPART(DAY, OpenDate) AS 'Day'
                ";

                var groupby = $@"
                    DATEPART(DAY, OpenDate),
                    DATEPART(MONTH, OpenDate),
                    DATEPART(YEAR, OpenDate)
                ";

                var orderby = $@"'Year', 'Month', 'Day'";

                if (options.GroupMode == StatisticsOptionsGroupModes.HOURS)
                {
                    select  += ", DATEPART(HOUR, OpenDate) AS 'Hour'";
                    groupby  = "DATEPART(HOUR, OpenDate), " + groupby;
                    orderby += ", 'Hour'";
                }
                else if (options.GroupMode == StatisticsOptionsGroupModes.MINUTES)
                {
                    select  += ", DATEPART(HOUR, OpenDate) AS 'Hour', DATEPART(MINUTE, OpenDate) AS 'Minute'";
                    groupby  = "DATEPART(HOUR, OpenDate), DATEPART(MINUTE, OpenDate), " + groupby;
                    orderby += ", 'Hour', 'Minute'";
                }

                var data = connection.ExecuteQuery
                               ($@" SELECT {select} FROM BankAccount WHERE ClientId = {clientId} GROUP BY {groupby} ORDER BY {orderby}");

                List <StatisticsItem> listItems = new List <StatisticsItem>();
                foreach (var item in data)
                {
                    var            property  = item as Dictionary <string, object>;
                    StatisticsItem statistic = new StatisticsItem(
                        int.Parse(property.ValueAsString("Year")),
                        int.Parse(property.ValueAsString("Month")),
                        int.Parse(property.ValueAsString("Day")),
                        (int)options.GroupMode > 0 ? int.Parse(property.ValueAsString("Hour")) : 0,
                        (int)options.GroupMode > 1 ? int.Parse(property.ValueAsString("Minute")) : 0,
                        int.Parse(property.ValueAsString("Count"))
                        );

                    listItems.Add(statistic);
                }
                return(new Statistics(options, listItems));
            }
        }
示例#10
0
 public StatisticsItem GetTodayStatisticItem()
 {
     StatisticsItem si;
     si = StatByDay.Where((x) => x.Date == DateTime.Today.Date).FirstOrDefault();
     if (si == null)
     {
         si = new StatisticsItem();
         StatByDay.Add(si);
     }
     return si;
 }
 private string GetValue(StatisticsItem item)
 {
     if (item.Target.ValueTypeName == Lazurite.ActionsDomain.Utils.GetValueTypeClassName(typeof(ToggleValueType)))
     {
         return(item.Value == ToggleValueType.ValueOFF ? "Выкл." : "Вкл.");
     }
     else
     {
         return(item.Value);
     }
 }
示例#12
0
 private void AddItem(StatisticsItem item, ScenarioBase scenario, string sourceId)
 {
     try
     {
         var dataItem = new StatisticsDataItem(sourceId, item.SourceName, item.SourceType ?? "Система", item.Value, (byte)item.DateTime.Hour, (byte)item.DateTime.Minute, (byte)item.DateTime.Second);
         _dataManager.SetItem(scenario.Id, ActionsDomain.Utils.GetValueTypeClassName(scenario.ValueType.GetType()), dataItem);
     }
     catch (Exception e)
     {
         Log.Error($"Ошибка во время записи значения сценария в файлы статистики. Сценарий: [{scenario.Id}]", e);
     }
 }
示例#13
0
        public void Reset()
        {
            _statistics = new StatisticsItem[Size];
            for (var i = 0; i < Size; i++)
            {
                _statistics[i] = new StatisticsItem();
            }

            _correctedStatistics = null;

            Count = 0;
        }
示例#14
0
 private string GetStatAsString(StatisticsItem StatItem)
 {
     if (StatItem == null) return "";
     string Text =
         "Всего \n" +
         "Слов собрано   : " + StatItem.TotalWordsCollected + "\n" +
         "Фраз собрано   : " + StatItem.TotalPhrasesCollected + "\n" +
         "Ошибок         : " + StatItem.TotalFailToCollectWord + "\n" +
         "Процент ошибок : " + Math.Round(StatItem.PercentOfErrors, 1) + "%" +
         "   \n   \n";
     return Text;
 }
示例#15
0
 private void AddItem(StatisticsItem item)
 {
     try
     {
         var dataItem = new StatisticsDataItem(item.Source?.ID, item.Source?.Name, item.Source?.SourceType ?? "Система", item.Value, (byte)item.DateTime.Hour, (byte)item.DateTime.Minute, (byte)item.DateTime.Second);
         _dataManager.SetItem(item.Target.ID, item.Target.ValueTypeName, dataItem);
     }
     catch (Exception e)
     {
         Log.ErrorFormat(e, "Ошибка во время записи значения сценария в файлы статистики. Сценарий: [\"{0}\"]", item.Target.ID);
     }
 }
示例#16
0
        public static StatisticsItem Sum(this IEnumerable <StatisticsItem> items, DateTime time)
        {
            var item = new StatisticsItem(time)
            {
                BytesUp                = items.Sum(s => s.BytesUp),
                BytesDown              = items.Sum(s => s.BytesDown),
                ConnectionCount        = items.Sum(s => s.ConnectionCount),
                SuccessConnectionCount = items.Sum(s => s.SuccessConnectionCount),
                FailedConnectionCount  = items.Sum(s => s.FailedConnectionCount)
            };

            return(item);
        }
示例#17
0
        public void WriteTest()
        {
            StatisticsWriter target            = new StatisticsWriter();
            string           referenceFilename = "Resources/statistics/statistics.xml";
            string           filename          = "Resources/statistics/statistics-neu.xml";

            Statistics expected = new Statistics();

            var date = new StatisticsDate(2012, 12, 15);
            var item = new StatisticsItem
            {
                Type      = StatisticsItemType.Song,
                Title     = "You are so faithful",
                Copyright = "Musik & Copyright unbekannt",
                CcliId    = "",
                Count     = 1
            };

            date.Items.Add(item.Identifier, item);
            expected.Dates.Add(date.Identifier, date);

            date = new StatisticsDate(2013, 1, 6);

            item = new StatisticsItem
            {
                Type      = StatisticsItemType.Song,
                Title     = "A Mighty Fortress Is Our God",
                Copyright = "Public Domain",
                CcliId    = "42964",
                Count     = 2
            };
            date.Items.Add(item.Identifier, item);

            item = new StatisticsItem
            {
                Type      = StatisticsItemType.Song,
                Title     = "You are so faithful",
                Copyright = "Musik & Copyright unbekannt",
                CcliId    = "",
                Count     = 1
            };
            date.Items.Add(item.Identifier, item);

            expected.Dates.Add(date.Identifier, date);

            target.Write(filename, expected);

            Assert.IsTrue(FileUtils.FileEquals(filename, referenceFilename));
        }
        public Statistics read(string filename)
        {
            var xmlDoc = new XmlDocument();

            xmlDoc.Load(filename);
            var xmlRoot = xmlDoc.DocumentElement;

            if (xmlRoot.Name != "statistics" ||
                (xmlRoot.Attributes["version"] == null || xmlRoot.Attributes["version"].Value != "1.0"))
            {
                throw new Exception("Ungültige Statistikdatei!");
            }
            var sl = new Statistics();

            for (var i = 0; i < xmlRoot.ChildNodes.Count; i++)
            {
                var node = xmlRoot.ChildNodes[i];
                if (node.Name == "date")
                {
                    var year  = int.Parse(node.Attributes["year"].Value);
                    var month = int.Parse(node.Attributes["month"].Value);
                    var day   = int.Parse(node.Attributes["day"].Value);
                    var date  = new StatisticsDate(year, month, day);
                    sl.Dates.Add(date.Identifier, date);

                    for (var j = 0; j < node.ChildNodes.Count; j++)
                    {
                        var cnode = node.ChildNodes[j];
                        if (cnode.Name == "song")
                        {
                            var item = new StatisticsItem
                            {
                                Type      = StatisticsItemType.Song,
                                Title     = cnode.Attributes["title"].Value,
                                CcliId    = cnode.Attributes["ccli"].Value,
                                Copyright = cnode.Attributes["copyright"].Value,
                                Count     = int.Parse(cnode.Attributes["count"].Value)
                            };
                            date.Items.Add(item.Identifier, item);
                        }
                    }
                }
            }
            return(sl);
        }
 public StatisticItemView(StatisticsItem item, string scenarioUnit = "")
 {
     ScenarioName = item.Target.Name;
     UserName     = item.Source.Name;
     SourceType   = item.Source.SourceType;
     DateTime     = item.DateTime;
     Value        = item.Value + scenarioUnit;
     if (item.Target.ValueTypeName == ToggleValueTypeName)
     {
         if (Value == ToggleValueType.ValueON)
         {
             Value = "Вкл.";
         }
         else
         {
             Value = "Выкл.";
         }
     }
 }
示例#20
0
        private void EventTriggered(object sender, EventsArgs <ScenarioValueChangedEventArgs> args)
        {
            if (args.Value.Scenario is RemoteScenario == false)
            {
                var newVal = args.Value.Scenario.GetCurrentValue();
                AddValueCache(args.Value.Scenario.Id, newVal);

                var item = new StatisticsItem();
                item.DateTime   = DateTime.Now;
                item.SourceType = GetStartupSourceName(args.Value.Source.Source);
                item.SourceName = args.Value.Source.User?.Name;
                item.Value      = newVal;

                AddItem(
                    item,
                    args.Value.Scenario,
                    args.Value.Source.User?.Id);
            }
        }
示例#21
0
        private void UpdateCorrectedStatistics()
        {
            if (_correctionProfile == null)
            {
                return;
            }

            if (_correctedStatistics == null)
            {
                _correctedStatistics = new StatisticsItem[Size];
                for (var i = 0; i < Size; i++)
                {
                    _correctedStatistics[i] = new StatisticsItem();
                }
            }

            for (var i = 0; i < Size; i++)
            {
                _correctedStatistics[i].Label = _statistics[i].Label;
                if (!_correctionApplicableItemSelector(this, i))
                {
                    _correctedStatistics[i].LastValue         = _statistics[i].LastValue;
                    _correctedStatistics[i].Max               = _statistics[i].Max;
                    _correctedStatistics[i].Min               = _statistics[i].Min;
                    _correctedStatistics[i].Mean              = _statistics[i].Mean;
                    _correctedStatistics[i].Sum               = _statistics[i].Sum;
                    _correctedStatistics[i].StandardDeviation = _statistics[i].StandardDeviation;
                }
                else
                {
                    _correctedStatistics[i].LastValue         = Math.Abs(_statistics[i].LastValue - _correctionProfile.Statistics[i].LastValue);
                    _correctedStatistics[i].Max               = Math.Abs(_statistics[i].Max - _correctionProfile.Statistics[i].Max);
                    _correctedStatistics[i].Min               = Math.Abs(_statistics[i].Min - _correctionProfile.Statistics[i].Min);
                    _correctedStatistics[i].Mean              = Math.Abs(_statistics[i].Mean - _correctionProfile.Statistics[i].Mean);
                    _correctedStatistics[i].Sum               = Math.Abs(_statistics[i].Sum - _correctionProfile.Statistics[i].Sum);
                    _correctedStatistics[i].StandardDeviation = Math.Abs(_statistics[i].StandardDeviation - _correctionProfile.Statistics[i].StandardDeviation);
                }
            }
        }
 public void Refresh(StatisticsScenarioInfo info, StatisticsItem item, DateTime dateTime)
 {
     if (item == null)
     {
         Visibility = Visibility.Collapsed;
     }
     else
     {
         Visibility      = Visibility.Visible;
         tbScenName.Text = info.Name;
         if (info.ValueTypeName == Lazurite.ActionsDomain.Utils.GetValueTypeClassName(typeof(ToggleValueType)))
         {
             tbScenVal.Text = item.Value == ToggleValueType.ValueON ? "Вкл." : "Выкл.";
         }
         else
         {
             tbScenVal.Text = item.Value;
         }
         var unit = string.Empty;
         if (_scen == null && !_notExist)
         {
             _scen = ScenariosRepository.Scenarios.FirstOrDefault(x => x.Id == info.ID);
             if (_scen == null)
             {
                 _notExist = true;
             }
         }
         if (_scen != null && _scen.ValueType is FloatValueType floatValueType)
         {
             tbScenVal.Text += floatValueType.Unit;
         }
         tbScenVal.Visibility  = string.IsNullOrEmpty(tbScenVal.Text) ? Visibility.Collapsed : Visibility.Visible;
         tbUser.Text           = item.SourceName;
         tbUser.Visibility     = string.IsNullOrEmpty(tbUser.Text) || tbUser.Text == UsersRepository.SystemUser.Name ? Visibility.Collapsed : Visibility.Visible;
         tbDateTimeSetted.Text = "Выставлено: " + item.DateTime.ToString();
     }
 }
示例#23
0
        public List<Statistics> GetStatisticsData(string databasePrefix, List<string> tableNames, DateTime beginTime, DateTime endTime, TimeSpan span, Dictionary<string, object> filters)
        {
            try
            {
                var data = new ConcurrentBag<Statistics>();

                var databaseInfos = MongodbServerMaintainceCenter.GetDatabaseInfos(databasePrefix, beginTime, endTime);
                if (databaseInfos.Count == 0) return null;
                var typeFullName = MongodbServerMaintainceCenter.GetTypeFullName(databasePrefix);
                var columnDescriptions = MongodbServerMaintainceCenter.GetMongodbColumnDescriptions(databasePrefix);

                var statTimeColumn = columnDescriptions.FirstOrDefault(c => c.IsTimeColumn);
                if (statTimeColumn == null) return null;

                var filterquery = Query.Null;
                if (filters != null)
                {
                    foreach (var item in filters)
                    {
                        if (item.Value != null)
                        {
                            if (item.Value is string && item.Value.ToString().Split(',').Length > 1)
                            {
                                var values = item.Value.ToString().Split(',');
                                filterquery = Query.And(filterquery, Query.In(item.Key, values.Select(val => BsonValue.Create(val)).ToArray()));
                            }
                            else
                            {
                                filterquery = Query.And(filterquery, Query.EQ(item.Key, BsonValue.Create(item.Value)));
                            }
                        }
                    }
                }

                var server = CreateSlaveMongoServer(typeFullName);
                if (server == null) return null;
                var serverUrl = GetMongodbServerUrl(typeFullName);
                var delay = TimeSpan.FromSeconds(0);
                if (serverUrl != null) delay = serverUrl.SyncDelay;

                Parallel.ForEach(tableNames, tableName =>
                {
                    var item = new Statistics();
                    item.StatisticsItems = new List<StatisticsItem>();
                    item.TableName = tableName;

                    var begin = beginTime;
                    var end = endTime;
                    while (begin < endTime)
                    {
                        DateTime tmpEndTime = begin.Add(span);
                        if (tmpEndTime > endTime)
                            tmpEndTime = endTime;

                        var statItem = new StatisticsItem
                        {
                            BeginTime = begin,
                            EndTime = tmpEndTime,
                            Value = 0,
                        };
                        if (begin.ToString("yyyyMM") == tmpEndTime.AddSeconds(-1).ToString("yyyyMM"))
                        {
                            var databaseInfo = databaseInfos.FirstOrDefault(d => d.DatabaseDate.ToLocalTime().ToString("yyyyMM") == tmpEndTime.ToString("yyyyMM"));
                            if (databaseInfo != null)
                            {
                                var databaseName = databaseInfo.DatabaseName;
                                statItem.Value = InternalGetDataCount(delay, typeFullName, databaseName, tableName,
                                    statTimeColumn.ColumnName, begin, tmpEndTime, filterquery);
                            }
                        }
                        else
                        {
                            var spanBegin = begin;
                            var spanEnd = tmpEndTime;
                            while (spanBegin < spanEnd)
                            {
                                DateTime tmpSpanEndTime = spanBegin.AddDays(1);
                                if (tmpSpanEndTime > spanEnd)
                                    tmpSpanEndTime = spanEnd;

                                var databaseInfo = databaseInfos.FirstOrDefault(d => d.DatabaseDate.ToLocalTime().ToString("yyyyMM") == spanBegin.ToString("yyyyMM"));
                                if (databaseInfo == null) continue;
                                var databaseName = databaseInfo.DatabaseName;
                                var query = Query.And(Query.LT(statTimeColumn.ColumnName, spanEnd).GTE(spanBegin), filterquery);
                                statItem.Value += InternalGetDataCount(delay, typeFullName, databaseName, tableName,
                                    statTimeColumn.ColumnName, spanBegin, tmpSpanEndTime, filterquery);
                                spanBegin = tmpSpanEndTime;
                            }
                        }
                        item.StatisticsItems.Add(statItem);
                        begin = tmpEndTime;
                    }
                    data.Add(item);
                });
                return data.ToList();
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServer_Statistics", "GetStatisticsData", ex.Message);
                throw;
            }
        }
        public void ReadTest()
        {
            StatisticsReader target   = new StatisticsReader();
            string           filename = "Resources/statistics/statistics.xml";

            Statistics expected = new Statistics();

            var date = new StatisticsDate(2012, 12, 15);
            var item = new StatisticsItem
            {
                Type      = StatisticsItemType.Song,
                Title     = "You are so faithful",
                Copyright = "Musik & Copyright unbekannt",
                CcliId    = "",
                Count     = 1
            };

            date.Items.Add(item.Identifier, item);
            expected.Dates.Add(date.Identifier, date);

            date = new StatisticsDate(2013, 1, 6);

            item = new StatisticsItem
            {
                Type      = StatisticsItemType.Song,
                Title     = "A Mighty Fortress Is Our God",
                Copyright = "Public Domain",
                CcliId    = "42964",
                Count     = 2
            };
            date.Items.Add(item.Identifier, item);

            item = new StatisticsItem
            {
                Type      = StatisticsItemType.Song,
                Title     = "You are so faithful",
                Copyright = "Musik & Copyright unbekannt",
                CcliId    = "",
                Count     = 1
            };
            date.Items.Add(item.Identifier, item);

            expected.Dates.Add(date.Identifier, date);

            Statistics actual = target.read(filename);

            foreach (var edate in expected.Dates)
            {
                Assert.AreEqual(edate.Value.Identifier, actual.Dates[edate.Key].Identifier);
                Assert.AreEqual(edate.Value.Year, actual.Dates[edate.Key].Year);
                Assert.AreEqual(edate.Value.Month, actual.Dates[edate.Key].Month);
                Assert.AreEqual(edate.Value.Day, actual.Dates[edate.Key].Day);
                Assert.AreEqual(edate.Value.Items.Count, actual.Dates[edate.Key].Items.Count);
                foreach (var eitem in edate.Value.Items)
                {
                    Assert.AreEqual(eitem.Value.CcliId, actual.Dates[edate.Key].Items[eitem.Key].CcliId);
                    Assert.AreEqual(eitem.Value.Title, actual.Dates[edate.Key].Items[eitem.Key].Title);
                    Assert.AreEqual(eitem.Value.Copyright, actual.Dates[edate.Key].Items[eitem.Key].Copyright);
                    Assert.AreEqual(eitem.Value.Count, actual.Dates[edate.Key].Items[eitem.Key].Count);
                    Assert.AreEqual(eitem.Value.Type, actual.Dates[edate.Key].Items[eitem.Key].Type);
                }
            }
        }
示例#25
0
        public async Task <ScenarioStatistic> GetItems(StatisticsScenarioInfo info, DateTime since, DateTime to, ScenarioActionSource source)
        {
            var scenario = ScenariosRepository.Scenarios.FirstOrDefault(x => x.Id == info.ID);

            if (scenario?.SecuritySettings.IsAvailableForUser(source.User, source.Source, source.Action) ?? false)
            {
                if (scenario is RemoteScenario remoteScenario)
                {
                    try
                    {
                        if (!scenario.GetIsAvailable())
                        {
                            throw new ScenarioExecutionException(ScenarioExecutionError.NotAvailable);
                        }

                        var remoteScenarioInfo = new StatisticsScenarioInfo()
                        {
                            Name  = remoteScenario.Name,
                            ID    = remoteScenario.RemoteScenarioId,
                            Since = DateTime.Now,
                            To    = DateTime.Now,
                        };

                        var client = ServiceClientFactory.Current.GetClient(remoteScenario.Credentials);
                        var remoteScenarioStatistics = await client.GetStatistics(since, to, remoteScenarioInfo);

                        var scenarioStatistics = new ScenarioStatistic();
                        scenarioStatistics.ScenarioInfo = info;
                        scenarioStatistics.Statistic    = remoteScenarioStatistics.Statistic ?? new StatisticsItem[0]; // Crutch

                        return(scenarioStatistics);
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
                else
                {
                    var valueTypeName = ActionsDomain.Utils.GetValueTypeClassName(scenario.ValueType.GetType());
                    var statistics    =
                        _dataManager
                        .GetDataItems(info.ID, valueTypeName, since, to)
                        .Select(x =>
                    {
                        var item        = new StatisticsItem();
                        item.SourceType = x.SourceType;
                        item.SourceName = x.SourceName;
                        item.DateTime   = new DateTime(x.Year, x.Month, x.Day, x.Hour, x.Minute, x.Second);
                        item.Value      = x.Value;
                        return(item);
                    })
                        .OrderBy(x => x.DateTime)
                        .ToArray();

                    var scenarioStatistics = new ScenarioStatistic();
                    scenarioStatistics.ScenarioInfo = info;
                    scenarioStatistics.Statistic    = statistics;

                    return(scenarioStatistics);
                }
            }
            throw new ScenarioExecutionException(ScenarioExecutionError.AccessDenied);
        }
示例#26
0
        public List <Statistics> GetStatisticsData(string databasePrefix, List <string> tableNames, DateTime beginTime, DateTime endTime, TimeSpan span, Dictionary <string, object> filters)
        {
            try
            {
                var data = new ConcurrentBag <Statistics>();

                var databaseInfos = MongodbServerMaintainceCenter.GetDatabaseInfos(databasePrefix, beginTime, endTime);
                if (databaseInfos.Count == 0)
                {
                    return(null);
                }
                var typeFullName       = MongodbServerMaintainceCenter.GetTypeFullName(databasePrefix);
                var columnDescriptions = MongodbServerMaintainceCenter.GetMongodbColumnDescriptions(databasePrefix);

                var statTimeColumn = columnDescriptions.FirstOrDefault(c => c.IsTimeColumn);
                if (statTimeColumn == null)
                {
                    return(null);
                }

                var filterquery = Query.Null;
                if (filters != null)
                {
                    foreach (var item in filters)
                    {
                        if (item.Value != null)
                        {
                            if (item.Value is string && item.Value.ToString().Split(',').Length > 1)
                            {
                                var values = item.Value.ToString().Split(',');
                                filterquery = Query.And(filterquery, Query.In(item.Key, values.Select(val => BsonValue.Create(val)).ToArray()));
                            }
                            else
                            {
                                filterquery = Query.And(filterquery, Query.EQ(item.Key, BsonValue.Create(item.Value)));
                            }
                        }
                    }
                }

                var server = CreateSlaveMongoServer(typeFullName);
                if (server == null)
                {
                    return(null);
                }
                var serverUrl = GetMongodbServerUrl(typeFullName);
                var delay     = TimeSpan.FromSeconds(0);
                if (serverUrl != null)
                {
                    delay = serverUrl.SyncDelay;
                }

                Parallel.ForEach(tableNames, tableName =>
                {
                    var item             = new Statistics();
                    item.StatisticsItems = new List <StatisticsItem>();
                    item.TableName       = tableName;

                    var begin = beginTime;
                    var end   = endTime;
                    while (begin < endTime)
                    {
                        DateTime tmpEndTime = begin.Add(span);
                        if (tmpEndTime > endTime)
                        {
                            tmpEndTime = endTime;
                        }

                        var statItem = new StatisticsItem
                        {
                            BeginTime = begin,
                            EndTime   = tmpEndTime,
                            Value     = 0,
                        };
                        if (begin.ToString("yyyyMM") == tmpEndTime.AddSeconds(-1).ToString("yyyyMM"))
                        {
                            var databaseInfo = databaseInfos.FirstOrDefault(d => d.DatabaseDate.ToLocalTime().ToString("yyyyMM") == tmpEndTime.ToString("yyyyMM"));
                            if (databaseInfo != null)
                            {
                                var databaseName = databaseInfo.DatabaseName;
                                statItem.Value   = InternalGetDataCount(delay, typeFullName, databaseName, tableName,
                                                                        statTimeColumn.ColumnName, begin, tmpEndTime, filterquery);
                            }
                        }
                        else
                        {
                            var spanBegin = begin;
                            var spanEnd   = tmpEndTime;
                            while (spanBegin < spanEnd)
                            {
                                DateTime tmpSpanEndTime = spanBegin.AddDays(1);
                                if (tmpSpanEndTime > spanEnd)
                                {
                                    tmpSpanEndTime = spanEnd;
                                }

                                var databaseInfo = databaseInfos.FirstOrDefault(d => d.DatabaseDate.ToLocalTime().ToString("yyyyMM") == spanBegin.ToString("yyyyMM"));
                                if (databaseInfo == null)
                                {
                                    continue;
                                }
                                var databaseName = databaseInfo.DatabaseName;
                                var query        = Query.And(Query.LT(statTimeColumn.ColumnName, spanEnd).GTE(spanBegin), filterquery);
                                statItem.Value  += InternalGetDataCount(delay, typeFullName, databaseName, tableName,
                                                                        statTimeColumn.ColumnName, spanBegin, tmpSpanEndTime, filterquery);
                                spanBegin = tmpSpanEndTime;
                            }
                        }
                        item.StatisticsItems.Add(statItem);
                        begin = tmpEndTime;
                    }
                    data.Add(item);
                });
                return(data.ToList());
            }
            catch (Exception ex)
            {
                LocalLoggingService.Error("{0} {1} {2} {3}", MongodbServerConfiguration.ModuleName, "MongodbServer_Statistics", "GetStatisticsData", ex.Message);
                throw;
            }
        }
示例#27
0
        public static StatisticsItem GetStatisticsItem(PoolyExtension originPool, string category, string prefabName, Transform prefab, int preloadedClones)
        {
            //See if this scene is in the pools list (by default we consider this the MainPool)
            string   targetSceneName = Pooly.mainPoolSceneName;
            PoolType targetPoolType  = PoolType.MainPool;

            if (originPool != null) //this is a pool extension
            {
                targetSceneName = originPool.gameObject.scene.name;
                targetPoolType  = PoolType.PoolExtension;
            }

            StatisticsPool         statisticsPool         = null;
            StatisticsPoolCategory statisticsPoolCategory = null;
            StatisticsItem         statisticsItem         = null;

            if (Instance.pools == null)                                                       //the pools list null
            {
                Instance.pools = new List <StatisticsPool>();                                 //initialize the pools list
            }
            if (Instance.pools.Count == 0)                                                    //the pools list empty
            {
                statisticsPool         = new StatisticsPool(targetSceneName, targetPoolType); //create a new StatisticsPool
                statisticsPoolCategory = new StatisticsPoolCategory(category);                //create a new category for the new StatisticsPool
                statisticsPool.categories.Add(statisticsPoolCategory);                        //add the new category to the new StatisticsPool
                statisticsItem = new StatisticsItem(prefabName, prefab);
                statisticsItem.data.Add(new StatisticsItemData(preloadedClones, 0));          //add initial item data
                statisticsPoolCategory.items.Add(statisticsItem);                             //add the StatisticsItem to the new category under the new StatisticsPool
                Instance.pools.Add(statisticsPool);                                           //add the newly created StatisticsPool to the pools list
                return(statisticsItem);                                                       //return the reference to the StatisticsItem in order to quickly update its data values
            }

            if (statisticsPool == null)                        // a new StatisticsPool was NOT created
            {
                for (int i = 0; i < Instance.pools.Count; i++) //look for the pool where this prefab should be in
                {
                    if (Instance.pools[i].sceneName == targetSceneName && Instance.pools[i].poolType == targetPoolType)
                    {
                        statisticsPool = Instance.pools[i];
                        break;
                    }
                }
            }

            if (statisticsPool == null)                                                       //the StatisticsPool we were looking for does not exist, it needs to be created
            {
                statisticsPool         = new StatisticsPool(targetSceneName, targetPoolType); //create a new StatisticsPool
                statisticsPoolCategory = new StatisticsPoolCategory(category);                //create a new category for the new StatisticsPool
                statisticsPool.categories.Add(statisticsPoolCategory);                        //add the new category to the new StatisticsPool
                statisticsItem = new StatisticsItem(prefabName, prefab);                      //create a new StatisticsItem
                if (statisticsItem.data.Count == MAXIMUM_NUMBER_OF_RECORDS)
                {
                    statisticsItem.data.RemoveAt(0);
                }
                statisticsItem.data.Add(new StatisticsItemData(preloadedClones, 0)); //add initial item data
                statisticsPoolCategory.items.Add(statisticsItem);                    //add the StatisticsItem to the new category under the new StatisticsPool
                Instance.pools.Add(statisticsPool);                                  //add the newly created StatisticsPool to the pools list
                return(statisticsItem);                                              //return the reference to the StatisticsItem in order to quickly update its data values
            }

            //if we got here then we found a StatisticsPool where this prefab should be in
            //start searching for the prefab category

            int categoryIndex = statisticsPool.HasCategory(category);

            if (categoryIndex != -1) //the category exists in this pool
            {
                statisticsItem = statisticsPool.categories[categoryIndex].GetStatisticsItem(prefabName, prefab);
                if (statisticsItem != null) //the StatisticsItem was found
                {
                    if (statisticsItem.data.Count == MAXIMUM_NUMBER_OF_RECORDS)
                    {
                        statisticsItem.data.RemoveAt(0);
                    }
                    statisticsItem.data.Add(new StatisticsItemData(preloadedClones, 0)); //add initial item data
                    return(statisticsItem);                                              //return the reference to the StatisticsItem in order to quickly update its data values
                }

                //the item does not exist in this category, we need to add it
                statisticsItem = new StatisticsItem(prefabName, prefab); //create a new StatisticsItem
                if (statisticsItem.data.Count == MAXIMUM_NUMBER_OF_RECORDS)
                {
                    statisticsItem.data.RemoveAt(0);
                }
                statisticsItem.data.Add(new StatisticsItemData(preloadedClones, 0)); //add initial item data
                statisticsPool.categories[categoryIndex].items.Add(statisticsItem);
                return(statisticsItem);                                              //return the reference to the StatisticsItem in order to quickly update its data values
            }

            //the category does not exist, we need to create it
            statisticsPoolCategory = new StatisticsPoolCategory(category); //create a new category for the new StatisticsPool
            statisticsPool.categories.Add(statisticsPoolCategory);         //add the new category to the new StatisticsPool
            statisticsItem = new StatisticsItem(prefabName, prefab);       //create a new StatisticsItem
            if (statisticsItem.data.Count == MAXIMUM_NUMBER_OF_RECORDS)
            {
                statisticsItem.data.RemoveAt(0);
            }
            statisticsItem.data.Add(new StatisticsItemData(preloadedClones, 0)); //add initial item data
            statisticsPoolCategory.items.Add(statisticsItem);                    //add the StatisticsItem to the new category under the new StatisticsPool
            return(statisticsItem);                                              //return the reference to the StatisticsItem in order to quickly update its data values
        }
示例#28
0
 public void AddMetric(StatisticsItem item, StatisticsMetrics metrics, int delta = 1)
 {
     Values[item][metrics] += delta;
 }
 public void AddStatistics(StatisticsItem item)
 {
     _statistics.Create(item);
 }
示例#30
0
 public void UpdateStatistics(StatisticsMessage msg)
 {
     if (OverAll == null) OverAll = new StatisticsItem();
     switch (msg.Cmd)
     {
         case StatisticsCmd.WordCollected:
             OverAll.TotalWordsCollected++;
             TodayStatisticsItem.TotalWordsCollected++;
             break;
         case StatisticsCmd.PhraseCollected:
             OverAll.TotalPhrasesCollected++;
             TodayStatisticsItem.TotalPhrasesCollected++;
             break;
         case StatisticsCmd.WordFail:
             OverAll.TotalFailToCollectWord++;
             TodayStatisticsItem.TotalFailToCollectWord++;
             break;
         case StatisticsCmd.PassUnderstandingTest:
             OverAll.TotalTestingUnderstandWords++;
             TodayStatisticsItem.TotalTestingUnderstandWords++;
             break;
     }
     OnPropertyChanged(()=>OverAllStatAsString);
     OnPropertyChanged(()=>TodayStatAsString);
 }