private static HeaderVersion GetHeaderVersionAndResetScanner(CommentToken comment, ISeekableTokenScanner scanner, bool isLenientParsing, ILog log) { if (comment.Data.IndexOf("PDF-1.", StringComparison.OrdinalIgnoreCase) != 0 && comment.Data.IndexOf("FDF-1.", StringComparison.OrdinalIgnoreCase) != 0) { return(HandleMissingVersion(comment, isLenientParsing, log)); } const int toDecimalStartLength = 4; if (!decimal.TryParse(comment.Data.Substring(toDecimalStartLength), NumberStyles.Number, CultureInfo.InvariantCulture, out var version)) { return(HandleMissingVersion(comment, isLenientParsing, log)); } var atEnd = scanner.CurrentPosition == scanner.Length; var rewind = atEnd ? 1 : 2; var commentOffset = scanner.CurrentPosition - comment.Data.Length - rewind; scanner.Seek(0); var result = new HeaderVersion(version, comment.Data, commentOffset); return(result); }
internal PdfDocument(ILog log, IInputBytes inputBytes, HeaderVersion version, CrossReferenceTable crossReferenceTable, bool isLenientParsing, ParsingCachingProviders cachingProviders, IPageFactory pageFactory, Catalog catalog, DocumentInformation information, EncryptionDictionary encryptionDictionary, IPdfTokenScanner pdfScanner, IFilterProvider filterProvider, AcroFormFactory acroFormFactory) { this.log = log; this.inputBytes = inputBytes; this.version = version ?? throw new ArgumentNullException(nameof(version)); this.isLenientParsing = isLenientParsing; this.cachingProviders = cachingProviders ?? throw new ArgumentNullException(nameof(cachingProviders)); this.encryptionDictionary = encryptionDictionary; this.pdfScanner = pdfScanner ?? throw new ArgumentNullException(nameof(pdfScanner)); this.filterProvider = filterProvider ?? throw new ArgumentNullException(nameof(filterProvider)); Information = information ?? throw new ArgumentNullException(nameof(information)); pages = new Pages(log, catalog, pageFactory, isLenientParsing, pdfScanner); Structure = new Structure(catalog, crossReferenceTable, pdfScanner); documentForm = new Lazy <AcroForm>(() => acroFormFactory.GetAcroForm(catalog)); }
public BitmapHeader(Stream stream) { using (var reader = new BinaryReader(stream, Encoding.Default, true)) { FileSize = reader.ReadInt32(); Reservered = reader.ReadInt32(); DataOffset = reader.ReadInt32(); // Header begins HeaderSize = reader.ReadInt32(); Version = (HeaderVersion)HeaderSize; if (Version != HeaderVersion.BITMAP_INFO_HEADER_SIZE) { throw new Exception("Unsupported header version. Only 40byte headers supported for now."); } Width = reader.ReadInt32(); Height = reader.ReadInt32(); Planes = reader.ReadInt16(); Debug.Assert(Planes == 1); BitCount = reader.ReadInt16(); Compression = (CompressionType)reader.ReadInt32(); ImageSize = reader.ReadInt32(); XPixelsPerM = reader.ReadInt32(); YPixelsPerM = reader.ReadInt32(); ColorsUsed = reader.ReadInt32(); ColorsImportant = reader.ReadInt32(); } }
internal PdfDocument(ILog log, IInputBytes inputBytes, HeaderVersion version, CrossReferenceTable crossReferenceTable, ParsingCachingProviders cachingProviders, IPageFactory pageFactory, Catalog catalog, DocumentInformation information, EncryptionDictionary encryptionDictionary, IPdfTokenScanner pdfScanner, ILookupFilterProvider filterProvider, AcroFormFactory acroFormFactory, BookmarksProvider bookmarksProvider, bool clipPaths) { this.log = log; this.inputBytes = inputBytes; this.version = version ?? throw new ArgumentNullException(nameof(version)); this.cachingProviders = cachingProviders ?? throw new ArgumentNullException(nameof(cachingProviders)); this.encryptionDictionary = encryptionDictionary; this.pdfScanner = pdfScanner ?? throw new ArgumentNullException(nameof(pdfScanner)); this.filterProvider = filterProvider ?? throw new ArgumentNullException(nameof(filterProvider)); this.bookmarksProvider = bookmarksProvider ?? throw new ArgumentNullException(nameof(bookmarksProvider)); this.clipPaths = clipPaths; Information = information ?? throw new ArgumentNullException(nameof(information)); pages = new Pages(catalog, pageFactory, pdfScanner); Structure = new Structure(catalog, crossReferenceTable, pdfScanner); Advanced = new AdvancedPdfDocumentAccess(pdfScanner, filterProvider, catalog); documentForm = new Lazy <AcroForm>(() => acroFormFactory.GetAcroForm(catalog)); }
public HeaderVersion Parse([NotNull] ISeekableTokenScanner scanner, bool isLenientParsing) { if (scanner == null) { throw new ArgumentNullException(nameof(scanner)); } // Read the first token if (!scanner.MoveNext()) { throw new PdfDocumentFormatException($"Could not read the first token in the document at position {scanner.CurrentPosition}."); } var comment = scanner.CurrentToken as CommentToken; var junkSkip = isLenientParsing ? 2 : 0; var attempts = 0; while (comment == null) { if (attempts == junkSkip) { throw new PdfDocumentFormatException("Could not find the version header comment at the start of the document."); } if (!scanner.MoveNext()) { throw new PdfDocumentFormatException("Could not find the version header comment at the start of the document."); } comment = scanner.CurrentToken as CommentToken; attempts++; } var match = VersionRegex.Match(comment.Data); if (!match.Success || !decimal.TryParse(match.Groups["version"].Value, out decimal version)) { if (isLenientParsing) { log.Warn($"Did not find a version header of the correct format, defaulting to 1.4 since lenient. Header was: {comment.Data}."); return(new HeaderVersion(1.4m, "PDF-1.4")); } throw new PdfDocumentFormatException($"The comment which should have provided the version was in the wrong format: {comment.Data}."); } scanner.Seek(0); var result = new HeaderVersion(version, comment.Data); return(result); }
private static bool TryBruteForceVersionLocation(long startPosition, IInputBytes inputBytes, out HeaderVersion headerVersion) { headerVersion = null; inputBytes.Seek(startPosition); // %PDF-x.y or %FDF-x.y const int versionLength = 8; const int bufferLength = 64; // Slide a window of bufferLength bytes across the file allowing for the fact the version could get split by // the window (so always ensure an overlap of versionLength bytes between the end of the previous and start of the next buffer). var buffer = new byte[bufferLength]; var currentOffset = startPosition; int readLength; do { readLength = inputBytes.Read(buffer, bufferLength); var content = OtherEncodings.BytesAsLatin1String(buffer); var pdfIndex = content.IndexOf("%PDF-", StringComparison.OrdinalIgnoreCase); var fdfIndex = content.IndexOf("%FDF-", StringComparison.OrdinalIgnoreCase); var actualIndex = pdfIndex >= 0 ? pdfIndex : fdfIndex; if (actualIndex >= 0 && content.Length - actualIndex >= versionLength) { var numberPart = content.Substring(actualIndex + 5, 3); if (decimal.TryParse( numberPart, NumberStyles.Number, CultureInfo.InvariantCulture, out var version)) { var afterCommentSymbolIndex = actualIndex + 1; headerVersion = new HeaderVersion( version, content.Substring(afterCommentSymbolIndex, versionLength - 1), currentOffset + actualIndex); inputBytes.Seek(startPosition); return(true); } } currentOffset += readLength - versionLength; inputBytes.Seek(currentOffset); } while (readLength == bufferLength); return(false); }
public static HeaderVersion Parse([NotNull] ISeekableTokenScanner scanner, bool isLenientParsing, ILog log) { if (scanner == null) { throw new ArgumentNullException(nameof(scanner)); } // Read the first token if (!scanner.MoveNext()) { throw new PdfDocumentFormatException($"Could not read the first token in the document at position {scanner.CurrentPosition}."); } var comment = scanner.CurrentToken as CommentToken; var junkSkip = isLenientParsing ? 2 : 0; var attempts = 0; while (comment == null) { if (attempts == junkSkip) { throw new PdfDocumentFormatException("Could not find the version header comment at the start of the document."); } if (!scanner.MoveNext()) { throw new PdfDocumentFormatException("Could not find the version header comment at the start of the document."); } comment = scanner.CurrentToken as CommentToken; attempts++; } if (comment.Data.IndexOf("PDF-1.", StringComparison.OrdinalIgnoreCase) != 0 && comment.Data.IndexOf("FDF-1.", StringComparison.OrdinalIgnoreCase) != 0) { return(HandleMissingVersion(comment, isLenientParsing, log)); } const int toDecimalStartLength = 4; if (!decimal.TryParse(comment.Data.Substring(toDecimalStartLength), out var version)) { return(HandleMissingVersion(comment, isLenientParsing, log)); } scanner.Seek(0); var result = new HeaderVersion(version, comment.Data); return(result); }
internal PdfDocument(ILog log, IRandomAccessRead reader, HeaderVersion version, CrossReferenceTable crossReferenceTable, bool isLenientParsing, ParsingCachingProviders cachingProviders, IPageFactory pageFactory, IPdfObjectParser pdfObjectParser, Catalog catalog, DocumentInformation information) { this.log = log; this.reader = reader ?? throw new ArgumentNullException(nameof(reader)); this.version = version ?? throw new ArgumentNullException(nameof(version)); this.crossReferenceTable = crossReferenceTable ?? throw new ArgumentNullException(nameof(crossReferenceTable)); this.isLenientParsing = isLenientParsing; this.cachingProviders = cachingProviders ?? throw new ArgumentNullException(nameof(cachingProviders)); Information = information ?? throw new ArgumentNullException(nameof(information)); Catalog = catalog ?? throw new ArgumentNullException(nameof(catalog)); Pages = new Pages(log, Catalog, pdfObjectParser, pageFactory, reader, isLenientParsing); }
public void Initialise() { this.plugin = new ExcessAndDeductibleDataSetValidationPlugin(); this.componentMetadata = MockRepository.GenerateStub<IComponentMetadata>(); // var headerVersionBuilder = new BusinessComponentBuilder<HeaderVersion>().Build(); // var sdvBuilder = new BusinessComponentBuilder<SectionDetailVersion>().Build(); // var coverageBuilder = new BusinessComponentBuilder<CoverageVersion>().Build(); var hdr = new BusinessComponentBuilder<Header>() .Add(new BusinessComponentBuilder<HeaderVersion>() .SetProperty(a => a.IsLatestVersion = true)) .Add(new BusinessComponentBuilder<Section>() .Add(new BusinessComponentBuilder<SectionVersion>() .SetProperty(a => a.IsLatestVersion = true)) .Add(new BusinessComponentBuilder<SectionDetail>() .Add(new BusinessComponentBuilder<SectionDetailVersion>() .SetProperty(a => a.IsLatestVersion = true)) .Add(new BusinessComponentBuilder<Coverage>() .Add(new BusinessComponentBuilder<CoverageVersion>() .SetProperty(a => a.IsLatestVersion = true))))).Build(); this.componentMetadata = MockRepository.GenerateStub<IComponentMetadata>(); var genericDataTypeVersion = new ProductBuilder<GenericDataTypeVersion>(this.componentMetadata).Build(); genericDataTypeVersion.GenericDataTypeComponent = new GenericDataType { Code = "AND2" }; this.header = hdr; this.headerVersion = this.header.HeaderVersions[0]; this.headerVersion.CreateGenericDataSet(); this.sectionDetailVersion = this.header.Sections[0].SectionDetails[0].SectionDetailVersions[0]; this.sectionDetailVersion.CreateGenericDataSet(); this.coverageVersion = this.header.Sections[0].SectionDetails[0].Coverages[0].CoverageVersions[0]; this.coverageVersion.CreateGenericDataSet(); this.businessTransaction = MockRepository.GenerateStub<IBusinessTransaction>(); this.businessTransaction.Component = hdr; var metadata = MockRepository.GenerateStub<IMetadataQuery>(); metadata.Stub(a => a.GetGenericDataTypeVersion(0, DateTime.Now)).IgnoreArguments().Return(new GenericDataTypeVersion { GenericDataTypeVersionID = 0 }); var container = new UnityContainer(); container.RegisterInstance<IMetadataQuery>(metadata); container.RegisterInstance<IComponentMetadata>(this.componentMetadata); container.RegisterInstance<IMessageService>(new MockMessagingService()); ObjectFactory.Instance = new ObjectFactory(container); }
internal PdfDocument(ILog log, IInputBytes inputBytes, HeaderVersion version, CrossReferenceTable crossReferenceTable, bool isLenientParsing, ParsingCachingProviders cachingProviders, IPageFactory pageFactory, Catalog catalog, DocumentInformation information, IPdfTokenScanner pdfScanner) { this.log = log; this.inputBytes = inputBytes; this.version = version ?? throw new ArgumentNullException(nameof(version)); this.isLenientParsing = isLenientParsing; this.cachingProviders = cachingProviders ?? throw new ArgumentNullException(nameof(cachingProviders)); this.pdfScanner = pdfScanner ?? throw new ArgumentNullException(nameof(pdfScanner)); Information = information ?? throw new ArgumentNullException(nameof(information)); pages = new Pages(log, catalog, pageFactory, isLenientParsing, pdfScanner); Structure = new Structure(catalog, crossReferenceTable, pdfScanner); }
public void Read(Stream stream) { var magic = new byte[MAGIC.Length]; stream.Read(magic); if (!MAGIC.SequenceEqual(magic)) { throw new BadImageFormatException("Magic value is not present for an ELF file"); } EI_CLASS = stream.ReadByteAndParse <HeaderIdentityClass>(HeaderIdentityClass.ELFCLASSNONE); EI_DATA = stream.ReadByteAndParse <HeaderIdentityData>(HeaderIdentityData.ELFDATANONE); EI_VERSION = stream.ReadByteAndParse <HeaderIdentityVersion>(HeaderIdentityVersion.EI_CURRENT); EI_OSABI = stream.ReadByteAndParse <HeaderOsAbiVersion>(HeaderOsAbiVersion.ELFOSABI_NONE); EI_ABIVERSION = (byte)stream.ReadByte(); stream.Seek(16, SeekOrigin.Begin); E_TYPE = stream.ReadHalfWord <HeaderType>(HeaderType.ET_NONE); E_MACHINE = stream.ReadHalfWord <HeaderMachine>(HeaderMachine.EM_NONE); E_VERSION = stream.ReadWord <HeaderVersion>(HeaderVersion.EV_NONE); E_ENTRY = stream.ReadAddress32(); E_PHOFF = stream.ReadOffset32(); E_SHOFF = stream.ReadOffset32(); E_FLAGS = stream.ReadUInt32(); E_EHSIZE = stream.ReadUInt16(); E_PHENTSIZE = stream.ReadUInt16(); E_PHNUM = stream.ReadUInt16(); E_SHENTSIZE = stream.ReadUInt16(); E_SHNUM = stream.ReadUInt16(); E_SHSTRNDX = stream.ReadUInt16(); if (E_EHSIZE != stream.Position && E_EHSIZE != 64) { throw new InvalidOperationException("E_EHSIZE does not equal the current reader position"); } }
public static HeaderVersion Parse([NotNull] ISeekableTokenScanner scanner, bool isLenientParsing, ILog log) { if (scanner == null) { throw new ArgumentNullException(nameof(scanner)); } // Read the first token if (!scanner.MoveNext()) { throw new PdfDocumentFormatException($"Could not read the first token in the document at position {scanner.CurrentPosition}."); } var comment = scanner.CurrentToken as CommentToken; const int junkTokensTolerance = 25; var attempts = 0; while (comment == null) { if (attempts == junkTokensTolerance) { throw new PdfDocumentFormatException("Could not find the version header comment at the start of the document."); } if (!scanner.MoveNext()) { throw new PdfDocumentFormatException("Could not find the version header comment at the start of the document."); } comment = scanner.CurrentToken as CommentToken; attempts++; } if (comment.Data.IndexOf("PDF-1.", StringComparison.OrdinalIgnoreCase) != 0 && comment.Data.IndexOf("FDF-1.", StringComparison.OrdinalIgnoreCase) != 0) { return(HandleMissingVersion(comment, isLenientParsing, log)); } const int toDecimalStartLength = 4; if (!decimal.TryParse(comment.Data.Substring(toDecimalStartLength), NumberStyles.Number, CultureInfo.InvariantCulture, out var version)) { return(HandleMissingVersion(comment, isLenientParsing, log)); } var atEnd = scanner.CurrentPosition == scanner.Length; var rewind = atEnd ? 1 : 2; var commentOffset = scanner.CurrentPosition - comment.Data.Length - rewind; scanner.Seek(0); var result = new HeaderVersion(version, comment.Data, commentOffset); return(result); }
/// <summary> /// Validate the Deductible Sequence /// </summary> /// <param name="processResults">The process results.</param> /// <param name="sourceComponent">The source component.</param> /// <param name="genericDataItems">The generic data items.</param> /// <param name="headerVersion">The header version.</param> private void DeductibleSequenceValidation(ProcessResultsCollection processResults, IBusinessComponent sourceComponent, IEnumerable<IGenericDataItem> genericDataItems, HeaderVersion headerVersion) { // Group by CustomNumeric01 - the Deductible sequence var grouping = genericDataItems.ToLookup(a => a.CustomNumeric01); // Deductible sequence must be different if subtypes match foreach (var group in grouping) { IGenericDataItem prevGroup = null; // Cycle through each entry in the group (of deductibles at a given sequence) foreach (IGenericDataItem entry in group) { // If we've viewed a group previously, compare the subtypes and throw an error if they match if (prevGroup != null) { // CustomCode01 = Division SubSection, CustomCode02 = Vehicle SubSection, CustomCode03 = DeductibleReasonSubSection if (entry.CustomCode01 == prevGroup.CustomCode01 && entry.CustomCode02 == prevGroup.CustomCode02 && entry.CustomCode03 == prevGroup.CustomCode03) { UWBusinessLogicHelper.AddError(processResults, "DeductibleSequenceMustBeDistinct", ProcessInvocationPoint.Validation, sourceComponent); break; } } // Assign this current Item to the 'previousGroup' (previous entry in the group) field. prevGroup = entry; } } // Cycle through all Generic Data Items foreach (IGenericDataItem genericData in genericDataItems) { decimal customNumeric03 = genericData.CustomNumeric03.GetValueOrDefault(0); // CustomNumeric03 is Deductible Policy Sequence number // Check if this is Funded (CustomBoolean03) AND // - the Deductible Type matches the Deductible Service Generic Data Type in the config // OR // - the Deductible Type matches the Deductible Captive Generic Data Type in the config // AND Deductible Policy Sequence number is 0 if (genericData.CustomBoolean03.GetValueOrDefault(false) == true && (genericData.CustomCode04 == ResolveMandatoryConfig(GenericDataType_Deductible_Service) || genericData.CustomCode04 == ResolveMandatoryConfig(GenericDataType_Deductible_Captive)) && customNumeric03 == 0) { // Raise error that the Deductible Policy Sequence must be > 0. string shortDescription = this.GetUWValueSetShortDescription(genericData); UWBusinessLogicHelper.AddError(processResults, UwMessageConstants.DEDUCTIBLE_SEQUENCE_MUST_BE_GREATER_THAN_ZERO, ProcessInvocationPoint.Validation, sourceComponent, shortDescription); } else if (genericData.CustomCode04 == ResolveMandatoryConfig(GenericDataType_Deductible_Client) && customNumeric03 > 0) { // Otherwise, if this is a Client type deductible, and the DEDUCIBLE POLICY sequence is > 0, it should be zero - raise an error. string shortDescription = this.GetUWValueSetShortDescription(genericData); UWBusinessLogicHelper.AddError(processResults, UwMessageConstants.DEDUCTIBLE_POLICY_SEQUENCE_SHOULD_BE_ZERO, ProcessInvocationPoint.Validation, sourceComponent, shortDescription); } // If we have a HeaderVersion if (headerVersion != null) { // Raise error if Deductible Policy Sequence == 1 and no Deductible Policy Reference on the UW Header in Custom Reference 01 // likewise for Deductible Policy Sequence a value of 2 to 5, with no custom reference02 to 05 set. if (customNumeric03 == 1 && string.IsNullOrWhiteSpace(headerVersion.CustomReference01)) { UWBusinessLogicHelper.AddError(processResults, UwMessageConstants.DEDUCTIBLE_POLICY_REFERENCE_SHOULD_NOT_BE_NULL, ProcessInvocationPoint.Validation, sourceComponent, headerVersion.CustomReference01Field.Title); } else if (customNumeric03 == 2 && string.IsNullOrWhiteSpace(headerVersion.CustomReference02)) { UWBusinessLogicHelper.AddError(processResults, UwMessageConstants.DEDUCTIBLE_POLICY_REFERENCE_SHOULD_NOT_BE_NULL, ProcessInvocationPoint.Validation, sourceComponent, headerVersion.CustomReference02Field.Title); } else if (customNumeric03 == 3 && string.IsNullOrWhiteSpace(headerVersion.CustomReference03)) { UWBusinessLogicHelper.AddError(processResults, UwMessageConstants.DEDUCTIBLE_POLICY_REFERENCE_SHOULD_NOT_BE_NULL, ProcessInvocationPoint.Validation, sourceComponent, headerVersion.CustomReference03Field.Title); } else if (customNumeric03 == 4 && string.IsNullOrWhiteSpace(headerVersion.CustomReference04)) { UWBusinessLogicHelper.AddError(processResults, UwMessageConstants.DEDUCTIBLE_POLICY_REFERENCE_SHOULD_NOT_BE_NULL, ProcessInvocationPoint.Validation, sourceComponent, headerVersion.CustomReference04Field.Title); } else if (customNumeric03 == 5 && string.IsNullOrWhiteSpace(headerVersion.CustomReference05)) { UWBusinessLogicHelper.AddError(processResults, UwMessageConstants.DEDUCTIBLE_POLICY_REFERENCE_SHOULD_NOT_BE_NULL, ProcessInvocationPoint.Validation, sourceComponent, headerVersion.CustomReference05Field.Title); } } } }
/// <summary> /// Validates the generic data items and puts data into the ProcessResultsCollection. /// All objects are passed by reference so the ProcessResults collection will return the results /// </summary> /// <param name="processResults">The process results.</param> /// <param name="sourceComponent">The source component.</param> /// <param name="genericDataItems">The generic data items.</param> /// <param name="header">The header.</param> private void ValidateGenericDataItems(ProcessResultsCollection processResults, IBusinessComponent sourceComponent, IEnumerable<IGenericDataItem> genericDataItems, HeaderVersion header) { // Get excess type Data Items then validate var excessDataItems = genericDataItems.Where(a => a.GenericDataTypeCode == ResolveMandatoryConfig("GenericDataType.Excess")); this.CommonGenericDataItemsValidation(processResults, sourceComponent, excessDataItems); // Get deductible data items, then validate var deductibleDataItems = genericDataItems.Where(a => a.GenericDataTypeCode == ResolveMandatoryConfig("GenericDataType.Deductible")); this.CommonGenericDataItemsValidation(processResults, sourceComponent, deductibleDataItems); // Validate deductible sequence this.DeductibleSequenceValidation(processResults, sourceComponent, deductibleDataItems, header); }