Пример #1
0
        public static async Task Run(
            [TimerTrigger("%AppInsightsSyncSchedule%")]
            TimerInfo timer,
            ILogger log,
            [BindConferenceConfig]
            ConferenceConfig conference,
            [BindAppInsightsSyncConfig]
            AppInsightsSyncConfig appInsights,
            [BindKeyDatesConfig]
            KeyDatesConfig keyDates
            )
        {
            if (keyDates.Before(x => x.StartSyncingAppInsightsFromDate) || keyDates.After(x => x.StopSyncingAppInsightsFromDate, TimeSpan.FromMinutes(10)))
            {
                log.LogInformation("AppInsightsSync sync not active");
                return;
            }

            var http = new HttpClient();

            http.DefaultRequestHeaders.Add("x-api-key", appInsights.ApplicationKey);

            var response = await http.GetAsync($"https://api.applicationinsights.io/v1/apps/{appInsights.ApplicationId}/query?timespan={WebUtility.UrlEncode(keyDates.StartSyncingAppInsightsFrom)}%2F{WebUtility.UrlEncode(keyDates.StopSyncingAppInsightsFrom)}&query={WebUtility.UrlEncode(VotingUserQuery.Query)}");

            response.EnsureSuccessStatusCode();
            var content = await response.Content.ReadAsAsync <AppInsightsQueryResponse <VotingUserQuery> >();

            var currentRecords = content.Data.Select(x => new AppInsightsVotingUser(conference.ConferenceInstance, x.UserId, x.VoteId, x.StartTime)).ToArray();

            var repo = await appInsights.GetRepositoryAsync();

            var existingRecords = await repo.GetAllAsync(conference.ConferenceInstance);

            // Taking up to 100 records to meet Azure Storage Bulk Operation limit
            var newRecords = currentRecords.Except(existingRecords, new AppInsightsVotingUserComparer()).Take(100).ToArray();

            log.LogInformation("Found {existingCount} existing app insights voting users and {currentCount} current app insights voting users. Inserting {newCount} new orders.", existingRecords.Count, currentRecords.Length, newRecords.Length);
            await repo.CreateBatchAsync(newRecords);
        }
Пример #2
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)]
            HttpRequest req,
            ILogger log,
            [BindConferenceConfig]
            ConferenceConfig conference,
            [BindSubmissionsConfig]
            SubmissionsConfig submissions,
            [BindVotingConfig]
            VotingConfig voting,
            [BindTitoSyncConfig]
            TitoSyncConfig tito,
            [BindAppInsightsSyncConfig]
            AppInsightsSyncConfig appInsights)
        {
            // Get submissions
            var(submissionsRepo, submittersRepo) = await submissions.GetRepositoryAsync();

            var receivedSubmissions = await submissionsRepo.GetAllAsync(conference.ConferenceInstance);

            var presenters = await submittersRepo.GetAllAsync(conference.ConferenceInstance);

            // Get votes
            var votingRepo = await voting.GetRepositoryAsync();

            var votes = await votingRepo.GetAllAsync(conference.ConferenceInstance);

            // Get Tito ids
            var ebRepo = await tito.GetRepositoryAsync();

            var titoTickets = await ebRepo.GetAllAsync(conference.ConferenceInstance);

            var titoIds = titoTickets.Select(o => o.TicketId).ToArray();

            // Get AppInsights sessions
            var aiRepo = await appInsights.GetRepositoryAsync();

            var userSessions = await aiRepo.GetAllAsync(conference.ConferenceInstance);

            // Analyse votes
            var analysedVotes = votes.Select(v => new AnalysedVote(v, votes, titoIds, userSessions)).ToArray();

            // Get summary
            var sessions = receivedSubmissions.Select(x => x.GetSession())
                           .Select(s => new SessionWithVotes
            {
                Id         = s.Id.ToString(),
                Title      = s.Title,
                Abstract   = s.Abstract,
                Format     = s.Format,
                Level      = s.Level,
                Tags       = s.Tags,
                Presenters = GetPresentersFromSession(presenters, s, ps => ps.Select(p =>
                                                                                     new Presenter
                {
                    Id              = p.Id.ToString(),
                    Name            = p.Name,
                    Tagline         = p.Tagline,
                    Bio             = p.Bio,
                    ProfilePhotoUrl = p.ProfilePhotoUrl,
                    TwitterHandle   = p.TwitterHandle,
                    WebsiteUrl      = p.WebsiteUrl
                }).ToArray()),
                CreatedDate          = s.CreatedDate,
                ModifiedDate         = s.ModifiedDate,
                IsUnderrepresented   = GetPresentersFromSession(presenters, s, IsUnderrepresented),
                Pronoun              = CollapsePresenterField(presenters, s, p => p.DataFields["Your pronoun"]),
                JobRole              = CollapsePresenterField(presenters, s, p => p.DataFields["How would you identify your job role"]),
                SpeakingExperience   = CollapsePresenterField(presenters, s, p => p.DataFields["How much speaking experience do you have?"]),
                VoteSummary          = new VoteSummary(analysedVotes.Where(v => v.Vote.GetSessionIds().Contains(s.Id.ToString())).ToArray()),
                FirstPreferenceCount = analysedVotes.Count(v => v.Vote.GetSessionIds()[0] == s.Id.ToString()),
                Top3PreferenceCount  = analysedVotes.Count(v => new [] { v.Vote.GetSessionIds()[0], v.Vote.GetSessionIds()[1], v.Vote.GetSessionIds()[2] }.Contains(s.Id.ToString()))
            })
                           .OrderBy(s => s.Title)
                           .ToArray();

            var tagSummaries = sessions.SelectMany(s => s.Tags).Distinct().OrderBy(t => t)
                               .Select(tag => new TagSummary
            {
                Tag         = tag,
                VoteSummary = new VoteSummary(sessions.Where(s => s.Tags.Contains(tag)).SelectMany(s => analysedVotes.Where(v => v.Vote.SessionIds.Contains(s.Id))).ToArray())
            }).ToArray();

            var response = new GetVotesResponse
            {
                VoteSummary  = new VoteSummary(analysedVotes),
                Sessions     = sessions.OrderByDescending(s => s.VoteSummary.RawTotal).ToArray(),
                TagSummaries = tagSummaries,
                Votes        = analysedVotes,
                UserSessions = userSessions.Select(x => new UserSession {
                    UserId = x.UserId, VoteId = x.VoteId, StartTime = x.StartTime
                }).ToArray()
            };
            var settings = new JsonSerializerSettings {
                ContractResolver = new DefaultContractResolver()
            };

            return(new JsonResult(response, settings));
        }