コード例 #1
0
        public void ShouldGetTemplateById()
        {
            const long templateId = 123;

            const string titletemplate = "title template";

            const string bodyTemplate = "body template";

            var templateDb = new Templates
            {
                Title = titletemplate,
                Body  = bodyTemplate,
                Id    = templateId
            };

            _templateRepository
            .Setup(_ => _.GetById(templateId))
            .Returns(templateDb);

            var template = new Mock <ITemplateWithTitle>();

            _templateBuilder
            .Setup(_ => _.Build(titletemplate, bodyTemplate))
            .Returns(template.Object);

            var result = _target.Get(templateId);

            result.Should().NotBeNull();
            result.ShouldBeEquivalentTo(template.Object);
        }
コード例 #2
0
        public byte[] Build(int salesOrderId)
        {
            var invoice = _invoiceRepository.Get(salesOrderId);

            using (var template = new MemoryStream(_templateProvider.Get()))
                using (var outputStream = new MemoryStream())
                {
                    var reportBuilder =
                        _reportBuilderFactory.Create <InvoiceDetail>(template)
                        // 単一項目のSetterを設定
                        .AddSetter("$SalesOrderId", cell => cell.Value = invoice.SalesOrderId)
                        .AddSetter("$OrderDate", cell => cell.Value    = invoice.OrderDate)
                        .AddSetter("$CompanyName", cell => cell.Value  = invoice.CompanyName)
                        .AddSetter("$Name", cell => cell.Value         = invoice.Name)
                        .AddSetter("$Address", cell => cell.Value      = invoice.Address)
                        .AddSetter("$PostalCode", cell => cell.Value   = invoice.PostalCode)
                        // テーブルのセルに対するSetterを設定
                        .AddTableSetter("$ProductName", (cell, detail) => cell.Value   = detail.ProductName)
                        .AddTableSetter("$UnitPrice", (cell, detail) => cell.Value     = detail.UnitPrice)
                        .AddTableSetter("$OrderQuantity", (cell, detail) => cell.Value = detail.OrderQuantity);
                    reportBuilder.Build(invoice.InvoiceDetails, outputStream, SaveFileFormat.Pdf);
                    return(outputStream.ToArray());
                }
        }
コード例 #3
0
        protected override void ExecuteStage(PostProcessingBundle bundle)
        {
            var fpAnnotation =
                bundle.IssueVulnerabilityLinks
                .Select(x => x.IssueAnnotation)
                .Concat(bundle.RemainingIssues)
                .Where(x => x.State == IssueAnnotationState.FalsePositive)
                .ToArray();

            var fixedAnnotation = bundle.RemainingIssues
                                  .Concat(bundle.Changes.Where(x => x.Type == FileChangeAnnotationType.Update).Select(x => x.Annotation))
                                  .Where(x => x.State == IssueAnnotationState.Fixed)
                                  .ToArray();

            var todoVulnerabilities   = bundle.Changes.Where(x => x.Annotation.State == IssueAnnotationState.Todo).ToArray();
            var reopenVulnerabilities = bundle.Changes.Where(x => x.Annotation.State == IssueAnnotationState.Reopen).ToArray();

            var groups =
                fpAnnotation.Select(x => new { Type = x.LongName, IssueId = x.Id })
                .Concat(
                    fixedAnnotation.Select(
                        x => new
            {
                Type    = x.LongName,
                IssueId = x.Id
            }))
                .Concat(
                    todoVulnerabilities.Concat(reopenVulnerabilities)
                    .Select(x => new { Type = x.Annotation.LongName, IssueId = x.Annotation.Id }))
                .Distinct()
                .ToArray();

            foreach (var group in groups)
            {
                var branchName = _branchNameBuilder.Build(new BranchNameBuilderInfo {
                    Type = group.Type
                });

                var template = _templateProvider.Get(TemplateNames.IssueBody);

                var fp = fpAnnotation.Where(x => x.LongName == group.Type).GroupBy(
                    x => new
                {
                    x.File,
                    x.LineStart
                }).Select(x => x.First()).ToArray();

                var fixedItems = fixedAnnotation.Where(x => x.LongName == group.Type).GroupBy(
                    x => new
                {
                    x.File,
                    x.LineStart
                }).Select(x => x.First()).ToArray();

                var todoItems = todoVulnerabilities
                                .Where(x => x.Annotation.LongName == group.Type)
                                .GroupBy(
                    x => new
                {
                    x.Vulnerability.File,
                    x.Vulnerability.NumberLine
                }).Select(x => x.First()).ToArray();

                var reopenItems = reopenVulnerabilities
                                  .Where(x => x.Annotation.LongName == group.Type)
                                  .GroupBy(
                    x => new
                {
                    x.Vulnerability.File,
                    x.Vulnerability.NumberLine
                }).Select(x => x.First()).ToArray();

                template.Body.Add(
                    new Dictionary <string, object>
                {
                    {
                        "FP", fp
                    },
                    {
                        "Fixed", fixedItems
                    },
                    {
                        "Todo", todoItems
                    },
                    {
                        "Reopen", reopenItems
                    },

                    // TODO: remove code block cause incorrect read out strongly typed GitHub settings
                    //{
                    //	"RepoOwner", settings[GitHubItSettingKeys.RepositoryOwner.ToString()]
                    //},
                    //{
                    //	"RepoName", settings[GitHubItSettingKeys.RepositoryName.ToString()]
                    //},
                    {
                        "RepoBranch", branchName
                    },
                    {
                        "TotalCount", fp.Length + fixedItems.Length + todoItems.Length + reopenItems.Length
                    }
                });

                var body = template.Body.Render();

                var issue = bundle.Issues.FirstOrDefault(x => x.Id == group.IssueId) ??
                            bundle.IssueTrackerPlugin.GetIssue(group.IssueId);

                var title = _issueNameBuilder.Build(
                    new IssueNameBuilderInfo
                {
                    IssueTypeName = group.Type
                });

                if (fp.Any() || fixedItems.Any() || todoItems.Any() || reopenItems.Any())
                {
                    title += Resources.IssueNameLeft.FormatWith(todoItems.Length + reopenItems.Length);
                }

                using (var telemetryScope = _telemetryScopeProvider.Create <ItPluginInfo>(TelemetryOperationNames.ItPlugin.Update))
                {
                    try
                    {
                        telemetryScope.SetEntity(
                            new ItPluginInfo
                        {
                            Plugins = bundle.Task.Projects.Plugins,
                            TaskId  = bundle.Task.Id
                        });

                        bundle.IssueTrackerPlugin.UpdateIssue(
                            new UpdateIssueRequest
                        {
                            Id          = issue.Id,
                            Title       = title,
                            Description = body,
                            Status      =
                                todoVulnerabilities.Concat(reopenVulnerabilities).Any(x => x.Annotation.LongName == group.Type)
                                                                                        ? IssueStatus.Open
                                                                                        : IssueStatus.Closed
                        });

                        telemetryScope.WriteSuccess();
                    }
                    catch (Exception ex)
                    {
                        telemetryScope.WriteException(ex);

                        throw;
                    }
                }
            }
        }
コード例 #4
0
        protected override void ExecuteStage(PostProcessingBundle bundle)
        {
            var branches = bundle.VersionControlPlugin.GetBranches().ToList();

            var mainBranch = branches.First(x => x.Name == bundle.Task.Repository);

            var annotationGroups = bundle.Changes
                                   .Where(x => x.Type != FileChangeAnnotationType.None)
                                   .GroupBy(x => x.Annotation.LongName);

            foreach (var typeGroup in annotationGroups)
            {
                var branchName = _branchNameBuilder.Build(new BranchNameBuilderInfo {
                    Type = typeGroup.Key
                });

                var branch = branches.FirstOrDefault(
                    x => string.Equals(
                        x.Name,
                        branchName,
                        StringComparison.CurrentCultureIgnoreCase));

                if (branch == null)
                {
                    using (
                        var telemetryScope = _telemetryScopeProvider.Create <VcsPluginInfo>(TelemetryOperationNames.VcsPlugin.CreateBranch)
                        )
                    {
                        try
                        {
                            telemetryScope.SetEntity(
                                new VcsPluginInfo
                            {
                                Plugin            = bundle.Task.Projects.Plugins1,                              // VCS plugin =)
                                CreatedBranchName = branchName,
                                TaskId            = bundle.Task.Id
                            });

                            branch = bundle.VersionControlPlugin.CreateBranch(bundle.Task.FolderPath, branchName, mainBranch.Id);

                            telemetryScope.WriteSuccess();
                        }
                        catch (Exception ex)
                        {
                            telemetryScope.WriteException(ex);

                            throw;
                        }
                    }

                    branches.Add(branch);
                }

                foreach (var fileGroup in typeGroup.GroupBy(x => x.Annotation.File))
                {
                    var content = File.ReadAllText(Path.Combine(bundle.Task.FolderPath, fileGroup.Key));

                    var ending = content.GetLineSplitter();

                    var linesContent = content.Split(new[] { ending }, StringSplitOptions.None).ToList();

                    var rowShift = 0;

                    foreach (var fileUpdate in fileGroup.OrderBy(x => x.Annotation.LineStart))
                    {
                        var removeCount = 0;

                        if (fileUpdate.Type == FileChangeAnnotationType.Update)
                        {
                            removeCount = fileUpdate.Annotation.LineEnd - fileUpdate.Annotation.LineStart + 1;

                            for (var index = 0; index < removeCount; index++)
                            {
                                linesContent.RemoveAt(fileUpdate.Annotation.LineStart + rowShift - 1);
                            }
                        }

                        var serializedIssueAnnotation = _issueAnnotationSerializer.Serialize(fileUpdate.Annotation);

                        var annotation = _issueAnnotationFormatter.Format(serializedIssueAnnotation);

                        var lines = annotation.Split('\n');

                        var rawLine        = linesContent[fileUpdate.Annotation.LineStart + rowShift - 1];
                        var startLineShift = rawLine.Substring(0, rawLine.Length - rawLine.TrimStart(' ', '\t').Length);

                        for (var index = 0; index < lines.Length; index++)
                        {
                            linesContent.Insert(
                                fileUpdate.Annotation.LineStart + rowShift + index - 1,
                                startLineShift + lines[index].Trim());
                        }

                        rowShift = rowShift - removeCount + lines.Length;
                        if (fileUpdate.Vulnerability != null)
                        {
                            fileUpdate.Vulnerability.NumberLine = fileUpdate.Annotation.LineStart + rowShift;
                        }
                    }

                    var memoryStream = new MemoryStream();
                    var streamWriter = new StreamWriter(memoryStream);

                    streamWriter.Write(string.Join(ending, linesContent));

                    streamWriter.Flush();
                    streamWriter.Close();

                    var commitTemplate = _templateProvider.Get(TemplateNames.CommitName);

                    commitTemplate.Body.Add(
                        new Dictionary <string, object>
                    {
                        { "Group", _vulnerabilityShortTypeResolver.Resolve(typeGroup.Key) },
                        { "File", Path.GetFileName(fileGroup.Key) }
                    });

                    var bodyCommit = commitTemplate.Body.Render();

                    _log.Debug($"Commit to {branch.Id} {fileGroup.Key}");

                    var fileContent = memoryStream.ToArray();

                    using (var telemetryScope = _telemetryScopeProvider.Create <VcsPluginInfo>(TelemetryOperationNames.VcsPlugin.Commit))
                    {
                        try
                        {
                            telemetryScope.SetEntity(
                                new VcsPluginInfo
                            {
                                Plugin = bundle.Task.Projects.Plugins1,                                         // VCS plugin
                                CommittedSourcesSize = fileContent.Length,
                                TaskId = bundle.Task.Id
                            });

                            bundle.VersionControlPlugin.Commit(
                                bundle.Task.FolderPath,
                                branch.Id,
                                bodyCommit,
                                fileGroup.Key,
                                fileContent);

                            telemetryScope.WriteSuccess();
                        }
                        catch (Exception ex)
                        {
                            telemetryScope.WriteException(ex);

                            throw;
                        }
                    }
                }
            }

            bundle.VersionControlPlugin.CleanUp(bundle.Task.FolderPath);
        }