public async Task <ReportMessage> CreateMessageAsync(AbstractReport reportData)
        {
            var msg = new MailMessage {
                IsBodyHtml = true
            };

            var mailAddressViewModel = new MailAddressViewModel(reportData, _logger);
            var recipients           = mailAddressViewModel.GetRecipientAdrresses();

            msg.From = mailAddressViewModel.From;
            msg.To.AddRange(recipients[RecipientType.TO]);
            msg.CC.AddRange(recipients[RecipientType.CC]);

            _logger.LogInformation("Sending mail for to address - " +
                                   string.Join(";", msg.To.Select(mailAddress => mailAddress.Address)));

            _logger.LogInformation("Sending mail for cc address - " +
                                   string.Join(";", msg.CC.Select(mailAddress => mailAddress.Address)));

            _logger.LogInformation("Creating view model for generating xml");
            var emailReportViewModel = new EmailReportViewModel(reportData, _emailReportConfiguration);

            _logger.LogInformation("Generated view model");

            msg.Subject = emailReportViewModel.EmailSubject;
            msg.Body    = GenerateBodyFromViewModel(emailReportViewModel);

            return(await Task.FromResult(new ReportMessage()
            {
                MailMessage = msg, SmtpConfiguration = reportData.SmtpConfiguration
            }));
        }
        public async Task AddReportDataAsync(AbstractReport reportData)
        {
            using (new PerformanceMeasurementBlock(nameof(TestSummaryDataProvider), _logger))
            {
                var priorityGroup = await GetTestRunSummaryWithPriority();

                var testSummaryGroups = new List <TestSummaryGroup>()
                {
                    priorityGroup
                };
                var summary =  //TODO - RetryHelper.Retry(() =>
                              await _tcmApiHelper.GetTestResultSummaryAsync();

                if (_reportDataConfiguration.GroupTestSummaryBy == TestResultsGroupingType.Priority)
                {
                    var prioritySummary = await GetTestSummaryByPriorityAsync();

                    testSummaryGroups.Add(prioritySummary);
                }

                _logger.LogInformation("Fetched data for test summary");
                reportData.Summary           = summary;
                reportData.TestSummaryGroups = testSummaryGroups;
            }
        }
        private void InitializeTestResultGroups(AbstractReport emailReportDto, EmailReportConfiguration emailReportConfig)
        {
            TestResultsGroups = new List <TestResultsGroupViewModel>();

            if (emailReportDto.FilteredResults != null)
            {
                foreach (var testSummaryGroup in emailReportDto.FilteredResults)
                {
                    var testResultsGroupViewModel = new TestResultsGroupViewModel(testSummaryGroup, emailReportConfig);

                    TestResultsGroups.Add(testResultsGroupViewModel);
                }
            }

            HasFilteredTests = emailReportDto.HasFilteredTests;

            if (TestResultsGroups.Count > 0)
            {
                if (emailReportConfig.ReportDataConfiguration.IncludePassedTests)
                {
                    HasTestResultsToShow = HasTestResultsToShow || TestResultsGroups.Any(t => t.PassedTests.Count > 0);
                }
                if (emailReportConfig.ReportDataConfiguration.IncludeFailedTests)
                {
                    HasTestResultsToShow = HasTestResultsToShow || TestResultsGroups.Any(t => t.FailedTests.Count > 0);
                }
                if (emailReportConfig.ReportDataConfiguration.IncludeOtherTests)
                {
                    HasTestResultsToShow = HasTestResultsToShow || TestResultsGroups.Any(t => t.OtherTests.Count > 0);
                }
            }
        }
        public async Task AddReportDataAsync(AbstractReport report)
        {
            if (report is ReleaseReport)
            {
                var releaseReport = report as ReleaseReport;
                using (new PerformanceMeasurementBlock("ReleaseDataProvider", _logger))
                {
                    // TODO - retry
                    _release = await _releaseHttpClient.GetReleaseAsync(_releaseConfiguration.ProjectId, _releaseConfiguration.Id);

                    if (_release == null)
                    {
                        throw new ReleaseNotFoundException(_releaseConfiguration.ProjectId + ": " + _releaseConfiguration.Id);
                    }

                    releaseReport.Artifacts   = new List <Artifact>(_release.Artifacts);
                    releaseReport.Release     = _release;
                    releaseReport.Environment = await GetEnvironmentAsync();

                    releaseReport.Phases = await GetPhasesAsync(releaseReport.Environment);

                    var lastCompletedRelease = await GetReleaseByLastCompletedEnvironmentAsync(releaseReport.Environment);

                    releaseReport.AssociatedChanges = await GetAssociatedChangesAsync(lastCompletedRelease);

                    releaseReport.LastCompletedRelease     = lastCompletedRelease;
                    releaseReport.LastCompletedEnvironment = lastCompletedRelease?.Environments?.FirstOrDefault(e => e.DefinitionEnvironmentId == _releaseConfiguration.DefinitionEnvironmentId);
                    releaseReport.CreatedBy = _release.CreatedBy;

                    _logger.LogInformation("ReleaseDataProvider: Fetched release data");
                }
            }
        }
        private string GetMailSubject(AbstractReport emailReportDto, ReportDataConfiguration reportDataConfiguration)
        {
            var userDefinedSubject = emailReportDto.MailConfiguration.MailSubject;

            if (string.IsNullOrWhiteSpace(userDefinedSubject))
            {
                throw new EmailReportException("Email subject not set");
            }

            string subject;

            if (passPercentageMatchRegex.IsMatch(userDefinedSubject))
            {
                var passPercentage = GetPassPercentage(emailReportDto, reportDataConfiguration.IncludeOthersInTotal);

                subject = passPercentageMatchRegex.Replace(userDefinedSubject, passPercentage);
            }
            else
            {
                subject = userDefinedSubject;
            }

            if (environmentStatusMatchRegex.IsMatch(subject))
            {
                subject = environmentStatusMatchRegex.Replace(subject, emailReportDto.GetEnvironmentStatus());
            }
            return(subject);
        }
        private string GetPassPercentage(AbstractReport emailReportDto, bool includeOthersInTotal)
        {
            var summary     = emailReportDto.Summary;
            var totalTests  = 0;
            var passedTests = 0;
            var failedTests = 0;

            if (summary != null)
            {
                if (summary.AggregatedResultsAnalysis.ResultsByOutcome.ContainsKey(TestOutcome.Passed))
                {
                    passedTests = summary.AggregatedResultsAnalysis.ResultsByOutcome[TestOutcome.Passed].Count;
                }
                if (summary.AggregatedResultsAnalysis.ResultsByOutcome.ContainsKey(TestOutcome.Failed))
                {
                    failedTests = summary.AggregatedResultsAnalysis.ResultsByOutcome[TestOutcome.Failed].Count;
                }

                totalTests = summary.AggregatedResultsAnalysis.TotalTests;

                if (!includeOthersInTotal)
                {
                    totalTests = passedTests + failedTests;
                }
            }

            return(TestResultsHelper.GetTestOutcomePercentageString(passedTests, totalTests));
        }
示例#7
0
        public async Task <bool> HasPreviousReleaseGotSameFailuresAsync(AbstractReport emailReportDto, PipelineConfiguration config, bool hasTestFailures, bool hasFailedTasks)
        {
            var hasPrevGotSameFailures = emailReportDto.HasPrevGotSameFailures();

            if (hasPrevGotSameFailures.HasValue)
            {
                return(hasPrevGotSameFailures.Value);
            }

            bool hasPrevFailedTasks = emailReportDto.HasPrevFailedTasks();

            if (emailReportDto.Summary == null)
            {
                return(false);
            }

            if (hasTestFailures)
            {
                var prevConfig = emailReportDto.GetPrevConfig(config);
                var lastCompletedTestResultSummary = await _tcmApiHelper.QueryTestResultsReportAsync(prevConfig);

                var failedInCurrent = GetFailureCountFromSummary(emailReportDto.Summary);
                var failedinPrev    = GetFailureCountFromSummary(lastCompletedTestResultSummary);

                // Threshold is 10 to decide whether they are same failures
                _logger.LogInformation($"Current Failures Found: '{failedInCurrent}'.");
                _logger.LogInformation($"Previous Failures Found: '{failedinPrev}'.");

                var hasSameFailures = failedInCurrent == failedinPrev;
                // No point in moving ahead if number of failures is different
                if (hasSameFailures)
                {
                    var currFailedTestCaseRefIds = await FetchFailedTestCaseIdsAsync(config);

                    var prevFailedTestCaseRefIds = await FetchFailedTestCaseIdsAsync(prevConfig);

                    var nonInteresection = currFailedTestCaseRefIds.Except(prevFailedTestCaseRefIds).Union(prevFailedTestCaseRefIds.Except(currFailedTestCaseRefIds));

                    if (nonInteresection.Any())
                    {
                        _logger.LogInformation($"Difference in Failed Test Reference Ids found between current - '{string.Join(",", nonInteresection.ToArray())}'.");
                        hasSameFailures = false;
                    }
                    else
                    {
                        _logger.LogInformation($"Failed Test Reference Ids match. No new failures found.");
                        hasSameFailures = true;
                    }
                }

                return(hasSameFailures);
            }
            else if (hasFailedTasks && hasPrevFailedTasks)
            {
                return(emailReportDto.ArePrevFailedTasksSame());
            }

            return(false);
        }
        public AbstractReportTest(int majorVersion)
        {
            var reportCodename = AbstractReport <TermsType> .GetCodename(typeof(ReportType));

            TokenExpressionResolver.RegisterTokenExpressions(typeof(TokenExpressionResolver).Assembly);

            InitializeCommonMocks(majorVersion, reportCodename);
        }
示例#9
0
        public static bool HasCanceledPhases(this AbstractReport source)
        {
            if (source.Phases == null)
            {
                return(false);
            }

            return(source.Phases.Any(p => p.Jobs != null && p.Jobs.Any(j => j.JobStatus == TaskStatus.Canceled)));
        }
示例#10
0
        private static TestSummaryGroup GetSummaryGroup(this AbstractReport source)
        {
            var summaryGroup = source.TestSummaryGroups?.First();

            if (summaryGroup == null)
            {
                // TODO - Log.LogError("summary group not found");
            }
            return(summaryGroup);
        }
示例#11
0
        public static bool HasPassedTests(this AbstractReport source)
        {
            if (source.Summary == null)
            {
                return(false);
            }

            return(source.Summary.AggregatedResultsAnalysis.ResultsByOutcome.ContainsKey(TestOutcome.Passed) &&
                   source.Summary.AggregatedResultsAnalysis.ResultsByOutcome[TestOutcome.Passed].Count > 0);
        }
        public async Task AddReportDataAsync(AbstractReport reportData)
        {
            var failedTestResultIds = await _tcmApiHelper.GetTestSummaryAsync(TestResultsConstants.TestRun, TestOutcome.Failed);

            List <TestCaseResult> resultsToFetch = failedTestResultIds.ResultsForGroup.SelectMany(group => group.Results).ToList();

            reportData.FailedTestOwners = await _tcmApiHelper.GetTestResultOwnersAsync(resultsToFetch);

            _logger.LogInformation("Fetched test owners data");
        }
 private void InitializeAssociatedChanges(AbstractReport emailReportDto, PipelineConfiguration config)
 {
     if (emailReportDto.AssociatedChanges?.Any() == true)
     {
         AssociatedChanges = new List <ChangeViewModel>();
         foreach (var associatedChange in emailReportDto.AssociatedChanges)
         {
             AssociatedChanges.Add(new ChangeViewModel(associatedChange, config));
         }
     }
 }
        public async Task AddReportDataAsync(AbstractReport reportData)
        {
            using (new PerformanceMeasurementBlock("In TestResultsDataProvider", _logger))
            {
                // This is to make sure the failing since information is computed before we fetch test results
                await _tcmApiHelper.QueryTestResultsReportAsync();

                _logger.LogInformation("Fetched test results data");
                await GetFilteredTestResultsAsync(reportData);
            }
        }
示例#15
0
        public static ReportModel GetReport(ReportModel model = null)
        {
            var userControl = new AbstractReport();
            var vm          = userControl.DataContext as AbstractReportViewModel;

            vm.SetReportInModel(model);
            if (TelaUtils.Instance.AbrirDialog(userControl) ?? true)
            {
                return(vm.GetReportModel());
            }
            return(null);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // Organiza os argumentos recebidos na querystring
            ArgumentBuilder argumentBuilder = new ArgumentBuilder();

            foreach (String argumentName in Request.QueryString)
            {
                argumentBuilder.Add(argumentName, Request.QueryString[argumentName]);
            }

            // Cria uma instância da classe de relatório ( através de Reflection )
            Type           reportClass = null;
            AbstractReport report      = null;

            if (!String.IsNullOrEmpty(Request["report"]))
            {
                // Usa a classe base dos relatórios para obter o nome completo da classe incluindo dll/assembly
                String qualifiedName = typeof(AbstractReport).AssemblyQualifiedName;
                qualifiedName = qualifiedName.Replace("AbstractReport", Request["report"]);

                reportClass = Type.GetType(qualifiedName);
                report      = (AbstractReport)Activator.CreateInstance(reportClass, argumentBuilder.GetArguments(reportClass));
            }

            // Aborta a operação caso o relatório solicitado não exista
            if ((reportClass == null) || (report == null))
            {
                return;
            }

            Dictionary <String, Object> exportOptions = ExportFormatContext.GetExportOptions(Session);

            this.Response.Clear();
            this.Response.ContentType = (String)exportOptions["ContentType"];
            this.Response.AddHeader("content-disposition", (String)exportOptions["Disposition"]);

            // Abre a conexão com o banco
            DataAccess dataAccess = DataAccess.Instance;

            dataAccess.MountConnection(FileResource.MapWebResource(this.Page.Server, "DataAccess.xml"), DatabaseEnum.PrintAccounting);
            dataAccess.OpenConnection();

            // Executa inicializações e chama o método "BuildReport" na instância da classe de relatório
            report.InitializeComponents(this.Page, (IReportBuilder)exportOptions["ReportBuilder"], dataAccess.GetConnection());
            report.BuildReport();

            // Fecha a conexão com o banco
            dataAccess.CloseConnection();
            dataAccess = null;

            this.Response.End();
        }
        private async Task GetFilteredTestResultsAsync(AbstractReport reportData)
        {
            if (_reportDataConfiguration.IncludeFailedTests || _reportDataConfiguration.IncludeOtherTests ||
                _reportDataConfiguration.IncludePassedTests)
            {
                var groupBy          = TestResultsConstants.GetName(_reportDataConfiguration.GroupTestResultsBy);
                var includedOutcomes = GetIncludedOutcomes();

                var resultIdsToFetch = await _tcmApiHelper.GetTestSummaryAsync(groupBy, includedOutcomes.ToArray());

                reportData.HasFilteredTests = FilterTestResults(resultIdsToFetch, _reportDataConfiguration.MaxFailuresToShow);
                reportData.FilteredResults  = (await GetTestResultsWithWorkItemsAsync(resultIdsToFetch)).ToList();
            }
        }
 private void InitializeSummaryGroupViewModel(AbstractReport emailReportDto, ReportDataConfiguration reportDataConfiguration, PipelineConfiguration config)
 {
     SummaryGroups = new List <TestSummaryGroupViewModel>();
     if (emailReportDto.TestSummaryGroups != null)
     {
         foreach (var testSummaryGroup in emailReportDto.TestSummaryGroups)
         {
             if (reportDataConfiguration.GroupTestSummaryBy == testSummaryGroup.GroupingType)
             {
                 // TODO - Log.LogVerbose($"Creating summary group viewmodel for {testSummaryGroupDto.GroupedBy}");
                 SummaryGroups.Add(new TestSummaryGroupViewModel(testSummaryGroup, config, reportDataConfiguration.IncludeOthersInTotal));
             }
         }
     }
 }
        public async Task AddReportDataAsync(AbstractReport reportData)
        {
            var secret = await KeyVaultReader.FetchSecret(
                MailConfiguration.KeyVaultName,
                MailConfiguration.SecretName,
                MailConfiguration.RetryCount,
                _logger);

            reportData.SmtpConfiguration = new SmtpConfiguration()
            {
                EnableSSL = true,
                SmtpHost  = MailConfiguration.SmtpHost,
                UserName  = MailConfiguration.MailSenderAddress,
                Password  = secret.Value
            };
        }
        private void InitializePhases(AbstractReport emailReportDto)
        {
            Phases = new List <PhaseViewModel>();
            if (emailReportDto.Phases?.Any() != true)
            {
                return;
            }

            foreach (var phase in emailReportDto.Phases)
            {
                Phases.Add(new PhaseViewModel(phase));
            }

            if (HasCanceledPhases)
            {
                PhaseIssuesSummary = new PhaseIssuesViewModel(emailReportDto.Phases);
            }
        }
示例#21
0
        public static bool HasFailedTests(this AbstractReport source, bool includeOthers)
        {
            if (source.Summary == null)
            {
                return(false);
            }

            if (!includeOthers)
            {
                return(source.Summary.AggregatedResultsAnalysis.ResultsByOutcome.ContainsKey(TestOutcome.Failed) &&
                       source.Summary.AggregatedResultsAnalysis.ResultsByOutcome[TestOutcome.Failed].Count > 0);
            }

            if (source.HasPassedTests())
            {
                return(source.Summary.AggregatedResultsAnalysis.TotalTests -
                       source.Summary.AggregatedResultsAnalysis.ResultsByOutcome[TestOutcome.Passed].Count > 0);
            }

            return(source.Summary.AggregatedResultsAnalysis.TotalTests > 0);
        }
        public EmailReportViewModel(AbstractReport emailReportDto, EmailReportConfiguration emailReportConfiguration)
        {
            var config = emailReportConfiguration.PipelineConfiguration;

            ProjectName     = config.ProjectName;
            HasTaskFailures = emailReportDto.HasFailedTasks();
            Release         = emailReportDto.GetReleaseViewModel(config);
            Build           = emailReportDto.GetBuildViewModel(config);
            Artifacts       = emailReportDto.GetArtifactViewModels(config);

            HasCanceledPhases = emailReportDto.HasCanceledPhases();
            InitializePhases(emailReportDto);

            var reportDataConfiguration = emailReportConfiguration.ReportDataConfiguration;

            EmailSubject   = GetMailSubject(emailReportDto, reportDataConfiguration);
            HasFailedTests = emailReportDto.HasFailedTests(reportDataConfiguration.IncludeOthersInTotal);

            var summaryGroupDto = emailReportDto.TestSummaryGroups?.First();

            if (emailReportDto.Summary != null)
            {
                AllTests = new TestResultSummaryViewModel(emailReportDto.Summary,
                                                          config,
                                                          reportDataConfiguration.IncludeOthersInTotal);
            }

            InitializeSummaryGroupViewModel(emailReportDto, emailReportConfiguration.ReportDataConfiguration, config);
            ShowAssociatedChanges = reportDataConfiguration.IncludeCommits;

            if (ShowAssociatedChanges)
            {
                InitializeAssociatedChanges(emailReportDto, config);
            }

            InitializeTestResultGroups(emailReportDto, emailReportConfiguration);

            TestTabLink = config.TestTabLink;
            DataMissing = emailReportDto.DataMissing;
        }
示例#23
0
 public void LoadReport(AbstractReport report) => _reportsStorage.Add(report);
示例#24
0
        public static void Merge(this AbstractReport source, AbstractReport target)
        {
            switch (source)
            {
            case ReleaseReport releaseSource:
                var releaseTarget = target as ReleaseReport
                                    ?? throw new NotSupportedException();

                if (releaseTarget.Artifacts != null)
                {
                    ThrowIfNotNull(releaseSource.Artifacts, nameof(releaseSource.Artifacts));
                    releaseSource.Artifacts = releaseTarget.Artifacts;
                }

                if (releaseTarget.Release != null)
                {
                    ThrowIfNotNull(releaseSource.Release, nameof(releaseTarget.Release));
                    releaseSource.Release = releaseTarget.Release;
                }

                if (releaseTarget.Environment != null)
                {
                    ThrowIfNotNull(releaseSource.Environment, nameof(releaseTarget.Environment));
                    releaseSource.Environment = releaseTarget.Environment;
                }

                if (releaseTarget.LastCompletedRelease != null)
                {
                    ThrowIfNotNull(releaseSource.LastCompletedRelease, nameof(releaseSource.LastCompletedRelease));
                    releaseSource.LastCompletedRelease = releaseTarget.LastCompletedRelease;
                }

                if (releaseTarget.LastCompletedEnvironment != null)
                {
                    ThrowIfNotNull(releaseSource.LastCompletedEnvironment, nameof(releaseSource.LastCompletedEnvironment));
                    releaseSource.LastCompletedEnvironment = releaseTarget.LastCompletedEnvironment;
                }

                if (releaseTarget.SmtpConfiguration != null)
                {
                    ThrowIfNotNull(releaseSource.SmtpConfiguration, nameof(releaseSource.SmtpConfiguration));
                    releaseSource.SmtpConfiguration = releaseTarget.SmtpConfiguration;
                }

                break;

            //TODO - case BuildEmailReportDto buildSource:
            //    var buildTarget = target as BuildEmailReportDto
            //        ?? throw new NotSupportedException();

            //    if (buildTarget.Build != null)
            //    {
            //        ThrowIfNotNull(buildSource.Build, nameof(buildSource.Build));
            //        buildSource.Build = buildTarget.Build;
            //    }

            //    if (buildTarget.Timeline != null)
            //    {
            //        ThrowIfNotNull(buildSource.Timeline, nameof(buildSource.Timeline));
            //        buildSource.Timeline = buildTarget.Timeline;
            //    }

            //    if (buildTarget.LastCompletedBuild != null)
            //    {
            //        ThrowIfNotNull(buildSource.LastCompletedBuild, nameof(buildSource.LastCompletedBuild));
            //        buildSource.LastCompletedBuild = buildTarget.LastCompletedBuild;
            //    }

            //    if (buildTarget.LastCompletedTimeline != null)
            //    {
            //        ThrowIfNotNull(buildSource.LastCompletedTimeline, nameof(buildSource.LastCompletedTimeline));
            //        buildSource.LastCompletedTimeline = buildTarget.LastCompletedTimeline;
            //    }

            //    break;

            default:
                throw new NotSupportedException();
            }

            if (target.TestSummaryGroups != null)
            {
                ThrowIfNotNull(source.TestSummaryGroups, nameof(source.TestSummaryGroups));

                source.TestSummaryGroups = target.TestSummaryGroups;
            }

            if (target.AssociatedChanges != null)
            {
                ThrowIfNotNull(source.AssociatedChanges, nameof(source.AssociatedChanges));

                source.AssociatedChanges = target.AssociatedChanges;
            }

            if (target.CreatedBy != null)
            {
                ThrowIfNotNull(source.CreatedBy, nameof(source.CreatedBy));

                source.CreatedBy = target.CreatedBy;
            }

            if (target.FailedTestOwners != null)
            {
                ThrowIfNotNull(source.FailedTestOwners, nameof(source.FailedTestOwners));

                source.FailedTestOwners = target.FailedTestOwners;
            }

            if (target.FilteredResults != null)
            {
                ThrowIfNotNull(source.FilteredResults, nameof(source.FilteredResults));

                source.FilteredResults = target.FilteredResults;
            }

            if (target.HasFilteredTests)
            {
                ThrowIfTrue(source.HasFilteredTests, nameof(source.HasFilteredTests));

                source.HasFilteredTests = target.HasFilteredTests;
            }

            if (target.Summary != null)
            {
                ThrowIfNotNull(source.Summary, nameof(source.Summary));

                source.Summary = target.Summary;
            }

            if (target.Phases != null)
            {
                ThrowIfNotNull(source.Phases, nameof(source.Phases));

                source.Phases = target.Phases;
            }
        }
示例#25
0
 public MailAddressViewModel(AbstractReport reportData, ILogger logger)
 {
     _logger     = logger;
     _reportData = reportData;
 }
        private IReport LoadReport(Serialization.Report xmlReport, bool proxy)
        {
            AbstractReport report = null;

            if (proxy)
            {
                report = new ReportProxy();
            }
            else
            {
                report = new Report();
            }

            report.Id          = xmlReport.Id;
            report.Name        = xmlReport.Name;
            report.Description = xmlReport.Description;

            if (xmlReport.NewUntilSpecified)
            {
                report.IsNew = xmlReport.NewUntil > DateTime.Now;
            }
            else
            {
                report.IsNew = false;
            }

            report.ReportType = (ReportType)Enum.Parse(typeof(ReportType), xmlReport.ReportType.ToString());

            if (xmlReport.ReportProcessingLocation.Use.Equals(Serialization.ActiveReportProcessingLocation.LocalReport))
            {
                string directory = ConfigurationManager.AppSettings["FirstLook.Reports.App.ReportDefinitionLibrary.Xml.XmlReportDefinitionFactory.Report.Directory"];

                Serialization.LocalReport localReport = xmlReport.ReportProcessingLocation.LocalReport;

                LocalReportProcessingLocation location = new LocalReportProcessingLocation();
                location.File           = directory + Path.DirectorySeparatorChar + localReport.File;
                location.DataSourceName = localReport.DataSourceName;

                report.ReportProcessingLocation = location;
            }
            else
            {
                string serverUrl = ConfigurationManager.AppSettings["FirstLook.Reports.App.ReportDefinitionLibrary.Xml.XmlReportDefinitionFactory.Report.ServerUrl"];

                Serialization.ServerReport serverReport = xmlReport.ReportProcessingLocation.ServerReport;

                RemoteReportProcessingLocation location = new RemoteReportProcessingLocation();
                location.Path      = serverReport.Path;
                location.ServerUrl = new Uri(serverUrl);

                report.ReportProcessingLocation = location;
            }

            IList <IReportParameter> reportParameters = new List <IReportParameter>();

            if (xmlReport.Parameters != null && xmlReport.Parameters.Length > 0)
            {
                foreach (Serialization.Parameter xmlParameter in xmlReport.Parameters)
                {
                    ReportParameter reportParameter = new ReportParameter();
                    reportParameter.AllowBlank = xmlParameter.AllowBlank;
                    reportParameter.AllowNull  = xmlParameter.AllowNull;
                    reportParameter.Label      = xmlParameter.Label;
                    reportParameter.Name       = xmlParameter.Name;
                    reportParameter.ReportParameterDataType  = (ReportParameterDataType)Enum.Parse(typeof(ReportParameterDataType), xmlParameter.ParameterDataType.ToString());
                    reportParameter.ReportParameterInputType = (ReportParameterInputType)Enum.Parse(typeof(ReportParameterInputType), xmlParameter.ParameterInputType.ToString());

                    AbstractReportParameterValues reportParameterValues = new ReportParameterValuesConstant();

                    if (xmlParameter.ValidValues != null)
                    {
                        if (xmlParameter.ValidValues.Item is Serialization.ParameterRange)
                        {
                            Serialization.ParameterRange xmlParameterRange = (Serialization.ParameterRange)xmlParameter.ValidValues.Item;

                            if (xmlParameterRange.Item is Serialization.DateRange)
                            {
                                Serialization.DateRange xmlDateRange = xmlParameterRange.Item;

                                DateRange dateRange = new DateRange();
                                dateRange.InitialUnit     = (TimeUnit)Enum.Parse(typeof(TimeUnit), xmlDateRange.InitialUnit.ToString());
                                dateRange.InitialDistance = Int32.Parse(xmlDateRange.InitialDistance);
                                dateRange.DistanceUnit    = (TimeUnit)Enum.Parse(typeof(TimeUnit), xmlDateRange.DistanceUnit.ToString());;
                                dateRange.Distance        = Int32.Parse(xmlDateRange.Distance);
                                dateRange.NumberOfItems   = Int32.Parse(xmlDateRange.NumberOfItems);
                                dateRange.Direction       = (TimeDirection)Enum.Parse(typeof(TimeDirection), xmlDateRange.Direction.ToString());

                                Serialization.DateTimeFormatInfo xmlDtfi = xmlDateRange.DateTimeFormatInfo;

                                System.Globalization.DateTimeFormatInfo dtfi = new System.Globalization.DateTimeFormatInfo();

                                if (!string.IsNullOrEmpty(xmlDtfi.FullDateTimePattern))
                                {
                                    dtfi.FullDateTimePattern = xmlDtfi.FullDateTimePattern;
                                }

                                if (!string.IsNullOrEmpty(xmlDtfi.LongDatePattern))
                                {
                                    dtfi.LongDatePattern = xmlDtfi.LongDatePattern;
                                }

                                if (!string.IsNullOrEmpty(xmlDtfi.LongTimePattern))
                                {
                                    dtfi.LongTimePattern = xmlDtfi.LongTimePattern;
                                }

                                if (!string.IsNullOrEmpty(xmlDtfi.MonthDayPattern))
                                {
                                    dtfi.MonthDayPattern = xmlDtfi.MonthDayPattern;
                                }

                                if (!string.IsNullOrEmpty(xmlDtfi.ShortDatePattern))
                                {
                                    dtfi.ShortDatePattern = xmlDtfi.ShortDatePattern;
                                }

                                if (!string.IsNullOrEmpty(xmlDtfi.ShortTimePattern))
                                {
                                    dtfi.ShortTimePattern = xmlDtfi.ShortTimePattern;
                                }

                                if (!string.IsNullOrEmpty(xmlDtfi.YearMonthPattern))
                                {
                                    dtfi.YearMonthPattern = xmlDtfi.YearMonthPattern;
                                }

                                int index = 0, selectedIndex = Int32.Parse(xmlDateRange.SelectedIndex);

                                foreach (DateTime value in dateRange.Items())
                                {
                                    ReportParameterValue reportParameterValue = new ReportParameterValue();
                                    reportParameterValue.Label    = value.ToString(xmlDateRange.LabelDateTimeFormatSpecifier.ToString(), dtfi);
                                    reportParameterValue.Value    = value.ToString(xmlDateRange.ValueDateTimeFormatSpecifier.ToString(), dtfi);
                                    reportParameterValue.Selected = (index++ == selectedIndex);
                                    reportParameterValues.AddReportParameterValue(reportParameterValue);
                                }
                            }
                            else
                            {
                                // ADD NEW RANGE ELEMENT CODE HERE
                            }
                        }
                        else if (xmlParameter.ValidValues.Item is Serialization.DomainModel)
                        {
                            Serialization.DomainModel xmlDomainModel = (Serialization.DomainModel)xmlParameter.ValidValues.Item;

                            IDictionary <string, string> parameterLabelValuePair = new Dictionary <string, string>();
                            parameterLabelValuePair.Add("Label", xmlDomainModel.Label.Name);
                            parameterLabelValuePair.Add("Value", xmlDomainModel.Value.Name);

                            reportParameterValues = new ReportParameterValuesDynamic(Type.GetType(xmlDomainModel.DomainModelName), xmlDomainModel.InvokeMethod.MethodName,
                                                                                     parameterLabelValuePair);

                            foreach (Serialization.MethodArgument argument in xmlDomainModel.InvokeMethod.Arguments)
                            {
                                ((ReportParameterValuesDynamic)reportParameterValues).AddMethodArgumentEntry(argument.Name, Type.GetType(argument.Type), argument.Value, argument.Source.ToString());
                            }

                            IList <IReportParameterValue> staticParameterValues = new List <IReportParameterValue>();

                            if (xmlDomainModel.CustomValues != null)
                            {
                                int index = System.Int32.Parse(xmlDomainModel.CustomValues.Insert.Index);

                                foreach (Serialization.ParameterValue parameterValue in xmlDomainModel.CustomValues.Insert.ParameterValue)
                                {
                                    ReportParameterValue reportParameterValue = new ReportParameterValue();
                                    reportParameterValue.Label    = parameterValue.Label;
                                    reportParameterValue.Value    = parameterValue.Value;
                                    reportParameterValue.Selected = parameterValue.Selected;

                                    staticParameterValues.Add(reportParameterValue);
                                }
                            }

                            bool itemSelected = false;

                            // this logic is build on the assumption you can only preselect custom fields - is this a safe assumption?
                            if (xmlDomainModel.Selected != null)
                            {
                                if (xmlDomainModel.Selected.Index != null)
                                {
                                    ((ReportParameterValue)staticParameterValues[System.Int32.Parse(xmlDomainModel.Selected.Index)]).Selected = true;
                                    itemSelected = true;
                                }
                                if (xmlDomainModel.Selected.Value != null)
                                {
                                    foreach (ReportParameterValue x in staticParameterValues)
                                    {
                                        if (x.Value.Equals(xmlDomainModel.Selected.Value))
                                        {
                                            x.Selected   = true;
                                            itemSelected = true;
                                            break;
                                        }
                                    }
                                }
                            }

                            if (!itemSelected)
                            {
                                if (staticParameterValues.Count > 0)
                                {
                                    ((ReportParameterValue)staticParameterValues[0]).Selected = true;
                                }
                            }

                            reportParameterValues.AddReportParameterValues(staticParameterValues);
                        }
                        else // ReportDefinitionLibrary.Xml.ParameterValues
                        {
                            Serialization.ParameterValue[] xmlParameterValues = (Serialization.ParameterValue[])xmlParameter.ValidValues.Item;

                            foreach (Serialization.ParameterValue parameterValue in xmlParameterValues)
                            {
                                ReportParameterValue reportParameterValue = new ReportParameterValue();
                                reportParameterValue.Label    = parameterValue.Label;
                                reportParameterValue.Value    = parameterValue.Value;
                                reportParameterValue.Selected = parameterValue.Selected;

                                reportParameterValues.AddReportParameterValue(reportParameterValue);
                            }
                        }
                    }

                    reportParameter.ReportParameterValues = reportParameterValues;

                    reportParameters.Add(reportParameter);
                }
            }

            report.ReportParameters = reportParameters;

            if (!proxy)
            {
                // Work against the RDL to extract data sources and verify parameters

                IList <IReportDataSource> dataSources = new List <IReportDataSource>();

                if (report.ReportProcessingLocation is LocalReportProcessingLocation)
                {
                    string filename = ((LocalReportProcessingLocation)report.ReportProcessingLocation).File;

                    FirstLook.Reports.App.ReportDefinitionLibrary.ReportDefinitionLanguage.Report rdl = ReportDefinitionLanguageFacade.LoadReport(filename);

                    ReportDefinitionLanguageFacade.PopulateReportDataSources((Report)report, rdl);

                    ReportDefinitionLanguageFacade.VerifyReportParameters((Report)report, rdl);
                }
            }

            return(report);
        }
示例#27
0
        public async Task AddReportDataAsync(AbstractReport emailReportDto)
        {
            var mailConfigs = _emailReportConfiguration.MailConfigurations;

            var shouldSendMail = emailReportDto.DataMissing;
            MailConfiguration mailConfigurationToUse = null;

            if (!shouldSendMail)
            {
                // Evaluate each configuration and see what matches
                foreach (var mailConfig in mailConfigs)
                {
                    if (mailConfig.SendMailCondition == SendMailCondition.Always)
                    {
                        mailConfigurationToUse = mailConfig;
                    }
                    else
                    {
                        if (!_testfailuresFlagsInitialized)
                        {
                            hasTestFailures               = emailReportDto.HasFailedTests(_emailReportConfiguration.ReportDataConfiguration.IncludeOthersInTotal);
                            hasFailedTasks                = emailReportDto.HasFailedTasks();
                            hasCanceledPhases             = emailReportDto.HasCanceledPhases();
                            _testfailuresFlagsInitialized = true;
                        }
                        var hasFailures = hasTestFailures || hasFailedTasks || hasCanceledPhases;

                        if ((mailConfig.SendMailCondition == SendMailCondition.OnFailure && hasFailures) ||
                            (mailConfig.SendMailCondition == SendMailCondition.OnSuccess && !hasFailures))
                        {
                            mailConfigurationToUse = mailConfig;
                        }
                        else if (mailConfig.SendMailCondition == SendMailCondition.OnNewFailuresOnly && hasFailures)
                        {
                            // Always treat phase cancellation issues as new failure as we cannot distinguish/compare phase level issues
                            // Still compare failed tests and failed tasks where possible to reduce noise
                            if (hasCanceledPhases && !hasTestFailures && !hasFailedTasks)
                            {
                                mailConfigurationToUse = mailConfig;
                                _logger.LogInformation($"Has Phase cancellation(s) issues. Treating as new failure.");
                            }
                            else
                            {
                                _logger.LogInformation(
                                    $"Looking for new failures, as the user send mail condition is '{mailConfig.SendMailCondition}'.");
                                if (hasPreviousReleaseGotSameFailures == null)
                                {
                                    hasPreviousReleaseGotSameFailures = await HasPreviousReleaseGotSameFailuresAsync(emailReportDto, _emailReportConfiguration.PipelineConfiguration, hasTestFailures, hasFailedTasks);
                                }
                                shouldSendMail         = !hasPreviousReleaseGotSameFailures.Value;
                                mailConfigurationToUse = mailConfig;
                            }
                        }
                    }

                    if (mailConfigurationToUse != null)
                    {
                        break;
                    }
                }
            }

            emailReportDto.MailConfiguration = mailConfigurationToUse;
        }