protected override Task ExecAsync(CFTFileContext context) { try { using (var readStream = new MemoryStream(context.OutputFile.FileContent)) { using (var xmlReader = XmlReader.Create(readStream)) { using (var writeStream = new MemoryStream()) { using (var xmlWriter = XmlWriter.Create( writeStream, new XmlWriterSettings() { // Что бы не было BOM. Encoding = new UTF8Encoding() })) { _transform.Transform(xmlReader, xmlWriter); context.OutputFile.FileContent = writeStream.ToArray(); } } } } } catch (Exception e) { throw new CFTApplicationException("Что-то пошло не так во время XSLT-преобразования файла.", e); } return(Task.CompletedTask); }
protected override Task ExecAsync(CFTFileContext context) { var exportFile = GetFileInfo(context); if (exportFile.Exists) { throw new Exception("Файл существует."); } using (var wStream = exportFile.CreateWriteStream()) { using (var bwStream = new BinaryWriter(wStream)) { bwStream.Write(GetFileContent(context)); } } if (!exportFile.Exists) { throw new Exception("Ошибка при создании файла."); } if (_option.FileType == ExportFileType.Output) { context.OutputFile.FullName = exportFile.PhysicalPath; } return(Task.CompletedTask); }
protected override Task NextExceptionExecAsync(Exception e, CFTFileContext context) { var filePath = Path.Combine(_backupPath, context.InputFile.FileName); if (File.Exists(filePath)) { File.Delete(filePath); } return(Task.CompletedTask); }
public async Task InvokeAsync(CFTFileContext context) { try { _logger.LogInformation(_startMessage); await _next.Invoke(context); _logger.LogInformation(_endSuccessMessage); } catch (Exception e) { _logger.LogError(e, _endErrorMessage); } }
protected override Task ExecAsync(CFTFileContext context) { if (!Directory.Exists(_backupPath)) { Directory.CreateDirectory(_backupPath); } var filePath = Path.Combine(_backupPath, context.InputFile.FileName); if (File.Exists(filePath)) { throw new CFTDublicateFileException($"Файл '{filePath}' уже существует."); } return(File.WriteAllBytesAsync(filePath, context.InputFile.FileContent)); }
private byte[] GetFileContent(CFTFileContext context) { switch (_option.FileType) { case ExportFileType.Input: return(context.InputFile.FileContent); case ExportFileType.Output: return(context.OutputFile.FileContent); case ExportFileType.Exception: return(Encoding.Default.GetBytes(context.Error.ToString())); default: throw new Exception("Не известный тип файла."); } }
protected override Task ExecAsync(CFTFileContext context) { var RemoveFile = GetFileInfo(context); if (!RemoveFile.Exists) { throw new Exception("Файл существует."); } RemoveFile.Delete(); if (RemoveFile.Exists) { throw new Exception("Ошибка при удалении файла."); } return(Task.CompletedTask); }
private ICFTFileInfo GetFileInfo(CFTFileContext context) { string fullName; switch (_option.FileType) { case RemoveFileType.Input: fullName = context.InputFile.FullName; break; case RemoveFileType.Output: fullName = context.OutputFile.FullName; break; default: throw new Exception("Не известный тип файла."); } return(_fileProvider.GetFileInfo(fullName)); }
public async Task InvokeAsync_Success(string xsltFileName) { var testClass = new XSLTransformContentMiddleWare( next: ctx => Task.CompletedTask, logger: _loggerFixture.GetMockLogger <XSLTransformContentMiddleWare>(), options: new XSLTransformContentOptions() { XSLTPath = _xsltFixture.GetFullPath(xsltFileName) }); var context = new CFTFileContext( applicationServices: new ServiceCollection().BuildServiceProvider(), inputFile: _xsltFixture.GetFakeFileInfo()); await testClass.InvokeAsync(context); Encoding.Default.GetString(context.OutputFile.FileContent) .Should() .Be(XSLTFixture.CONTENT_DATA_XML_AFTER_XSLT); }
public async Task InvokeAsync(CFTFileContext context) { using (_logger.BeginScope($"file_name = {context.InputFile.FileName}")) { using (_logger.BeginScope($"full_name = {context.InputFile.FullName}")) { using (_logger.BeginScope($"corelation_id = {Guid.NewGuid()}")) { try { _logger.LogInformation("Начинаем обработку файла."); await _next.Invoke(context); _logger.LogInformation("Файл успешно обработан."); } catch (Exception e) { _logger.LogError(e, "Ошибка обработки файла."); } } } } }
public void InvokeAsync_Success_Namespace_Error() { var next = GetNextDelegate(isThrow: false); var testClass = new ValidateByXSDMiddleWare( next: next, logger: _loggerFixture.GetMockLogger <ValidateByXSDMiddleWare>(), options: new ValidateByXSDOptions() { XSDPath = _xsdFixture.GetFullPath(XSDFixture.FILENAME_XSD_NAMESPACE) }); var context = new CFTFileContext( applicationServices: new ServiceCollection().BuildServiceProvider(), inputFile: _xmlFixture.GetFakeFileInfo(XMLFixture.XMLType.SIMPLE)); Action call = () => testClass.InvokeAsync(context).GetAwaiter().GetResult(); call.Should().Throw <XSDValidationException>(); A.CallTo(() => next.Invoke(A <CFTFileContext> .That.Matches((ctx) => ctx == context))) .MustNotHaveHappened(); }
protected override Task ExecAsync(CFTFileContext context) { List <string> errors = new List <string>(); XmlReaderSettings xmlSettings = new XmlReaderSettings(); xmlSettings.Schemas.Add(_schemas); xmlSettings.ValidationType = ValidationType.Schema; xmlSettings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; xmlSettings.ValidationEventHandler += (o, e) => { errors.Add(e.Message); }; xmlSettings.IgnoreComments = true; xmlSettings.IgnoreWhitespace = true; // отключим проверку DTD т.к она не нужна. // ЕСЛИ ВДРУГ КОГДА-ТО ПОНАДОБИТСЯ... // ТО пробросим в опции эту настройку. xmlSettings.DtdProcessing = DtdProcessing.Ignore; using (var readStream = new MemoryStream(context.OutputFile.FileContent)) { using (var xmlReader = XmlReader.Create(readStream, xmlSettings)) { while (xmlReader.Read()) { } } } if (errors.Count > 0) { throw new XSDValidationException(errors, _option.XSDPath); } return(Task.CompletedTask); }
protected override Task ExecAsync(CFTFileContext context) { try { var allParams = _parameterExtracterBase.Extract((ParameterContext)context); var newFileName = _options.FileMask; foreach (var param in allParams) { if (!newFileName.Contains("@{")) { break; } newFileName = newFileName.Replace($"@{{{param.Key}}}", param.Value); } context.OutputFile.FileName = newFileName; } catch (Exception e) { throw new CFTApplicationException("Ошибка при переименовании файла.", e); } return(Task.CompletedTask); }
private ICFTFileInfo GetFileInfo(CFTFileContext context) { string fileName; switch (_option.FileType) { case ExportFileType.Input: fileName = context.InputFile.FileName; break; case ExportFileType.Exception: fileName = string.Concat(context.InputFile.FileName, "_Error"); break; case ExportFileType.Output: fileName = context.OutputFile.FileName; break; default: throw new Exception("Не известный тип файла."); } return(_fileProvider.GetFileInfo(string.Concat(_option.Path, "\\", fileName))); }
public ParameterContext(CFTFileContext context) { AppContext = context ?? throw new ArgumentNullException(nameof(context)); }
protected override Task NextExceptionExecAsync(Exception e, CFTFileContext context) { return(Task.CompletedTask); }