コード例 #1
0
        public void Execute()
        {
            var filterEntityId = EntityTypeCache.GetId(typeof(SQLFilter));

            if (!filterEntityId.HasValue)
            {
                throw new System.Exception("Could not find SQL Filter");
            }

            RockContext                   rockContext                   = new RockContext();
            DataViewFilterService         dataViewFilterService         = new DataViewFilterService(rockContext);
            DataViewSqlFilterStoreService dataViewSqlFilterStoreService = new DataViewSqlFilterStoreService(rockContext);

            var filters = dataViewFilterService.Queryable().Where(s => s.EntityTypeId == filterEntityId.Value).ToList();

            List <string> hashes = new List <string>();

            foreach (var filter in filters)
            {
                hashes.Add(Helpers.Md5Hash(filter.Selection));
            }

            ReportingContext reportingContext = new ReportingContext();
            var toDelete = reportingContext.DataViewSQLFilterStores
                           .Where(s => !hashes.Contains(s.Hash))
                           .Select(s => s.Hash).Distinct().ToList();

            foreach (var hash in toDelete)
            {
                rockContext.Database.ExecuteSqlCommand(string.Format("DELETE FROM _org_secc_Reporting_DataViewSQLFilterStore WHERE Hash = '{0}'", hash));
            }
        }
コード例 #2
0
        private void SetUpClient()
        {
            var builder = new WebHostBuilder()
                          .UseStartup <Startup>()
                          .ConfigureServices(services =>
            {
                var context = new ReportingContext(new DbContextOptionsBuilder <ReportingContext>()
                                                   .UseSqlite("DataSource=:memory:")
                                                   .EnableSensitiveDataLogging()
                                                   .Options);

                services.RemoveAll(typeof(ReportingContext));
                services.AddSingleton(context);

                context.Database.OpenConnection();
                context.Database.EnsureCreated();

                context.SaveChanges();

                // Clear local context cache
                foreach (var entity in context.ChangeTracker.Entries().ToList())
                {
                    entity.State = EntityState.Detached;
                }
            });

            _server = new TestServer(builder);

            Client = _server.CreateClient();
        }
コード例 #3
0
        public ActionResult Index()
        {
            var startDate = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1);

            using (var dbContext = new ReportingContext())
            {
                var buildSummary = GetLastBuildSummary(dbContext);
                var viewModel    = new HomeViewModel
                {
                    Builds       = buildSummary,
                    CoverageStat = new ModuleCoverageForABuild(),
                    Challenges   = ComputeChallengesSummary(dbContext, startDate, startDate.AddMonths(1)),
                };

                var mainProjectName = ConfigurationManager.AppSettings["MainProjectName"];
                var lastBuild       = !string.IsNullOrEmpty(mainProjectName) ? buildSummary.FirstOrDefault(i => i.ActualBuild.Definition == mainProjectName) : buildSummary.FirstOrDefault();
                if (lastBuild != null)
                {
                    var coverages = lastBuild.ActualBuild.CoverageCollection.OrderBy(i => (i.BlocksCovered * 100) / (i.BlocksNotCovered + i.BlocksCovered)).ToArray();
                    viewModel.CoverageStat.Modules   = string.Join(", ", coverages.Select(i => i.Name.Replace(".dll", string.Empty).Replace(".exe", string.Empty)));
                    viewModel.CoverageStat.Coverages = string.Join(", ", coverages.Select(i => (i.BlocksCovered * 100) / (i.BlocksNotCovered + i.BlocksCovered)));
                }

                viewModel.ShootBoxBuilds = GetLastBuilds(dbContext, startDate, startDate.AddMonths(1)).ToArray();
                return(View(viewModel));
            }
        }
コード例 #4
0
        public override void StreamEvents(InputDefinition inputDefinition)
        {
            #region Get stanza values

            Stanza stanza = inputDefinition.Stanza;
            SystemLogger.Write(string.Format("Name of Stanza is : {0}", stanza.Name));

            string reportName   = GetConfigurationValue(stanza, ConstantReportName);
            string emailAddress = GetConfigurationValue(stanza, ConstantEmailAddress);
            string password     = GetConfigurationValue(stanza, ConstantPassword);

            SystemLogger.Write(GetConfigurationValue(stanza, ConstantStartDate));

            DateTime startDate = TryParseDateTime(GetConfigurationValue(stanza, ConstantStartDate), DateTime.MinValue);
            DateTime endDate   = TryParseDateTime(GetConfigurationValue(stanza, ConstantEndDate), DateTime.MinValue);

            #endregion Get stanza values

            string streamName = stanza.Name;

            ReportingContext context = new ReportingContext("https://reports.office365.com/ecp/reportingwebservice/reporting.svc");
            context.UserName     = GetConfigurationValue(stanza, ConstantEmailAddress);
            context.Password     = GetConfigurationValue(stanza, ConstantPassword);
            context.FromDateTime = TryParseDateTime(GetConfigurationValue(stanza, ConstantStartDate), DateTime.MinValue);
            context.ToDateTime   = TryParseDateTime(GetConfigurationValue(stanza, ConstantEndDate), DateTime.MinValue);
            context.SetLogger(new SplunkTraceLogger());

            IReportVisitor visitor = new SplunkReportVisitor(streamName);

            ReportingStream stream = new ReportingStream(context, reportName, streamName);
            stream.RetrieveData(visitor);
        }
コード例 #5
0
        public async Task <IActionResult> TokenBased()
        {
            var test            = "dsfdsfs";
            ReportingContext db = new ReportingContext();
            var list            = await db.Users.ToListAsync();;

            return(Unauthorized());
        }
コード例 #6
0
        public ActivityController(ReportingContext context)
        {
            _context = context;

            //if (_context.Activities.Count() == 0)
            //{
            // Create a new TodoItem if collection is empty,
            // which means you can't delete all TodoItems.
            //    _context.Activities.Add(new Activity { Name = "Item1" });
            //    _context.SaveChanges();
            //}
        }
コード例 #7
0
        public static void AddActionsToScheduler(
            ReportJobConfiguration config,
            CoreBusinessLayerService service)
        {
            if (!config.get_Enabled())
            {
                return;
            }
            ReportingActionContext reportingActionContext = new ReportingActionContext();

            reportingActionContext.set_AccountID(config.get_AccountID());
            reportingActionContext.set_UrlsGroupedByLeftPart(ReportJobInitializer.GroupUrls(config));
            reportingActionContext.set_WebsiteID(config.get_WebsiteID());
            ReportingActionContext reportingContext  = reportingActionContext;
            MacroContext           macroContext      = ((ActionContextBase)reportingContext).get_MacroContext();
            ReportingContext       reportingContext1 = new ReportingContext();

            reportingContext1.set_AccountID(config.get_AccountID());
            reportingContext1.set_ScheduleName(config.get_Name());
            reportingContext1.set_ScheduleDescription(config.get_Description());
            reportingContext1.set_LastRun(config.get_LastRun());
            reportingContext1.set_WebsiteID(config.get_WebsiteID());
            macroContext.Add((ContextBase)reportingContext1);
            ((ActionContextBase)reportingContext).get_MacroContext().Add((ContextBase) new GenericContext());
            int num = 0;

            if (config.get_Schedules() == null)
            {
                return;
            }
            using (List <ReportSchedule> .Enumerator enumerator1 = config.get_Schedules().GetEnumerator())
            {
                while (enumerator1.MoveNext())
                {
                    ReportSchedule current  = enumerator1.Current;
                    DateTime       dateTime = !current.get_EndTime().HasValue ? DateTime.MaxValue : current.get_EndTime().Value;
                    Scheduler.get_Instance().Add(new ScheduledTask(string.Format("ReportJob-{0}_{1}", (object)config.get_ReportJobID(), (object)num), (TimerCallback)(o =>
                    {
                        ReportJobInitializer.log.Info((object)"Starting action execution");
                        using (List <ActionDefinition> .Enumerator enumerator = config.get_Actions().GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                service.ExecuteAction(enumerator.Current, (ActionContextBase)reportingContext);
                            }
                        }
                        config.set_LastRun(new DateTime?(DateTime.Now.ToUniversalTime()));
                        ReportJobDAL.UpdateLastRun(config.get_ReportJobID(), config.get_LastRun());
                    }), (object)null, current.get_CronExpression(), current.get_StartTime(), dateTime, config.get_LastRun(), current.get_CronExpressionTimeZoneInfo()), true);
                    ++num;
                }
            }
        }
コード例 #8
0
        public override bool Validate(Validation validation, out string errorMessage)
        {
            try
            {
                #region Get param values

                //Adding the validate value at the end to differentiate it from the real stream later created while streaming data
                string   streamName    = validation.Name + "validate";
                string   reportName    = validation.Parameters[ConstantReportName].ToString();
                string   emailAddress  = validation.Parameters[ConstantEmailAddress].ToString();
                string   password      = validation.Parameters[ConstantPassword].ToString();
                DateTime startDateTime = validation.Parameters[ConstantStartDate].ToString().TryParseDateTime(DateTime.MinValue);
                DateTime endDateTime   = validation.Parameters[ConstantEndDate].ToString().TryParseDateTime(DateTime.MaxValue);

                #endregion Get param values

                if (startDateTime > endDateTime)
                {
                    errorMessage = "From date must be less than or equal to To date";
                    return(false);
                }

                ReportingContext context = new ReportingContext();
                context.UserName     = emailAddress;
                context.Password     = password;
                context.FromDateTime = startDateTime;
                context.ToDateTime   = endDateTime;
                //TODO: Need the EventWriter instance to log stuff here
                context.SetLogger(new DefaultLogger());

                ReportingStream stream = new ReportingStream(context, reportName, streamName);

                bool res = stream.ValidateAccessToReport();
                if (res)
                {
                    errorMessage = "";
                    stream.ClearProgress();
                }
                else
                {
                    errorMessage = string.Format("An error occured while validating your crendentials against report: {0}", reportName);
                }
                return(res);
            }
            catch (Exception e)
            {
                errorMessage = e.Message;
                return(false);
            }
        }
コード例 #9
0
        private IEnumerable <ShootBoxBuild> GetLastBuilds(ReportingContext dbContext, DateTime startDate, DateTime stopDate)
        {
            return(dbContext.Builds.Where(i => i.Date >= startDate && i.Date < stopDate).OrderByDescending(i => i.Date).ToList().Select(i =>
            {
                var challenge = dbContext.Challenges.FirstOrDefault(j => j.Build.Id == i.Id);

                return new ShootBoxBuild
                {
                    BuildName = i.BuildName,
                    BuildDate = string.Format("{0} {1}", i.Date.ToShortDateString(), i.Date.ToShortTimeString()),
                    BuildColor = i.Status == "succeeded" ? "#5cb85c" : "#d9534f",
                    SumPoints = challenge != null ? Convert.ToInt32(challenge.Points) : 0,
                    DetailPoints = challenge != null ? challenge.ModuleCoverages : null,
                    User = i.User,
                };
            }));
        }
コード例 #10
0
        public IActionResult AddFilter(SavedSearches filter)
        {
            try
            {
                ReportingContext context = new ReportingContext();
                context.SavedSearches.Add(new SavedSearches {
                    UserId = filter.UserId, Field = filter.Field, Operator1 = filter.Operator1, Operator2 = filter.Operator2, Value1 = filter.Value1, Value2 = filter.Value2, IsPublic = filter.IsPublic, Searchname = filter.Searchname, Logic = filter.Logic
                });
                context.SaveChanges();

                //_context.SavedSearches.Add(new SavedSearches {UserId=filter.UserId, Field = filter.Field, Operator1 = filter.Operator1, Operator2 = filter.Operator2, Value1 = filter.Value1, Value2 = filter.Value2 });
                //_context.SaveChanges();
                return(Ok("Success"));
            }
            catch (Exception ex)
            {
                return(BadRequest());
            }
        }
コード例 #11
0
        private IEnumerable <ChallengeSummary> ComputeChallengesSummary(ReportingContext dbContext, DateTime startDate, DateTime stopDate)
        {
            var challenges = new List <ChallengeSummary>();
            var committers = dbContext.Builds.Where(i => i.Date >= startDate && i.Date < stopDate).Select(i => i.User).Distinct().ToArray();

            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var committer in committers)
            {
                var currentCommitter  = committer;
                var challengeEntities = dbContext.Challenges.Where(i => i.User == currentCommitter && i.Build.Date >= startDate && i.Build.Date < stopDate).ToList();
                var points            = challengeEntities.Sum(i => i.Points);
                var challengeSummary  = new ChallengeSummary
                {
                    Name   = committer,
                    Points = Convert.ToInt32(points)
                };
                challenges.Add(challengeSummary);
            }

            return(challenges.OrderByDescending(i => i.Points).Take(3));
        }
コード例 #12
0
        private List <BuildSummary> GetLastBuildSummary(ReportingContext dbContext)
        {
            var builds = new List <BuildSummary>();

            foreach (var buildName in ConfigurationManager.AppSettings["ExpectedBuilds"].Split('|'))
            {
                var orderByDescending = dbContext.Builds.OrderByDescending(i => i.Date);
                var build             = orderByDescending.FirstOrDefault(i => i.Definition == buildName);
                if (build == null)
                {
                    builds.Add(new BuildSummary {
                        ActualBuild = new BuildEntity {
                            BuildName = "Not actually a build.", CoverageCollection = new Collection <CoverageEntity>()
                        }, Challenge = new ChallengeEntity()
                    });
                    continue;
                }

                var actualBuild = build;
                foreach (var coverageEntity in actualBuild.CoverageCollection)
                {
                    coverageEntity.ComputedAverage =
                        (coverageEntity.BlocksCovered * 100) / (coverageEntity.BlocksCovered + coverageEntity.BlocksNotCovered);
                }
                actualBuild.CoverageCollection = actualBuild.CoverageCollection.OrderBy(i => i.ComputedAverage).ToArray();

                var actualAverageCoverage = ComputeBuildCoverage(actualBuild.CoverageCollection.ToList());

                var buildSummary = new BuildSummary
                {
                    ActualBuild           = actualBuild,
                    ActualAverageCoverage = actualAverageCoverage,
                    Challenge             = dbContext.Challenges.FirstOrDefault(i => i.Build.Id == actualBuild.Id),
                    UserGravatar          = CalculateMD5Hash(actualBuild.User.ToLower()).ToLower()
                };
                builds.Add(buildSummary);
            }

            return(builds);
        }
コード例 #13
0
        public override async Task StreamEventsAsync(InputDefinition inputDefinition, EventWriter eventWriter)
        {
            #region Get param values

            string streamName = inputDefinition.Name;
            await eventWriter.LogAsync(Severity.Info, string.Format("Name of Stanza is : {0}", inputDefinition.Name));

            string reportName = await GetConfigurationValue(inputDefinition, ConstantReportName, eventWriter);

            string emailAddress = await GetConfigurationValue(inputDefinition, ConstantEmailAddress, eventWriter);

            string password = await GetConfigurationValue(inputDefinition, ConstantPassword, eventWriter, false);

            string start = await GetConfigurationValue(inputDefinition, ConstantStartDate, eventWriter);

            DateTime startDateTime = start.TryParseDateTime(DateTime.MinValue);
            string   end           = await GetConfigurationValue(inputDefinition, ConstantEndDate, eventWriter);

            DateTime endDateTime = end.TryParseDateTime(DateTime.MinValue);

            #endregion Get param values

            ReportingContext context = new ReportingContext();
            context.UserName     = emailAddress;
            context.Password     = password;
            context.FromDateTime = startDateTime;
            context.ToDateTime   = endDateTime;
            context.SetLogger(new SplunkTraceLogger(eventWriter));

            IReportVisitor visitor = new SplunkReportVisitor(streamName, eventWriter);

            while (true)
            {
                await Task.Delay(1000);

                ReportingStream stream = new ReportingStream(context, reportName, streamName);
                stream.RetrieveData(visitor);
            }
        }
コード例 #14
0
        private double ComputeRatio(BuildEntity buildEntity, ReportingContext context)
        {
            var currentProject = context.Projects.FirstOrDefault(i => i.Name == buildEntity.Definition);

            if (currentProject == null)
            {
                currentProject = new ProjectEntity {
                    Name = buildEntity.Definition
                };
                context.Projects.Add(currentProject);
            }
            if (!buildEntity.CoverageCollection.Any())
            {
                return(0);
            }

            var currentProjectBlock = buildEntity.CoverageCollection.Sum(i => i.BlocksCovered + i.BlocksNotCovered);

            currentProject.Blocks = currentProjectBlock;

            if (!context.Projects.Any())
            {
                return(1);
            }

            var maxBlock   = context.Projects.Max(i => i.Blocks);
            var maxProject = context.Projects.FirstOrDefault(i => i.Blocks == maxBlock);

            if (maxProject == null || maxBlock == 0)
            {
                return(1); // Ratio = 1 : no project to be compared.
            }
            if (maxProject.Id == currentProject.Id)
            {
                return(1); // current projet is the bigest project.
            }
            return((double)currentProjectBlock / maxBlock);
        }
コード例 #15
0
        public ActionResult Challenges()
        {
            var monthChallenges = new List <MonthChallenge>();

            using (var context = new ReportingContext())
            {
                var firstDate = context.Builds.OrderBy(i => i.Date).Select(i => i.Date).FirstOrDefault();
                firstDate = new DateTime(firstDate.Year, firstDate.Month, 1);
                for (var date = firstDate; date < DateTime.UtcNow; date = date.AddMonths(1))
                {
                    var challengeSummary = ComputeChallengesSummary(context, date, date.AddMonths(1));
                    monthChallenges.Add(new MonthChallenge
                    {
                        Date    = date,
                        Summary = challengeSummary
                    });
                }
            }

            return(View(new ChallengesViewModel {
                MonthChallenges = monthChallenges.OrderByDescending(i => i.Date).ToArray()
            }));
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: panjkov/O365DataExtractor
        private static void Main(string[] args)
        {
            var options = new Options();

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                Credential creds = new Credential(null, null, options.CredentialManagerItemName);
                if (creds.Load())
                {
                    ReportingContext context = new ReportingContext();

                    context.UserName     = creds.Username;
                    context.Password     = creds.Password;
                    context.FromDateTime = options.From;
                    context.ToDateTime   = options.To;
                    context.SetLogger(new DefaultLogger());

                    IReportVisitor visitor = new DefaultReportVisitor();

                    ReportingStream stream = new ReportingStream(context, options.ReportName, options.StreamName);
                    stream.RetrieveData(visitor);
                }
            }
        }
コード例 #17
0
 public TransactionService(ReportingContext context)
 {
     _context = context;
 }
コード例 #18
0
 public ReportingRepository(ReportingContext context)
 {
     _context = context;
 }
コード例 #19
0
 private ReportingContextBuilder()
 {
     this.reportingContext = new ReportingContext();
 }
コード例 #20
0
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            if (selection.IsNotNullOrWhiteSpace())
            {
                var hash = Helpers.Md5Hash(selection);

                var                  rockContext         = ( RockContext )serviceInstance.Context;
                MethodInfo           queryableMethodInfo = serviceInstance.GetType().GetMethod("Queryable", new Type[] { });
                IQueryable <IEntity> entityQuery         = queryableMethodInfo.Invoke(serviceInstance, null) as IQueryable <IEntity>;

                var entityIds = serviceInstance.Context.Database.SqlQuery <int>(selection).ToList();

                //Small data sets don't need to be put in the database for subselect
                if (entityIds.Count <= 1000)
                {
                    var qry = entityQuery.Where(p => entityIds.Contains(p.Id));
                    return(FilterExpressionExtractor.Extract <IEntity>(qry, parameterExpression, "p"));
                }

                /*
                 * SqlQuery() returns what is essentially an IEnumerable. This means when we build our expression
                 * we won't be telling EF how to get the values we want, but the actual values themselves.
                 * This is okay for smallish sets of data, but if it gets over a few thousand it overwhelms SQL Server
                 * and throws an error. In testing with SQL Server 2017 this happened at around 32,000 items.
                 * The code below saves our data set in a skinny table so that we can query against it. Before querying
                 * it updates the table using direct requests to keep the data not stale.
                 * https://docs.microsoft.com/en-us/sql/t-sql/language-elements/in-transact-sql?view=sql-server-2017#remarks
                 */

                using (ReportingContext updateContext = new ReportingContext())
                {
                    var sqlStores = updateContext.DataViewSQLFilterStores;

                    //This is slower, but we need to stay out of the database
                    var storedEntityIds = sqlStores.Where(s => s.Hash == hash).Select(s => s.EntityId).ToList();

                    var toRemove = storedEntityIds.Except(entityIds).ToList();
                    var toAdd    = entityIds.Except(storedEntityIds).ToList();

                    //If we need to remove more than 5,000 entries it's faster/safer to just remove all the entries
                    if (toRemove.Count >= 5000)
                    {
                        updateContext.Database.ExecuteSqlCommand(string.Format("DELETE FROM _org_secc_Reporting_DataViewSQLFilterStore WHERE Hash = '{0}'", hash));
                        toAdd = entityIds;
                    }
                    else if (toRemove.Any())
                    {
                        updateContext.Database.ExecuteSqlCommand(string.Format("DELETE FROM _org_secc_Reporting_DataViewSQLFilterStore WHERE Hash = '{0}' AND EntityId IN ({1})", hash, string.Join(",", toRemove)));
                    }

                    if (toAdd.Any())
                    {
                        List <DataViewSQLFilterStore> storesToAdd = toAdd.Select(s =>
                                                                                 new DataViewSQLFilterStore()
                        {
                            Hash     = hash,
                            EntityId = s
                        }).ToList();

                        updateContext.BulkInsert(storesToAdd);
                    }
                }

                DataViewSqlFilterStoreService dataViewSqlFilterSoreService = new DataViewSqlFilterStoreService(rockContext);

                var selectedEntityIds = dataViewSqlFilterSoreService.Queryable().Where(s => s.Hash == hash).Select(s => s.EntityId);
                var subselectQry      = entityQuery.Where(p => selectedEntityIds.Contains(p.Id));
                return(FilterExpressionExtractor.Extract <IEntity>(subselectQry, parameterExpression, "p"));
            }
            return(null);
        }
コード例 #21
0
 public ReportingService(IPowerBIEmbedService powerBIEmbedService, ReportingContext reportingContext)
 {
     _powerBIEmbedService = powerBIEmbedService;
     _reportingContext    = reportingContext;
 }
コード例 #22
0
 public ReportService(ReportingContext context)
 {
     _context = context;
 }
コード例 #23
0
        public async Task <IHttpActionResult> Post([FromBody] HttpHookBuild build)
        {
            var knowDefinitionsBuilds = ConfigurationManager.AppSettings["ExpectedBuilds"].Split('|').Where(i => !string.IsNullOrEmpty(i)).ToArray();

            if (knowDefinitionsBuilds.Any() && !knowDefinitionsBuilds.Contains(build.resource.definition.name))
            {
                return(Ok());
            }

            try
            {
                using (var context = new ReportingContext())
                {
                    var request = build.resource.requests.FirstOrDefault();

                    var buildEntity = new BuildEntity
                    {
                        BuildName          = build.resource.buildNumber,
                        Definition         = build.resource.definition.name,
                        Date               = build.resource.finishTime,
                        Status             = build.resource.status,
                        Reason             = build.resource.reason,
                        Link               = build.message.html,
                        User               = request != null ? request.requestedFor.uniqueName : "Unknown user",
                        CoverageCollection = new Collection <CoverageEntity>()
                    };

                    if (buildEntity.User == "Project Collection Service Accounts")
                    {
                        buildEntity.User = "******";
                    }

                    if (buildEntity.User == ConfigurationManager.AppSettings["VsoUsername"])
                    {
                        return(Ok());
                    }

                    if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["VSO.OrganisationName"]) || string.IsNullOrEmpty(ConfigurationManager.AppSettings["VSO.ProjectName"]))
                    {
                        throw new ApplicationException("Please configuration VSO.OrganisationName and VSO.ProjectName first.");
                    }

                    var api      = new ApiWrapper(ConfigurationManager.AppSettings["VSO.OrganisationName"], ConfigurationManager.AppSettings["VSO.ProjectName"]);
                    var coverage = await api.GetBuildCoverageAsync(build);

                    if (coverage != null)
                    {
                        foreach (var moduleCoverage in coverage)
                        {
                            buildEntity.CoverageCollection.Add(new CoverageEntity
                            {
                                Name             = moduleCoverage.Name,
                                ComputedAverage  = moduleCoverage.ComputedAverage,
                                BlocksCovered    = moduleCoverage.BlocksCovered,
                                BlocksNotCovered = moduleCoverage.BlocksNotCovered,
                                Build            = buildEntity
                            });
                        }
                    }

                    double currentRatio = ComputeRatio(buildEntity, context);
                    var    challenge    = ComputeCoverageChanges(buildEntity, context, currentRatio);
                    if (challenge != null)
                    {
                        context.Challenges.Add(challenge);
                    }

                    context.Builds.Add(buildEntity);
                    context.SaveChanges();
                }

                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
コード例 #24
0
 public ReportingRepository(ReportingContext reportingContext, IPolicyAsyncExecutor resilientAsyncSqlExecutor, IPolicySyncExecutor resilientSyncSqlExecutor)
 {
     _reportingContext          = reportingContext ?? throw new ArgumentNullException(nameof(reportingContext));
     _resilientAsyncSqlExecutor = resilientAsyncSqlExecutor ?? throw new ArgumentNullException(nameof(resilientAsyncSqlExecutor));
     _resilientSyncSqlExecutor  = resilientSyncSqlExecutor ?? throw new ArgumentNullException(nameof(resilientSyncSqlExecutor));
 }
コード例 #25
0
 public UserService(ReportingContext context)
 {
     _context = context;
 }
コード例 #26
0
        private AboutViewModel GetCoverageStat(string buildName, int top)
        {
            using (var context = new ReportingContext())
            {
                var allStats = context.Builds
                               .Where(i => i.Definition == buildName && i.CoverageCollection.Any()).ToArray();

                if (top != 0)
                {
                    var count = allStats.Count();
                    if (count > top)
                    {
                        allStats = allStats.Skip(count - top).Take(top).ToArray();
                    }
                }

                var stats = allStats
                            .ToArray();
                var step            = (stats.Length / 20);
                var selectedEntries = new List <BuildEntity>();
                for (var i = stats.Min(a => a.Id); i < stats.Max(a => a.Id); i += step)
                {
                    var b = stats.FirstOrDefault(j => j.Id == i);
                    if (b != null)
                    {
                        selectedEntries.Add(b);
                    }
                }
                if (!selectedEntries.Any())
                {
                    return(new AboutViewModel {
                        BuildName = buildName, Message = "No coverage result"
                    });
                }


                if (selectedEntries.Count() == 1)
                {
                    selectedEntries = new List <BuildEntity> {
                        selectedEntries[0], selectedEntries[0]
                    };
                }

                selectedEntries = selectedEntries.OrderBy(i => i.Date).ToList();
                var moduleCoverages = new List <int>();
                foreach (var buildInformation in selectedEntries)
                {
                    if (buildInformation.CoverageCollection.Any())
                    {
                        var allCovered    = buildInformation.CoverageCollection.Sum(i => i.BlocksCovered);
                        var allNotCovered = buildInformation.CoverageCollection.Sum(i => i.BlocksNotCovered);
                        moduleCoverages.Add((allCovered * 100) / (allNotCovered + allCovered));
                    }
                    else
                    {
                        moduleCoverages.Add(0);
                    }
                }
                var averageStat = new ModuleCoverageByBuild
                {
                    ModuleName = buildName,
                    Dates      = string.Join(", ", selectedEntries.Select(i => string.Format("{0} {1}", i.Date.ToShortDateString(), i.Date.ToShortTimeString()))),
                    Coverages  = string.Join(", ", moduleCoverages)
                };

                return(new AboutViewModel
                {
                    BuildName = buildName,
                    AverageStatistics = averageStat,
                    BuildNames = ConfigurationManager.AppSettings["ExpectedBuilds"].Split('|').Select(i => new SelectListItem {
                        Text = i
                    }).ToList()
                });
            }
        }
コード例 #27
0
        private ChallengeEntity ComputeCoverageChanges(BuildEntity buildEntity, ReportingContext context, double currentRatio)
        {
            if (buildEntity.Status != "succeeded")
            {
                return(null);
            }

            var previousBuild = context.Builds
                                .OrderByDescending(i => i.Date)
                                .FirstOrDefault(i => i.Definition == buildEntity.Definition && i.Status == "succeeded" && i.CoverageCollection.Any());

            if (previousBuild == null)
            {
                return(null);
            }

            var challenge = new ChallengeEntity
            {
                User            = buildEntity.User,
                Build           = buildEntity,
                ModuleCoverages = new List <ModuleChallengeCoverage>()
            };

            var allModules = previousBuild.CoverageCollection.Select(i => i.Name).Union(buildEntity.CoverageCollection.Select(i => i.Name));

            foreach (var moduleName in allModules)
            {
                var currentModuleName = moduleName;

                var previousModule = previousBuild.CoverageCollection.FirstOrDefault(i => i.Name == currentModuleName);
                var currentModule  = buildEntity.CoverageCollection.FirstOrDefault(i => i.Name == currentModuleName);

                if (currentModule != null && previousModule != null && (previousModule.BlocksCovered == currentModule.BlocksCovered && previousModule.BlocksNotCovered == currentModule.BlocksNotCovered))
                {
                    continue; // Ignore if no change in the module.
                }
                if (currentModule == null)
                {
                    continue;
                }

                var previousModuleCoverage = ComputeBuildCoverage(previousModule);
                var currentModuleCoverage  = ComputeBuildCoverage(currentModule);

                var deltaCoverage = currentModuleCoverage - previousModuleCoverage;
                var allBlocks     = currentModule.BlocksCovered + currentModule.BlocksNotCovered;

                challenge.ModuleCoverages.Add(new ModuleChallengeCoverage {
                    Module = currentModuleName, DeltaCoverage = deltaCoverage, Blocks = allBlocks
                });
            }

            var previousProjectCoverage = ComputeBuildCoverage(previousBuild);
            var currentProjectCoverage  = ComputeBuildCoverage(buildEntity);

            challenge.Points = (currentProjectCoverage - previousProjectCoverage) * 100 * currentRatio;
            if (double.IsNaN(challenge.Points))
            {
                challenge.Points = 0;
            }

            return(challenge);
        }
コード例 #28
0
ファイル: ReportsService.cs プロジェクト: CmProfile/test
 public ReportsService(ReportingContext reportingContext, IStringLocalizer localizer)
 {
     _reportingContext = reportingContext;
     _localizer        = localizer;
 }
 public ReportingRepository(ReportingContext reportingContext)
 {
     _reportingContext = reportingContext ?? throw new ArgumentNullException(nameof(reportingContext));
 }
コード例 #30
0
 public ReportUsersController(ReportingContext context)
 {
     _context = context;
 }