/// <summary> /// Creates a report formatter. /// </summary> /// <param name="htmlReportFormatter">The HTML report formatter.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="htmlReportFormatter"/> is null.</exception> public MHtmlReportFormatter(IReportFormatter htmlReportFormatter) { if (htmlReportFormatter == null) throw new ArgumentNullException("htmlReportFormatter"); this.htmlReportFormatter = htmlReportFormatter; }
/// <inheritdoc /> public void Format(IReportWriter reportWriter, string formatterName, ReportFormatterOptions formatterOptions, IProgressMonitor progressMonitor) { if (reportWriter == null) { throw new ArgumentNullException(@"reportWriter"); } if (formatterName == null) { throw new ArgumentNullException(@"formatterName"); } if (formatterOptions == null) { throw new ArgumentNullException(@"formatterOptions"); } if (progressMonitor == null) { throw new ArgumentNullException(@"progressMonitor"); } IReportFormatter formatter = GetReportFormatter(formatterName); if (formatter == null) { throw new InvalidOperationException(String.Format("There is no report formatter named '{0}'.", formatterName)); } formatter.Format(reportWriter, formatterOptions, progressMonitor); }
// Method Injection: передача обязательных зависимостей метода public void SendReport(Report report, IReportFormatter formatter) { Logger.Info("Sending report..."); var formattedReport = formatter.Format(report); _reportSender.SendReport(formattedReport); Logger.Info("Report has been sent"); }
public HomeController(IUnitOfWork uow, IReportFormatter reportFormatter, IReportGenerator reportGenerator, IPersonTimeManager personTimeManager) { _uow = uow; _reportFormatter = reportFormatter; _reportGenerator = reportGenerator; _personTimeManager = personTimeManager; _dataMapper = new ViewDataMapper(); }
/// <summary> /// Creates a report formatter. /// </summary> /// <param name="htmlReportFormatter">The HTML report formatter.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="htmlReportFormatter"/> is null.</exception> public MHtmlReportFormatter(IReportFormatter htmlReportFormatter) { if (htmlReportFormatter == null) { throw new ArgumentNullException("htmlReportFormatter"); } this.htmlReportFormatter = htmlReportFormatter; }
public void GetFormatterTest(IDictionary <string, IReportFormatter> formatterStorage, string formatterName, IReportFormatter expected) { // Arrange var manager = new FormatterManager(formatterStorage); // Act IReportFormatter formatter = manager.GetFormatter(formatterName); // Assert Assert.That(formatter, Is.EqualTo(expected)); }
/// <summary> /// Рисует строку подведения итогов. Это может быть как строка с общими итогами, так и с промежуточными /// </summary> /// <remarks>Переопределяем стандартный метод</remarks> protected override void WriteTotalRow(tablelayoutClass LayoutProfile, Croc.XmlFramework.ReportService.Layouts.ReportLayoutData LayoutData, Croc.XmlFramework.ReportService.Layouts.TableLayout.LayoutColumns Columns, int CurrentRowNum, int CurrentColumnNum, bool SubTotals, DataTable oTable, int[] ColumnsRowspan, int nGroupedCellsCount, DataRow PreviousRow) { // вызываем базовый метод, но передаем ему столбцы для накопления итогов // только по помеченным строкам base.WriteTotalRow(LayoutProfile, LayoutData, TotalColumns, CurrentRowNum, CurrentColumnNum, SubTotals, oTable, ColumnsRowspan, nGroupedCellsCount, PreviousRow); // если выводим общие итоги, то больше ничего делать не надо if (!SubTotals) { return; } // получаем объект, с которым работают форматтеры и эвалуаторы ReportFormatterData FormatterData = new ReportFormatterData(LayoutData, ((int)PreviousRow["Expected"] - (int)PreviousRow["TotalSpent"]).ToString(), null, PreviousRow, -1, -1); durationevaluatorClass FormatterNode = new durationevaluatorClass(); FormatterNode.workdayDuration = "{#WorkdayDuration}"; FormatterNode.format = "{@TimeMeasureUnits}"; // просим объект у фабрики IReportFormatter Formatter = (IReportFormatter)ReportObjectFactory.GetInstance(FormatterNode.GetAssembly(), FormatterNode.GetClass()); // делаем что-то Formatter.Execute(FormatterNode, FormatterData); // далее добавляем строку для вывода дисбаланса по сотруднику LayoutTable.AddRow(); LayoutTable.CurrentRow.AddCell("<fo:block text-align='right'>Дисбаланс по сотруднику:</fo:block>", "string", 1, 3, "SUBTOTAL"); LayoutTable.CurrentRow.CurrentCell.StartsColumnspanedCells = true; LayoutTable.CurrentRow.CurrentCell.IsAggregated = true; LayoutTable.CurrentRow.AddCell(null, null, 1, 1); LayoutTable.CurrentRow.CurrentCell.IsFakeCell = true; LayoutTable.CurrentRow.CurrentCell.IsAggregated = true; LayoutTable.CurrentRow.AddCell(null, null, 1, 1); LayoutTable.CurrentRow.CurrentCell.IsFakeCell = true; LayoutTable.CurrentRow.CurrentCell.IsAggregated = true; LayoutTable.CurrentRow.AddCell(FormatterData.CurrentValue, "string", 1, 2, "SUBTOTAL"); LayoutTable.CurrentRow.CurrentCell.StartsColumnspanedCells = true; LayoutTable.CurrentRow.CurrentCell.IsAggregated = true; LayoutTable.CurrentRow.AddCell(null, null, 1, 1); LayoutTable.CurrentRow.CurrentCell.IsFakeCell = true; LayoutTable.CurrentRow.CurrentCell.IsAggregated = true; }
public void RegisterFormatterTest_ThrowsException(IDictionary <string, IReportFormatter> storage, string name, IReportFormatter formatter, Type expectedException) { // Arrange var manager = new FormatterManager(storage); // Act void TestAction() => manager.RegisterFormatter(name, formatter); // Assert Assert.That(TestAction, Throws.TypeOf(expectedException)); }
public void RegisterFormatterTest(string name, IReportFormatter formatter) { // Arrange Mock <IDictionary <string, IReportFormatter> > dictionaryMock = new(); dictionaryMock.Setup(formatters => formatters.Add(name, formatter)).Verifiable(); FormatterManager manager = new(dictionaryMock.Object); // Act manager.RegisterFormatter(name, formatter); // Assert dictionaryMock.Verify(); }
private void Load(string reportPath, IReportFormatter formatter, string configurationPath) { var formatterResult = formatter.Load(reportPath); var configuration = XDocument.Load(configurationPath); _report = new XDocument( new XElement( "dbGhost", new XAttribute("errors", formatterResult.HasErrors), formatterResult.Report.Elements(), configuration.Elements())); _hasErrors = formatterResult.HasErrors; }
private void Load(string reportPath, IReportFormatter formatter, string configurationPath) { FormatterResult formatterResult = formatter.Load(reportPath); XDocument xDocument = XDocument.Load(configurationPath); _report = new XDocument(new object[] { new XElement("dbGhost", new object[] { new XAttribute("errors", formatterResult.HasErrors), formatterResult.Report.Elements(), xDocument.Elements() }) }); _hasErrors = formatterResult.HasErrors; }
private void Load(string reportPath, IReportFormatter formatter, string configurationPath) { FormatterResult formatterResult = formatter.Load(reportPath); XDocument xDocument = XDocument.Load(configurationPath); _report = new XDocument(new object[] { new XElement("dbGhost", new object[] { new XAttribute("errors", formatterResult.HasErrors), formatterResult.Report.Elements(), xDocument.Elements() }) }); _hasErrors = formatterResult.HasErrors; }
private bool ValidateReportFormats(IReportManager reportManager, TestProject consolidatedTestProject) { foreach (string reportFormat in reportFormats) { IReportFormatter formatter = reportManager.GetReportFormatter(reportFormat); if (formatter != null) { continue; } logger.Log(LogSeverity.Error, String.Format("Unrecognized report format: '{0}'.", reportFormat)); return(false); } if (consolidatedTestProject.ReportNameFormat.Length == 0) { logger.Log(LogSeverity.Error, "Report name format must not be empty."); return(false); } return(true); }
/// <summary> /// Saves a new instance of <see cref="IReportFormatter"/> with specified name. /// </summary> /// <param name="name">Formatter name.</param> /// <param name="formatter">Formatter instance.</param> /// <exception cref="ArgumentNullException"><see cref="name"/> or <see cref="formatter"/> is null.</exception> /// <exception cref="RegistrationNotSupportedException">Internal formatter container is read-only.</exception> /// <exception cref="DuplicatedFormatterException">Formatter with specified name does already exist.</exception> public void RegisterFormatter(string name, IReportFormatter formatter) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (formatter == null) { throw new ArgumentNullException(nameof(formatter)); } try { _formatterStorage.Add(name, formatter); } catch (NotSupportedException e) { throw new RegistrationNotSupportedException("The storage does not support registering new formatters.", e); } catch (ArgumentException e) { throw new DuplicatedFormatterException("Formatter with such name is already registered.", e); } }
public ReportGenerator(EmployeeDB edb) { _employeeReport = new Report(edb); _currentFormatter = new AgeFirstFormatter(); _currentPrinter = new ConsolePrinter(); }
/// <summary> /// Constructor allowing to create ReportFileWriter with associated result formatter and output path. /// Please note that full output path is being resolved at time when constructor is called, not when results are saved, so any relative paths will be resolved at the construction of this class. /// </summary> /// <param name="formatter">Report formatter.</param> /// <param name="outputPath">Output path. If starts with <c>~</c>, it would be resolved to <c>AppContext.BaseDirectory</c>. It can contain string.Format() like parameters of {name:format} syntax. /// This constructor uses default <see cref="ReportPathFormatter"/> to format these parameters. See <see cref="ReportPathFormatter.CreateDefault"/>() for more details on available parameter types.</param> public ReportFileWriter(IReportFormatter formatter, string outputPath) : this(formatter, outputPath, ReportPathFormatter.CreateDefault()) { }
public FileReporter(string path, Encoding encoding, IReportFormatter formatter) : base(new StreamWriter(new FileStream(path, FileMode.Append), encoding), formatter) { }
// Закомментил старое /*protected override void WriteColumns(tablelayoutClass LayoutProfile, XslFOProfileWriter RepGen, DataTable oTable, LayoutColumns Columns, ReportParams Params, object CustomData, IDictionary Vars) * { * base.WriteColumns(LayoutProfile, RepGen, oTable, Columns, Params, CustomData, Vars); * * // создаем копию существующих столбцов * // для накопления общих итогов только по помеченным строкам * m_TotalColumns = cloneLayoutColumns(Columns); * } */ /// <summary> /// Вычисляет данные ячейки таблицы лэйаута /// </summary> /// <remarks>Переопределяем стандартный метод</remarks> protected override ReportFormatterData CalculateCellValue(ReportLayoutData LayoutData, TableLayout.LayoutColumns Columns, int RowNum, int ColumnNum, DataRow CurrentRow, int RowSpan) { // значение в ячейке object CurrentValue = null; // получаем объект, с которым работают форматтеры и эвалуаторы ReportFormatterData FormatterData = new ReportFormatterData( LayoutData, CurrentValue, null, CurrentRow, RowNum, ColumnNum); if (string.Empty == Columns[ColumnNum].RSFileldName) // если текущее значение не соответсвует никакой колонке рекордсета { if (Columns[ColumnNum].ColumnIsCounter) // если колонка - счетчик { // текущее значение счетчика CurrentValue = Columns[ColumnNum].CounterCurrent.ToString(); // инкрементируем счетчик Columns[ColumnNum].IncrementCounter(); } else // null иначе { CurrentValue = null; } } else // значение { CurrentValue = new Croc.XmlFramework.ReportService.Utility.MacroProcessor(FormatterData).Process(Columns[ColumnNum].RSFileldName); } // Encoding if (Columns[ColumnNum].Encoding == encodingtype.text) { CurrentValue = System.Web.HttpUtility.HtmlEncode(CurrentValue.ToString()); } FormatterData.CurrentValue = CurrentValue; // проходим по эвалуаторам и форматтерам if (Columns[ColumnNum].Formatters != null) { foreach (abstractformatterClass FormatterNode in Columns[ColumnNum].Formatters) { if (!FormatterNode.useSpecified || FormatterNode.use != usetype.totalcell) { // просим объект у фабрики IReportFormatter Formatter = (IReportFormatter)ReportObjectFactory.GetInstance(FormatterNode.GetAssembly(), FormatterNode.GetClass()); // делаем что-то Formatter.Execute(FormatterNode, FormatterData); } } } if (string.Empty != Columns[ColumnNum].AggregationFunction) { Columns[ColumnNum].UpdateTotals(CurrentValue); // проапдейтим итоги по помеченным строкам bool bNoTotals; try { // берем из строки рекорсета столбец NoTotals bNoTotals = Convert.ToBoolean(CurrentRow[NOTOTALS_COLUMN_NAME]); } catch (Exception) { // если, что-то пошло не так, считаем, что нужно // пересчитывать итоги (как обычно) bNoTotals = false; } // пересчитаем итоги, если нужно if (!bNoTotals) { TotalColumns[ColumnNum].UpdateTotals(CurrentValue); } } if (FormatterData.ClassName == null || FormatterData.ClassName == string.Empty) { FormatterData.ClassName = Columns[ColumnNum].CellCssClass; } return(FormatterData); }
public FileReporter(string path, Encoding encoding, IReportFormatter formatter) : base(new StreamWriter(path, true, encoding), formatter) { }
public Log4NetReporter(IReportFormatter formatter) : base(formatter) { }
public SampledFileReporter(string directory, Encoding encoding, IReportFormatter formatter) : base (null, formatter) { _directory = directory; _encoding = encoding; }
public ConsoleReporter(IReportFormatter formatter) : base(Console.Out, formatter) { }
public SampledFileReporter(string directory, Encoding encoding, IReportFormatter formatter, IDateTimeOffsetProvider dateTimeOffsetProvider) : base(null, formatter) { _directory = directory; _encoding = encoding; _dateTimeOffsetProvider = dateTimeOffsetProvider; }
public SampledFileReporter(string directory, IReportFormatter formatter, IDateTimeOffsetProvider dateTimeOffsetProvider = null) : this(directory, Encoding.UTF8, formatter, dateTimeOffsetProvider) { }
public SampledFileReporter(IReportFormatter formatter, IDateTimeOffsetProvider dateTimeOffsetProvider = null) : this("", Encoding.UTF8, formatter, dateTimeOffsetProvider) { }
public LaserReportPrinter(IReportFormatter reportFormatter, IReportDataAccess dataAccess) { _reportFormatter = reportFormatter; _dataAccess = dataAccess; }
public SampledFileReporter(IReportFormatter formatter) : this("", Encoding.UTF8, formatter) { }
public SampledFileReporter(string directory, IReportFormatter formatter) : this(directory, Encoding.UTF8, formatter) { }
public ZipReportWrapper(IReportFormatter reportFormatter) { _reportFormatter = reportFormatter; }
public FileReporter(string path, Encoding encoding, IReportFormatter formatter) : base(new StreamWriter(path, true, encoding), formatter) { }
public Report(IDataAccess dataAccess, IReportFormatter formatter, IMediaGenerator generator) { _dataAccess = dataAccess; _formatter = formatter; _generator = generator; }
public Log4NetReporter(TextWriter writer, IReportFormatter formatter) : base(writer, formatter) { }
public Report(string reportPath, IReportFormatter formatter, string configurationPath) { Load(reportPath, formatter, configurationPath); }
/// <summary> /// Initializes a new instance of the <see cref="ReportsSaver{TFormat}"/> class. /// </summary> /// <param name="formatter">Desired report formatter to read reports.</param> /// <param name="storage">Desired storage to save reports data.</param> public ReportsSaver(IReportFormatter <TFormat> formatter, IReportStorage <TFormat> storage) { _formatter = formatter; _storage = storage; }
public ReportMaker(IEmployeeFillingData employeeFillingService, IReportFormatter reportFormatter) { builder = new StringBuilder(); formatter = reportFormatter; employeeWithDataService = employeeFillingService; }
public MetricsListener(IReportFormatter formatter = null) { _formatter = formatter ?? new JsonReportFormatter(); }
public Report(string reportPath, IReportFormatter formatter, string configurationPath) { Load(reportPath, formatter, configurationPath); }
public ConsoleReporter(IReportFormatter formatter) : base(Console.Out, formatter) { }
public Report(IDataAccess dataAccess, IReportFormatter formatter, IPrinter printer) { this._dataAccess = dataAccess; this._formatter = formatter; this._printer = printer; }
/// <summary> /// Constructor allowing to create ReportFileWriter with associated result formatter, output path and path formatter. /// Please note that full output path is being resolved at time when constructor is called, not when results are saved, so any relative paths will be resolved at the construction of this class. /// </summary> /// <param name="formatter">Report formatter.</param> /// <param name="outputPath">Output path. If starts with <c>~</c>, it would be resolved to <c>AppContext.BaseDirectory</c>. It can contain string.Format() like parameters of {name:format} syntax.</param> /// <param name="pathFormatter"><see cref="ReportPathFormatter"/> instance used to format <paramref name="outputPath"/>.</param> public ReportFileWriter(IReportFormatter formatter, string outputPath, ReportPathFormatter pathFormatter) { OutputPath = outputPath; _path = pathFormatter.ToFormattablePath(outputPath); Formatter = formatter; }
public void FormatWritesTheArchivedReport() { IReportWriter reportWriter = Mocks.StrictMock <IReportWriter>(); IReportContainer reportContainer = Mocks.StrictMock <IReportContainer>(); IReportFormatter htmlReportFormatter = Mocks.StrictMock <IReportFormatter>(); IProgressMonitor progressMonitor = NullProgressMonitor.CreateInstance(); var reportFormatterOptions = new ReportFormatterOptions(); string reportPath = SpecialPathPolicy.For <MHtmlReportFormatterTest>().CreateTempFileWithUniqueName().FullName; using (Stream tempFileStream = File.OpenWrite(reportPath)) { using (Mocks.Record()) { SetupResult.For(reportWriter.ReportContainer).Return(reportContainer); SetupResult.For(reportWriter.Report).Return(new Report()); Expect.Call(reportContainer.EncodeFileName(null)) .Repeat.Any() .IgnoreArguments() .Do((Gallio.Common.GallioFunc <string, string>) delegate(string value) { return(value); }); SetupResult.For(reportContainer.ReportName).Return("Foo"); Expect.Call(reportContainer.OpenWrite("Foo.mht", MimeTypes.MHtml, new UTF8Encoding(false))) .Return(tempFileStream); reportWriter.AddReportDocumentPath("Foo.mht"); Expect.Call(delegate { htmlReportFormatter.Format(null, null, null); }) .Constraints(Is.NotNull(), Is.Same(reportFormatterOptions), Is.NotNull()) .Do((FormatDelegate) delegate(IReportWriter innerReportWriter, ReportFormatterOptions innerFormatterOptions, IProgressMonitor innerProgressMonitor) { using (StreamWriter contentWriter = new StreamWriter(innerReportWriter.ReportContainer.OpenWrite("Foo.html", MimeTypes.Html, Encoding.UTF8))) contentWriter.Write("<html><body>Some HTML</body></html>"); using (StreamWriter contentWriter = new StreamWriter(innerReportWriter.ReportContainer.OpenWrite( innerReportWriter.ReportContainer.EncodeFileName("Foo\\Attachment 1%.txt"), MimeTypes.PlainText, Encoding.UTF8))) contentWriter.Write("An attachment."); using (StreamWriter contentWriter = new StreamWriter(innerReportWriter.ReportContainer.OpenWrite("Foo.css", null, null))) contentWriter.Write("#Some CSS."); }); } using (Mocks.Playback()) { MHtmlReportFormatter formatter = new MHtmlReportFormatter(htmlReportFormatter); formatter.Format(reportWriter, reportFormatterOptions, progressMonitor); string reportContents = File.ReadAllText(reportPath); TestLog.AttachPlainText("MHTML Report", reportContents); Assert.Contains(reportContents, "MIME-Version: 1.0"); Assert.Contains(reportContents, "Content-Type: multipart/related; type=\"text/html\"; boundary="); Assert.Contains(reportContents, "This is a multi-part message in MIME format."); Assert.Contains(reportContents, "text/html"); Assert.Contains(reportContents, "Content-Location: file:///Foo.html"); Assert.Contains(reportContents, Convert.ToBase64String(Encoding.UTF8.GetBytes("<html><body>Some HTML</body></html>"), Base64FormattingOptions.InsertLineBreaks)); Assert.Contains(reportContents, "text/plain"); Assert.Contains(reportContents, "Content-Location: file:///Foo/Attachment_1%25.txt"); Assert.Contains(reportContents, Convert.ToBase64String(Encoding.UTF8.GetBytes("An attachment."), Base64FormattingOptions.InsertLineBreaks)); Assert.Contains(reportContents, "text/css"); Assert.Contains(reportContents, "Content-Location: file:///Foo.css"); Assert.Contains(reportContents, Convert.ToBase64String(Encoding.UTF8.GetBytes("#Some CSS."), Base64FormattingOptions.InsertLineBreaks)); File.Delete(reportPath); } } }
protected ReporterBase(TextWriter writer, IReportFormatter formatter) { Out = writer; _formatter = formatter; }
protected ReporterBase(IReportFormatter formatter) { Formatter = formatter; }
public SampledFileReporter(string directory, IReportFormatter formatter) : this(directory, Encoding.UTF8, formatter) { }
public SampledFileReporter(string directory, Encoding encoding, IReportFormatter formatter) : base(null, formatter) { _directory = directory; _encoding = encoding; }
public SampledFileReporter(IReportFormatter formatter) : this("", Encoding.UTF8, formatter) { }
public void SetUp() { _subject = new PlainTextReportFormatter(); }
protected ReporterBase(TextWriter writer, IReportFormatter formatter) { Out = writer; Formatter = formatter; }
public void SetUp() { _subject = new HtmlReportFormatter(); }
public ReportGenerator(EmployeeDB edb) { _employeeReport = new Report(edb); _currentFormatter = new AgeFirstFormatter(); _currentPrinter = new ConsolePrinter(); }