public async Task <ActionResult> Devices()
        {
            // Manage session and Context
            HttpServiceUriBuilder contextUri = new HttpServiceUriBuilder().SetServiceName(this.context.ServiceName);

            if (HTTPHelper.IsSessionExpired(HttpContext, this))
            {
                return(Redirect(contextUri.GetServiceNameSiteHomePath()));
            }
            else
            {
                this.ViewData["TargetSite"]  = contextUri.GetServiceNameSite();
                this.ViewData["PageTitle"]   = "Devices";
                this.ViewData["HeaderTitle"] = "Devices Dashboard";

                string reportUniqueId = HashUtil.GetUniqueId();
                string reportName     = "DoverCivaconDemo"; // the dashboard

                EmbedConfig task = await ReportsHandler.GetEmbedReportConfigData(ClientId, GroupId, Username, Password, AuthorityUrl, ResourceUrl, ApiUrl, reportUniqueId, reportName, this.context, ServiceEventSource.Current);

                this.ViewData["EmbedToken"]     = task.EmbedToken.Token;
                this.ViewData["EmbedURL"]       = task.EmbedUrl;
                this.ViewData["EmbedId"]        = task.Id;
                this.ViewData["ReportUniqueId"] = "";

                return(this.View());
            }
        }
Beispiel #2
0
        public void ReturnsEmptyCollection_IfDbIsEmpty()
        {
            A.CallTo(() => database.GetMatches()).Returns(new MatchInfo[0]);
            A.CallTo(() => database.GetServers()).Returns(new GameServer[0]);
            handler = new ReportsHandler(database);

            handler.GetPopularServers(2).Should().BeEmpty();
        }
Beispiel #3
0
        public void ReturnsLessServersThenCount_IfThereLackOfServers()
        {
            A.CallTo(() => database.GetMatches()).Returns(TestData.Matches.Take(1).ToArray());
            A.CallTo(() => database.GetServers()).Returns(TestData.Servers);
            handler = new ReportsHandler(database);

            var popularServers = handler.GetPopularServers(2).ToArray();

            popularServers.Length.Should().Be(1);
        }
Beispiel #4
0
        public void ReturnNotMoreServersThanCount()
        {
            A.CallTo(() => database.GetMatches()).Returns(TestData.Matches);
            A.CallTo(() => database.GetServers()).Returns(TestData.Servers);
            handler = new ReportsHandler(database);

            var popularServers = handler.GetPopularServers(2).ToArray();

            popularServers.Length.Should().Be(2);
        }
Beispiel #5
0
        public void ReturnPopularServers_InCorrectOrder()
        {
            A.CallTo(() => database.GetMatches()).Returns(TestData.Matches);
            A.CallTo(() => database.GetServers()).Returns(TestData.Servers);
            handler = new ReportsHandler(database);

            var popularServers = handler.GetPopularServers(10).ToArray();

            popularServers.Should().Equal(TestData.BestServers);
        }
        public ParkReportViewModel()
        {
            _handler = ReportsHandler.Instance;

            CarsHandler.Instance.CarsRefreshed += Instance_CarsRefreshed;
            if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                return;
            }
            CreateReport();
        }
Beispiel #7
0
        public void ReturnsLessPlayersThanCount_IfThereareLacksOfAppropriatePlayes()
        {
            var scoreboard = TestData.Scoreboard;
            var matchInfo  = new MatchInfo {
                result = new MatchResult {
                    scoreboard = scoreboard
                }
            };
            const int matchCount = 10;

            A.CallTo(() => database.GetMatches()).Returns(Enumerable.Repeat(matchInfo, matchCount).ToArray());
            handler = new ReportsHandler(database);

            handler.GetBestPlayers(5).Count().Should().Be(3);
        }
Beispiel #8
0
        public void NotReturnsPlayers_WhichPlaysLessThan10Times()
        {
            var scoreboard = TestData.Scoreboard;
            var matchInfo  = new MatchInfo {
                result = new MatchResult {
                    scoreboard = scoreboard
                }
            };
            const int matchCount = 9;

            A.CallTo(() => database.GetMatches()).Returns(Enumerable.Repeat(matchInfo, matchCount).ToArray());
            handler = new ReportsHandler(database);

            handler.GetBestPlayers(3).Should().BeEmpty();
        }
Beispiel #9
0
        public void NotReturnsPlayers_WhichAreNotBeenKilled()
        {
            var matchInfo = new MatchInfo {
                result = new MatchResult {
                    scoreboard = new[] { new PlayerInfo {
                                             name = "player", deaths = 0
                                         } }
                }
            };
            const int matchCount = 10;

            A.CallTo(() => database.GetMatches()).Returns(Enumerable.Repeat(matchInfo, matchCount).ToArray());
            handler = new ReportsHandler(database);

            handler.GetBestPlayers(3).Should().BeEmpty();
        }
Beispiel #10
0
        public GetStatisticModule(
            ServerStatisticHandler serverStatisticHandler,
            PlayerStatisticHandler playerStatisticHandler,
            ReportsHandler reportsHandler
            )
        {
            this.serverStatisticHandler = serverStatisticHandler;
            this.playerStatisticHandler = playerStatisticHandler;
            this.reportsHandler         = reportsHandler;

            Get["/servers/{endpoint:url}/stats", true] = async(x, _) => await GetServerStatisticAsync(x.endpoint);

            Get["/players/{name}/stats", true] = async(x, _) => await GetPlayerStatisticAsync(x.name);

            Get["/reports/recent-matches/", true] = async(x, _) => await GetRecentMatchesReportAsync(Constants.DefaultCount);

            Get["/reports/recent-matches/{count:int}", true] = async(x, _) =>
            {
                var count = NormalizeCount(x.count);
                return(await GetRecentMatchesReportAsync(count));
            };

            Get["/reports/best-players/", true] = async(x, _) => await GetBestPlayersReportAsync(Constants.DefaultCount);

            Get["/reports/best-players/{count:int}", true] = async(x, _) =>
            {
                var count = NormalizeCount(x.count);
                return(await GetBestPlayersReportAsync(count));
            };

            Get["/reports/popular-servers/", true] = async(x, _) => await GetPopularServersReportAsync(Constants.DefaultCount);

            Get["/reports/popular-servers/{count:int}", true] = async(x, _) =>
            {
                var count = NormalizeCount(x.count);
                return(await GetPopularServersReportAsync(count));
            };
        }
Beispiel #11
0
        public void ReturnBestPlayersInCorrectOrder()
        {
            var scoreboard = TestData.Scoreboard;
            var matchInfo  = new MatchInfo {
                result = new MatchResult {
                    scoreboard = scoreboard
                }
            };
            const int matchCount = 10;

            A.CallTo(() => database.GetMatches()).Returns(Enumerable.Repeat(matchInfo, matchCount).ToArray());
            handler = new ReportsHandler(database);

            var bestPlayers = handler.GetBestPlayers(3).ToArray();

            bestPlayers.Should().BeInDescendingOrder(x => x.killToDeathRatio);
            foreach (var player in bestPlayers)
            {
                var expectedPlayer = scoreboard.First(x => x.name == player.name);
                var expectedRatio  = (double)expectedPlayer.kills / expectedPlayer.deaths;
                player.killToDeathRatio.Should().Be(expectedRatio);
            }
        }
Beispiel #12
0
        public async Task <IActionResult> EmbedReport(string reportName, string reportParm = null, string reportParmStart = null, string reportParmEnd = null, int numberOfObservations = (-1), int minMagnitudeAllowed = 1)
        {
            // Manage session and Context
            HttpServiceUriBuilder contextUri = new HttpServiceUriBuilder().SetServiceName(this.context.ServiceName);

            ViewBag.RedirectURL = "";

            if (HTTPHelper.IsSessionExpired(HttpContext, this))
            {
                return(Ok(contextUri.GetServiceNameSiteHomePath()));
            }
            else
            {
                this.ViewData["TargetSite"]  = contextUri.GetServiceNameSite();
                this.ViewData["PageTitle"]   = "Report";
                this.ViewData["HeaderTitle"] = "Last Posted Events";

                string reportUniqueId = FnvHash.GetUniqueId();

                // Now it is time to refresh the data set
                List <DeviceViewModelList> deviceViewModelList = null;
                int  resampleSetsLimit = 0;
                var  refreshDataresult = false;
                bool publishReportData = true;

                if (reportName.Equals("PSG-VibrationDeviceReport-02"))
                {
                    refreshDataresult = true;
                    publishReportData = false;
                }
                else if (reportName.Equals("PSG-VibrationDeviceReport-01") && reportParm != null)
                {
                    deviceViewModelList = await DevicesController.GetDevicesDataAsync(reportParm, httpClient, fabricClient, appLifetime);
                }
                else
                {
                    resampleSetsLimit = 1;

                    deviceViewModelList = new List <DeviceViewModelList>();
                    ServiceUriBuilder uriBuilder = new ServiceUriBuilder(Names.InsightDataServiceName);
                    Uri serviceUri = uriBuilder.Build();

                    // service may be partitioned.
                    // this will aggregate device IDs from all partitions
                    ServicePartitionList partitions = await fabricClient.QueryManager.GetPartitionListAsync(serviceUri);

                    foreach (Partition partition in partitions)
                    {
                        string pathAndQuery      = null;
                        int    index             = 0;
                        float  indexInterval     = 1F;
                        bool   keepLooping       = true;
                        int    observationsCount = 0;
                        int    batchIndex        = 0;
                        int    batchSize         = 10000;


                        while (keepLooping)
                        {
                            if (reportParmEnd == null)
                            {
                                pathAndQuery = $"/api/devices/history/byKey/{reportParmStart}";
                                keepLooping  = false;
                            }
                            else if (numberOfObservations != (-1))
                            {
                                pathAndQuery = $"/api/devices/history/byKeyRange/{reportParmStart}/{reportParmEnd}/{batchIndex}/{batchSize}";

                                if (index == 0)
                                {
                                    string getCountPathAndQuery = $"/api/devices/history/count/interval/{reportParmStart}/{reportParmEnd}";
                                    Uri    getCountUrl          = new HttpServiceUriBuilder()
                                                                  .SetServiceName(serviceUri)
                                                                  .SetPartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey)
                                                                  .SetServicePathAndQuery(getCountPathAndQuery)
                                                                  .Build();

                                    HttpResponseMessage localResponse = await httpClient.GetAsync(getCountUrl, appLifetime.ApplicationStopping);

                                    if (localResponse.StatusCode == System.Net.HttpStatusCode.OK)
                                    {
                                        string localResult = await localResponse.Content.ReadAsStringAsync();

                                        long count = Int64.Parse(localResult);

                                        indexInterval = count / numberOfObservations;

                                        if (indexInterval < 1)
                                        {
                                            indexInterval = 1;
                                        }
                                    }
                                }
                            }
                            else if (reportParmEnd != null)
                            {
                                pathAndQuery = $"/api/devices/history/byKeyRange/{reportParmStart}/{reportParmEnd}";
                                keepLooping  = false;
                            }

                            Uri getUrl = new HttpServiceUriBuilder()
                                         .SetServiceName(serviceUri)
                                         .SetPartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey)
                                         .SetServicePathAndQuery(pathAndQuery)
                                         .Build();

                            HttpResponseMessage response = await httpClient.GetAsync(getUrl, appLifetime.ApplicationStopping);

                            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                            {
                                JsonSerializer serializer = new JsonSerializer();
                                using (StreamReader streamReader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                                {
                                    using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
                                    {
                                        List <DeviceViewModelList> localResult = serializer.Deserialize <List <DeviceViewModelList> >(jsonReader);

                                        if (localResult != null)
                                        {
                                            if (localResult.Count != 0)
                                            {
                                                foreach (DeviceViewModelList device in localResult)
                                                {
                                                    if (index >= (observationsCount * indexInterval))
                                                    {
                                                        deviceViewModelList.Add(device);
                                                        observationsCount++;
                                                    }
                                                    index++;

                                                    if (numberOfObservations != (-1))
                                                    {
                                                        if (observationsCount == numberOfObservations)
                                                        {
                                                            keepLooping = false;
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                keepLooping = false;
                                            }
                                        }
                                        else
                                        {
                                            keepLooping = false;
                                        }
                                    }
                                }
                            }
                            batchIndex += batchSize;
                        }
                    }
                }

                if (publishReportData)
                {
                    refreshDataresult = await ReportsHandler.PublishReportDataFor(reportUniqueId, DevicesDataStream01URL, deviceViewModelList, context, httpClient, appLifetime.ApplicationStopping, ServiceEventSource.Current, resampleSetsLimit, minMagnitudeAllowed);
                }

                if (reportName.Equals("PSG-VibrationDeviceReport-02"))
                {
                    reportUniqueId = "";
                }

                EmbedConfig task = await ReportsHandler.GetEmbedReportConfigData(ClientId, GroupId, Username, Password, AuthorityUrl, ResourceUrl, ApiUrl, reportUniqueId, reportName, this.context, ServiceEventSource.Current);

                this.ViewData["EmbedToken"]     = task.EmbedToken.Token;
                this.ViewData["EmbedURL"]       = task.EmbedUrl;
                this.ViewData["EmbedId"]        = task.Id;
                this.ViewData["ReportUniqueId"] = reportUniqueId;

                return(this.View());
            }
        }
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            // Get the IoT Hub connection string from the Settings.xml config file
            // from a configuration package named "Config"
            string PublishDataServiceURLs =
                this.Context.CodePackageActivationContext
                .GetConfigurationPackageObject("Config")
                .Settings
                .Sections["ExtenderServiceConfigInformation"]
                .Parameters["PublishDataServiceURLs"]
                .Value.Trim('/');

            ServiceEventSource.Current.ServiceMessage(this.Context, $"ExtenderService - {ServiceUniqueId} - RunAsync - Starting service  - Data Service URLs[{PublishDataServiceURLs}]");

            DateTimeOffset currentSearchStartingTime = DateTimeOffset.UtcNow.AddHours(-1);

            if (PublishDataServiceURLs != null && PublishDataServiceURLs.Length > 0)
            {
                string[] routingparts = PublishDataServiceURLs.Split(';');
                int      currentValueForIntervalEnd = global::Iot.Common.Names.ExtenderStandardRetryWaitIntervalsInMills;

                using (HttpClient httpClient = new HttpClient(new HttpServiceClientHandler()))
                {
                    while (true)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string reportUniqueId = FnvHash.GetUniqueId();
                        int    messageCount   = 1;

                        while (messageCount > 0)
                        {
                            try
                            {
                                DateTimeOffset startTime           = currentSearchStartingTime;
                                long           searchIntervalStart = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - currentSearchStartingTime.ToUnixTimeMilliseconds() - 500; // this last adjusment is only to compensate for latency around the calls
                                long           searchIntervalEnd   = searchIntervalStart - currentValueForIntervalEnd;

                                if (searchIntervalEnd < 0)
                                {
                                    searchIntervalEnd          = 0;
                                    currentValueForIntervalEnd = global::Iot.Common.Names.ExtenderStandardRetryWaitIntervalsInMills;
                                }

                                DateTimeOffset endTime = DateTimeOffset.UtcNow.AddMilliseconds(searchIntervalEnd * (-1));

                                string servicePathAndQuery = $"/api/devices/history/interval/{searchIntervalStart}/{searchIntervalEnd}";

                                ServiceUriBuilder uriBuilder = new ServiceUriBuilder(routingparts[0], global::Iot.Common.Names.InsightDataServiceName);
                                Uri serviceUri = uriBuilder.Build();

                                ServiceEventSource.Current.ServiceMessage(this.Context, $"ExtenderService - {ServiceUniqueId} - RunAsync - About to call URL[{serviceUri}] to collect completed messages - Search[{servicePathAndQuery}] Time Start[{startTime}] End[{endTime}]");

                                // service may be partitioned.
                                // this will aggregate the queue lengths from each partition
                                System.Fabric.Query.ServicePartitionList partitions = await this.fabricClient.QueryManager.GetPartitionListAsync(serviceUri);

                                foreach (System.Fabric.Query.Partition partition in partitions)
                                {
                                    List <DeviceViewModelList> deviceViewModelList = new List <DeviceViewModelList>();
                                    Uri getUrl = new HttpServiceUriBuilder()
                                                 .SetServiceName(serviceUri)
                                                 .SetPartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey)
                                                 .SetServicePathAndQuery(servicePathAndQuery)
                                                 .Build();

                                    HttpResponseMessage response = await httpClient.GetAsync(getUrl, cancellationToken);

                                    if (response.StatusCode == System.Net.HttpStatusCode.OK)
                                    {
                                        JsonSerializer serializer = new JsonSerializer();
                                        using (StreamReader streamReader = new StreamReader(await response.Content.ReadAsStreamAsync()))
                                        {
                                            using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
                                            {
                                                List <DeviceViewModelList> resultList = serializer.Deserialize <List <DeviceViewModelList> >(jsonReader);

                                                deviceViewModelList.AddRange(resultList);
                                            }
                                        }

                                        if (deviceViewModelList.Count > 0)
                                        {
                                            DeviceViewModelList lastItem = deviceViewModelList.ElementAt(deviceViewModelList.Count() - 1);

                                            messageCount = deviceViewModelList.Count;
                                            await ReportsHandler.PublishReportDataFor(reportUniqueId, routingparts[1], deviceViewModelList, this.Context, httpClient, cancellationToken, ServiceEventSource.Current, 1);

                                            ServiceEventSource.Current.ServiceMessage(this.Context, $"ExtenderService - {ServiceUniqueId} - RunAsync - Finished posting messages to report stream - Published total number of collected messages[{messageCount}]");
                                            currentSearchStartingTime  = endTime;
                                            currentValueForIntervalEnd = global::Iot.Common.Names.ExtenderStandardRetryWaitIntervalsInMills;
                                        }
                                        else
                                        {
                                            messageCount = 0;
                                            ServiceEventSource.Current.ServiceMessage(this.Context, $"ExtenderService - {ServiceUniqueId} - RunAsync - Could not find any messages in the interval from [{startTime}] to [{endTime}]");
                                        }
                                    }
                                    else
                                    {
                                        messageCount = 0;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                ServiceEventSource.Current.ServiceMessage(this.Context, $"ExtenderService - {ServiceUniqueId} - RunAsync - Severe error when reading or sending messages to report stream - Exception[{ex}] - Inner Exception[{ex.InnerException}] StackTrace[{ex.StackTrace}]");
                            }
                        }

                        currentValueForIntervalEnd += global::Iot.Common.Names.ExtenderStandardRetryWaitIntervalsInMills;

                        DateTimeOffset boundaryTime = currentSearchStartingTime.AddMilliseconds(currentValueForIntervalEnd);

                        if (boundaryTime.CompareTo(DateTimeOffset.UtcNow) > 0)
                        {
                            await Task.Delay(global::Iot.Common.Names.ExtenderStandardRetryWaitIntervalsInMills);
                        }
                    }
                }
            }
            else
            {
                ServiceEventSource.Current.ServiceMessage(this.Context, $"ExtenderService - {ServiceUniqueId} - RunAsync - Starting service  - Data Service URLs[{PublishDataServiceURLs}]");
            }
        }