/// <summary>
        /// Constructor
        /// </summary>
        public SemanticConstraintRegistry(FileFormatVersions format, ApplicationType appType)
        {
            _format = format;
            _appType = appType;

            Initialize();
        }
        public SemanticValidator(FileFormatVersions format, ApplicationType app)
        {
            FileFormat = format;
            AppType = app;

            _curReg = new SemanticConstraintRegistry(format, app);
        }
        /// <summary>
        /// Initializes a new instance of the SchemaValidator. 
        /// </summary>
        /// <param name="fileFormat">The target Open XML format.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the "fileFormat" parameter is not FileFormat.Office2007, FileFormat.Office2010 or FileFormat.O15.</exception>
        internal SchemaValidator(FileFormatVersions fileFormat)
        {
            if (fileFormat == FileFormatVersions.Office2007)
            {
                this._sdbSchemaDatas = SdbSchemaDatas.GetOffice2007SchemaDatas();
            }
            else if(fileFormat == FileFormatVersions.Office2010)
            {
                this._sdbSchemaDatas = SdbSchemaDatas.GetOffice2010SchemaDatas();
            }
            else if (fileFormat == FileFormatVersions.Office2013)
            {
                this._sdbSchemaDatas = SdbSchemaDatas.GetOffice2013SchemaDatas();
            }
            else
            {
                string message = String.Format(System.Globalization.CultureInfo.CurrentUICulture,
                                                    ExceptionMessages.FileFormatNotSupported,
                                                    fileFormat);
                throw new ArgumentOutOfRangeException("fileFormat", message);
            }

            this._schemaTypeValidator = new SchemaTypeValidator(this._sdbSchemaDatas);
#if DEBUG
            this._fileFormat = fileFormat;
#endif
        }
        /// <summary>
        /// Initializes a new instance of the ValidationSettings.
        /// </summary>
        /// <param name="fileFormat">The target file format.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown when the "fileFormat" parameter is not FileFormat.Office2007,  or FileFormat.Office2010 or FileFormat.Office2013.</exception>
        internal ValidationSettings(FileFormatVersions fileFormat)
        {
            fileFormat.ThrowExceptionIfFileFormatNotSupported("fileFormat");
            this.FileFormat = fileFormat;

            this.MaxNumberOfErrors = _defaultMaxNumberOfErrorsReturned;
        }
        internal AttributeConstraint(XsdAttributeUse xsdAttributeUse, SimpleTypeRestriction simpleTypeConstraint, FileFormatVersions supportedVersion)
        {
            Debug.Assert(simpleTypeConstraint != null);

            this.XsdAttributeUse = xsdAttributeUse;
            this.SimpleTypeConstraint = simpleTypeConstraint;
            this.SupportedVersion = supportedVersion;
        }
    /// <summary>
    /// Whether this element is available in a specific version of Office Application.
    /// </summary>
    /// <param name="version">The Office file format version.</param>
    /// <returns>Returns true if the element is defined in the specified version.</returns>
    internal override bool IsInVersion(FileFormatVersions version)
    {
		if((7 & (int)version) > 0)
		{
			return true;
		}
		return false;
    }
        /// <summary>
        /// Register a constraint to this registry.
        /// </summary>
        public void RegisterConstraint(int elementTypeID, int ancestorTypeID, FileFormatVersions fileFormat, ApplicationType appType, SemanticConstraint constraint )
        {
            if ((fileFormat & _format) == _format && (appType & _appType) == _appType)
            {

                AddConstraintToDic(constraint, ancestorTypeID, _cleanList);
                AddConstraintToDic(constraint, elementTypeID, _semConstraintMap);
            }
        }
 /// <summary>
 /// Initialize a instance of PartConstraintRule class.
 /// </summary>
 /// <param name="partClassName">The class name of the part.</param>
 /// <param name="partContentType">The content type of the part.</param>
 /// <param name="minOccursIsNonZero">The MinOccursIsNonZero data.</param>
 /// <param name="maxOccursGreatThanOne">The MaxOccursGreatThanOne data.</param>
 /// <param name="fileFormat">The file format version information.</param>
 internal PartConstraintRule(string partClassName, string partContentType, 
                             bool minOccursIsNonZero, bool maxOccursGreatThanOne,
                             FileFormatVersions fileFormat)
 {
     this.PartClassName = partClassName;
     this.PartContentType = partContentType;
     this.MinOccursIsNonZero = minOccursIsNonZero;
     this.MaxOccursGreatThanOne = maxOccursGreatThanOne;
     this.FileFormat = fileFormat;
 }
Exemple #9
0
        internal static OpenXmlSimpleType CreateTargetValueObject(RedirectedRestriction redirectedRestriction, FileFormatVersions fileFormatVersion)
        {
            switch (fileFormatVersion)
            {
                case FileFormatVersions.Office2007:
                    return O12UnionHelper.CreateTargetValueObject(redirectedRestriction);

                case FileFormatVersions.Office2010:
                    return O14UnionHelper.CreateTargetValueObject(redirectedRestriction);

                case FileFormatVersions.Office2013:
                    return O15UnionHelper.CreateTargetValueObject(redirectedRestriction);

                default:
                    Debug.Assert(fileFormatVersion == FileFormatVersions.Office2007 || fileFormatVersion == FileFormatVersions.Office2010 || fileFormatVersion == FileFormatVersions.Office2013);
                    break;
            }
            return null;
        }
Exemple #10
0
        internal static OpenXmlSimpleType[] CreatePossibleMembers(UnionValueRestriction unionValueRestriction, FileFormatVersions fileFormatVersion)
        {
            switch (fileFormatVersion)
            {
                case FileFormatVersions.Office2007:
                    return O12UnionHelper.CreatePossibleMembers(unionValueRestriction);

                case FileFormatVersions.Office2010:
                    return O14UnionHelper.CreatePossibleMembers(unionValueRestriction);

                case FileFormatVersions.Office2013:
                    return O15UnionHelper.CreatePossibleMembers(unionValueRestriction);

                default:
                    Debug.Assert(fileFormatVersion == FileFormatVersions.Office2007 || fileFormatVersion == FileFormatVersions.Office2010 || fileFormatVersion == FileFormatVersions.Office2013);
                    break;
            }
            return null;
        }
 internal override bool IsInVersion(FileFormatVersions version) => version.AtLeast(FileFormatVersions.Office2013);
        internal static OpenXmlSimpleType[] CreatePossibleMembers(UnionValueRestriction unionValueRestriction, FileFormatVersions fileFormatVersion)
        {
            switch (fileFormatVersion)
            {
            case FileFormatVersions.Office2007:
                return(O12UnionHelper.CreatePossibleMembers(unionValueRestriction));

            case FileFormatVersions.Office2010:
                return(O14UnionHelper.CreatePossibleMembers(unionValueRestriction));

            case FileFormatVersions.Office2013:
                return(O15UnionHelper.CreatePossibleMembers(unionValueRestriction));

            default:
                Debug.Assert(fileFormatVersion.Any());
                break;
            }
            return(null);
        }
 /// <summary>
 /// Test whether the value is allowed in the specified file format version. Only for EnumValue.
 /// </summary>
 /// <param name="fileFormat">The file format version.</param>
 /// <returns>True if the value is defined in the specified file format version.</returns>
 /// <remarks>
 /// Method to support enum validation in schema validation.
 /// </remarks>
 internal virtual bool IsInVersion(FileFormatVersions fileFormat)
 {
     throw new NotImplementedException();
 }
Exemple #14
0
 /// <summary>
 /// Initializes a new instance of the OfficeAvailabilityAttribute class.
 /// </summary>
 /// <param name="officeVersion">The Office version where this class or property is available.
 /// If there is more than one version, use bitwise OR to specify multiple versions.</param>
 public OfficeVersionValidator(FileFormatVersions officeVersion)
 {
     OfficeVersion = officeVersion;
 }
Exemple #15
0
 public void AtLeastExceptions(FileFormatVersions version)
 {
     Assert.Throws <ArgumentOutOfRangeException>(nameof(version), () => version.AtLeast(FileFormatVersions.Office2007));
     Assert.Throws <ArgumentOutOfRangeException>("minimum", () => FileFormatVersions.Office2007.AtLeast(version));
 }
        private static OpenXmlElement GetChildMc(this OpenXmlElement parent, OpenXmlElement child, MCContext mcContext, FileFormatVersions format)
        {
            // Use stack to cache the next siblings in different levels.
            Stack <OpenXmlElement> nextSiblings = new Stack <OpenXmlElement>();

            while (child != null)
            {
                var acb = child as AlternateContent;
                if (acb == null && child.IsInVersion(format))
                {
                    return(child);
                }
                else
                {
                    mcContext.PushMCAttributes2(child.MCAttributes, child.LookupNamespace);
                    if (acb != null)
                    {
                        nextSiblings.Push(child.GetNextNonMiscElementSibling());
                        var select = mcContext.GetContentFromACBlock(acb, format);
                        if (select != null)
                        {
                            child = select.GetFirstNonMiscElementChild();
                        }
                        else
                        {
                            // The ACB has no children elements.
                            // case like: <acb/> <acb><choice/><fallback/></acb>
                            child = null;
                        }
                    }
                    else
                    {
                        // Ignorable element, skip it
                        if (mcContext.IsIgnorableNs(child.NamespaceUri))
                        {
                            // Any element marked with ProcessContent should be an Ignorable Element
                            if (mcContext.IsProcessContent(child))
                            {
                                nextSiblings.Push(child.GetNextNonMiscElementSibling());
                                //
                                child = child.GetFirstNonMiscElementChild();
                            }
                            else
                            {
                                child = child.GetNextNonMiscElementSibling();
                            }
                        }
                        else
                        {
                            mcContext.PopMCAttributes2();
                            return(child);
                        }
                    }
                    mcContext.PopMCAttributes2();
                }

                while (child == null && nextSiblings.Count > 0)
                {
                    child = nextSiblings.Pop();
                }
            }

            // child is null.
            return(child);
        }
Exemple #17
0
 /// <summary>
 /// Initialize a new instance of ChildElementTypeAttribute.
 /// </summary>
 /// <param name="elementType">Specifies the type of the possible child element.</param>
 /// <param name="availableInOfficeVersion">Specifies the office version where the child element is first available.</param>
 public ChildElementInfoAttribute(Type elementType, FileFormatVersions availableInOfficeVersion)
 {
     ElementType        = elementType;
     AvailableInVersion = availableInOfficeVersion.AndLater();
 }
 private IEnumerable <OpenXmlPackageValidationEventArgs> ValidateDataPartReferenceRelationships(OpenXmlPartContainer container, FileFormatVersions version)
 {
     // At current, only media / audio / video reference. There are all [0, unbounded].
     // So just check whether the reference is allowed.
     foreach (var dataPartReference in container.DataPartReferenceRelationships)
     {
         if (!container.GetDataPartReferenceConstraint().TryGetValue(dataPartReference.RelationshipType, out var constraintRule))
         {
             yield return(new OpenXmlPackageValidationEventArgs(container)
             {
                 MessageId = "DataPartReferenceIsNotAllowed",
                 PartClassName = dataPartReference.RelationshipType,
                 Part = container.ThisOpenXmlPart,
                 SubPart = null,
                 DataPartReferenceRelationship = dataPartReference
             });
         }
     }
 }
 /// <summary>
 /// Initializes a new instance of the OfficeAvailabilityAttribute class.
 /// </summary>
 /// <param name="officeVersion">The Office version where this class or property is available. 
 /// If there is more than one version, use bitwise OR to specify multiple versions.</param>
 public OfficeAvailabilityAttribute(FileFormatVersions officeVersion)
 {
     OfficeVersion = officeVersion;
 }
 public virtual ParticleConstraint?Build(FileFormatVersions version)
 => version.AtLeast(Version) ? this : null;
        internal ElementAction GetElementAction(OpenXmlElement element, FileFormatVersions format)
        {
            if (format == (FileFormatVersions.Office2010 | FileFormatVersions.Office2007) || format == (FileFormatVersions.Office2010 | FileFormatVersions.Office2007 | FileFormatVersions.Office2013))
            {
                return ElementAction.Normal;
            }

            if (element is AlternateContent)
            {
                return ElementAction.ACBlock;
            } 
            
            if (element.IsInVersion(format))
            {
                return ElementAction.Normal;
            }

            if (IsIgnorableNs(element.NamespaceUri))
            {
                if (IsPreservedElement(element.NamespaceUri, element.LocalName))
                {
                    return ElementAction.Normal;
                }
                if (IsProcessContent(element.NamespaceUri, element.LocalName))
                {
                    return ElementAction.ProcessContent;
                }
                return ElementAction.Ignore;
            }

            return ElementAction.Normal;
        }
        internal AttributeAction GetAttributeAction(string ns, string localName, FileFormatVersions format)
        {
            if (format == (FileFormatVersions.Office2010|FileFormatVersions.Office2007) || format == (FileFormatVersions.Office2010|FileFormatVersions.Office2007|FileFormatVersions.Office2013))
            {
                return AttributeAction.Normal;
            }

            if (string.IsNullOrEmpty(ns))
            {
                return AttributeAction.Normal;
            }

            if (NamespaceIdMap.IsInFileFormat(ns, format))
            {
                return AttributeAction.Normal;
            }

            if (!IsIgnorableNs(ns))
            {
                return AttributeAction.Normal;
            }

            if (IsPreservedAttribute(ns, localName))
            {
                return AttributeAction.Normal;
            }

            return AttributeAction.Ignore;
        }
        internal OpenXmlCompositeElement GetContentFromACBlock(AlternateContent acblk, FileFormatVersions format)
        {
            Debug.Assert(format != (FileFormatVersions.Office2007 | FileFormatVersions.Office2010 | FileFormatVersions.Office2013));

            foreach (var choice in acblk.ChildElements.OfType<AlternateContentChoice>())
            {
                if(choice.Requires == null)
                {
                    //should we throw exception here?
                    continue;
                }
                string reqs = choice.Requires.InnerText.Trim();
                if (string.IsNullOrEmpty(reqs))
                {
                    //should we throw exception here?
                    continue;
                }

                bool chooce = true;
                foreach (var req in reqs.Split(new char[] { ' ' }))
                {
                    //fix bug 537858
                    //the LookupNamespaceDeleget is from xmlReader
                    //bug when we try to GetContentFromACBlock, the reader has already moved to the next element of ACB
                    //so we should use the element's LookupNamespace function to find it
                    //string ns = LookupNamespaceDelegate(req);
                    string ns = choice.LookupNamespace(req);
                    if (ns == null)
                    {
                        if (this._noExceptionOnError)
                        {
                            chooce = false;
                            break;
                        }
                        else
                        {
                            var msg = String.Format(System.Globalization.CultureInfo.CurrentUICulture, ExceptionMessages.UnknowMCContent, req);
                            throw new InvalidMCContentException(msg);
                        }
                    }
                    if (!NamespaceIdMap.IsInFileFormat(ns, format))
                    {
                        chooce = false;
                        break;
                    }
                }

                if (chooce)
                {
                    return choice;
                }
            }
            var fallback = acblk.GetFirstChild<AlternateContentFallback>();
            if (fallback != null)
            {
                return fallback;
            }
            return null;
        }
 public EnumStringInfo(FileFormatVersions versions, string name)
 {
     Versions = versions;
     Name     = name;
 }
        /// <summary>
        /// Validates the package (do not validate the xml content in each part).
        /// </summary>
        /// <param name="container">The Open XML container to validate</param>
        /// <param name="version">Version to validate against</param>
        /// <param name="processedParts">Parts already processed.</param>
        private IEnumerable <OpenXmlPackageValidationEventArgs> ValidateInternal(OpenXmlPartContainer container, FileFormatVersions version, Dictionary <OpenXmlPart, bool> processedParts)
        {
            foreach (var result in ValidateDataPartReferenceRelationships(container, version))
            {
                yield return(result);
            }

            // count all parts of same type
            var partOccurs = new Dictionary <string, int>(StringComparer.Ordinal);

            foreach (var part in container.ChildrenParts.Values)
            {
                if (partOccurs.TryGetValue(part.RelationshipType, out int occurs))
                {
                    partOccurs[part.RelationshipType] = occurs + 1;
                }
                else
                {
                    partOccurs.Add(part.RelationshipType, 1);
                }

                if (!(container is ExtendedPart) &&
                    !container.GetPartConstraint().Keys.Contains(part.RelationshipType) &&
                    part.IsInVersion(version))
                {
                    yield return(new OpenXmlPackageValidationEventArgs(container)
                    {
                        MessageId = "PartIsNotAllowed",
                        PartClassName = part.RelationshipType,
                        Part = container.ThisOpenXmlPart,
                        SubPart = part
                    });
                }

                // if the part is not defined in this version, then should not report error, just treat it as ExtendedPart.
            }

            foreach (var constraintRulePair in container.GetPartConstraint())
            {
                var relatinshipType = constraintRulePair.Key;
                var constraintRule  = constraintRulePair.Value;

                // validate the required parts
                if (constraintRule.MinOccursIsNonZero
                    // only check rules apply to the specified version.
                    && constraintRule.FileFormat.Includes(version))
                {
                    // must have one
                    if (null == container.GetSubPart(relatinshipType))
                    {
                        yield return(new OpenXmlPackageValidationEventArgs(container)
                        {
                            MessageId = "RequiredPartDoNotExist",
                            PartClassName = constraintRule.PartClassName,
                            Part = container.ThisOpenXmlPart
                        });
                    }
                }

                // check for parts MaxOccursGreatThanOne=false, but do have multiple instance
                if (!constraintRule.MaxOccursGreatThanOne
                    // only check rules apply to the specified version.
                    && constraintRule.FileFormat.Includes(version))
                {
                    if (partOccurs.TryGetValue(relatinshipType, out int occurs))
                    {
                        if (occurs > 1)
                        {
                            yield return(new OpenXmlPackageValidationEventArgs(container)
                            {
                                MessageId = "OnlyOnePartAllowed",
                                PartClassName = constraintRule.PartClassName,
                                Part = container.ThisOpenXmlPart,
#if DEBUG
                                SubPart = container.GetSubPart(relatinshipType)
#endif
                            });
                        }
                    }
                }
            }

            foreach (var part in container.ChildrenParts.Values)
            {
                if (!processedParts.ContainsKey(part))
                {
                    if (!(part is ExtendedPart))
                    {
                        if (container.GetPartConstraint().TryGetValue(part.RelationshipType, out var rule))
                        {
                            if (rule.FileFormat.Includes(version))
                            {
                                // validate content type
                                if (rule.PartContentType != null && part.ContentType != rule.PartContentType)
                                {
                                    var message = String.Format(CultureInfo.CurrentUICulture, ExceptionMessages.InvalidContentTypePart, rule.PartContentType);
                                    yield return(new OpenXmlPackageValidationEventArgs(container)
                                    {
                                        Message = message,
                                        MessageId = "InvalidContentTypePart",
                                        SubPart = part,
                                        Part = container.ThisOpenXmlPart
                                    });
                                }
                            }
                            else
                            {
                                // if the part is not defined in this version, then should not report error, just treat it as ExtendedPart.
                            }
                        }
                    }
#if DEBUG
                    else
                    {
                        // check the relationship type
                        if (part.RelationshipType.StartsWith(@"http://schemas.openxmlformats.org", StringComparison.OrdinalIgnoreCase))
                        {
                            yield return(new OpenXmlPackageValidationEventArgs(container)
                            {
                                MessageId = "ExtendedPartIsOpenXmlPart",
                                SubPart = part,
                                Part = container.ThisOpenXmlPart
                            });
                        }
                    }
#endif
                    processedParts.Add(part, true);

                    foreach (var result in ValidateInternal(part, version, processedParts))
                    {
                        yield return(result);
                    }
                }
            }
        }
        internal static OpenXmlElement GetFirstChildMc(this OpenXmlElement parent, MCContext mcContext, FileFormatVersions format)
        {
            var child = parent.GetFirstNonMiscElementChild();

            return(parent.GetChildMc(child, mcContext, format));
        }
 /// <summary>
 /// Indicates whether the current part is available in a specific version of an Office Application.
 /// </summary>
 /// <param name="version">The Office file format version.</param>
 /// <returns>Returns true if the part is defined in the specified version.</returns>
 internal virtual bool IsInVersion(FileFormatVersions version)
 {
     return(true);
 }
 /// <summary>
 /// Initialize a new instance of ChildElementTypeAttribute.
 /// </summary>
 /// <param name="elementType">Specifies the type of the possible child element.</param>
 public ChildElementInfoAttribute(Type elementType)
 {
     _type = elementType;
     format = FileFormatVersions.Office2007 | FileFormatVersions.Office2010;
 }
Exemple #29
0
 /// <summary>
 /// Initializes a new instance of the SchemaValidator.
 /// </summary>
 /// <param name="fileFormat">The target Open XML format.</param>
 /// <exception cref="ArgumentOutOfRangeException">Thrown when the "fileFormat" parameter is not FileFormat.Office2007, FileFormat.Office2010 or FileFormat.O15.</exception>
 public SchemaValidator(FileFormatVersions fileFormat)
 {
     _sdbSchemaDatas      = SdbSchemaDatas.GetSchemaDatas(fileFormat);
     _schemaTypeValidator = new SchemaTypeValidator(_sdbSchemaDatas);
 }
 /// <summary>
 /// Initializes a new instance of the OpenXmlValidator.
 /// </summary>
 /// <param name="fileFormat">The target filr format to be validated aginst.</param>
 /// <remarks>
 /// Default to FileFormat.Office2007.
 /// </remarks>
 /// <exception cref="ArgumentOutOfRangeException">Thrown when the "fileFormat" parameter is not FileFormat.Office2007, FileFormat.Office2010 or FileFormat.O15.</exception>
 public OpenXmlValidator(FileFormatVersions fileFormat)
 {
     fileFormat.ThrowExceptionIfFileFormatNotSupported("fileFormat");
     this._settings = new ValidationSettings(fileFormat);
 }
Exemple #31
0
 public ValidationContext(FileFormatVersions version = FileFormatVersions.Office2007)
     : this(new ValidationSettings(version), new ValidationCache(version), default)
 {
 }
 public static bool IsInFileFormat(string ns,FileFormatVersions format)
 {
     if (format == FileFormatVersions.Office2007)
     {
         if (_O12NamespaceSet.Contains(ns))
         {
             return true;
         }
         return false;
     }
     else if (format == FileFormatVersions.Office2010)
     {
         if (_O14NamespaceSet.Contains(ns))
         {
             return true;
         }
         return false;
     }
     else if (format == FileFormatVersions.Office2013)
     {
         if (_O15NamespaceSet.Contains(ns))
         {
             return true;
         }
         return false;
     }
     throw new NotImplementedException();
 }
        /// <summary>
        /// Trys to create an OpenXmlElement from the specified namespace URI and local name.
        /// </summary>
        /// <param name="parent">The parent element.</param>
        /// <param name="fileFormat">The specified file format version.</param>
        /// <param name="namespaceUri">The namespace URI of the requested child element.</param>
        /// <param name="localName">The local name of the requested child element.</param>
        /// <returns>A new OpenXmlElement if the parent element can contains a child with the specified namespace and local name. Otherwise, returns null.</returns>
        internal static OpenXmlElement?TryCreateValidChild(this OpenXmlElement parent, FileFormatVersions fileFormat, string namespaceUri, string localName)
        {
            Debug.Assert(parent is OpenXmlCompositeElement);

            var newElement = parent.CreateElement(OpenXmlQualifiedName.Create(namespaceUri, string.Empty, localName));

            if (newElement is OpenXmlUnknownElement || !newElement.IsInVersion(fileFormat))
            {
                return(null);
            }

            return(newElement);
        }
Exemple #34
0
 /// <summary>
 /// Initializes a new instance of the OpenXmlValidator.
 /// </summary>
 /// <param name="fileFormat">The target file format to be validated against.</param>
 /// <remarks>
 /// Default to FileFormat.Office2007.
 /// </remarks>
 /// <exception cref="ArgumentOutOfRangeException">Thrown when the <paramref name="fileFormat"/> parameter is not a known format.</exception>
 public OpenXmlValidator(FileFormatVersions fileFormat)
 {
     fileFormat.ThrowExceptionIfFileFormatNotSupported(nameof(fileFormat));
     _settings = new ValidationSettings(fileFormat);
 }
        internal static OpenXmlElement TryCreateValidChild(this OpenXmlElement parent, FileFormatVersions fileFormat, string namespaceUri, string localName)
        {
            Debug.Assert(parent is OpenXmlCompositeElement);
            Debug.Assert(localName is not null);

            var newElement = parent.ElementFactory(string.Empty, localName, namespaceUri);

            if (newElement is OpenXmlUnknownElement || !newElement.IsInVersion(fileFormat))
            {
                return(null);
            }

            return(newElement);
        }
        internal static OpenXmlSimpleType CreateTargetValueObject(RedirectedRestriction redirectedRestriction, FileFormatVersions fileFormatVersion)
        {
            switch (fileFormatVersion)
            {
            case FileFormatVersions.Office2007:
                return(O12UnionHelper.CreateTargetValueObject(redirectedRestriction));

            case FileFormatVersions.Office2010:
                return(O14UnionHelper.CreateTargetValueObject(redirectedRestriction));

            case FileFormatVersions.Office2013:
                return(O15UnionHelper.CreateTargetValueObject(redirectedRestriction));

            default:
                Debug.Assert(fileFormatVersion.Any());
                break;
            }
            return(null);
        }
 /// <summary>
 /// Whether this element is available in a specific version of Office Application.
 /// For OpenXmlUnknownElement, always return false, no matter what the version is.
 /// </summary>
 /// <param name="version">The Office file format version.</param>
 /// <returns>Returns true if the element is defined in the specified version.</returns>
 internal override bool IsInVersion(FileFormatVersions version)
 {
     return false;
 }
Exemple #38
0
 internal override bool IsInVersion(FileFormatVersions version)
 {
     return(version.AtLeast(FileFormatVersions.Office2013));
 }
 /// <summary>
 /// Determines whether the source FileFormatVersions includes the target FileFormatVersions. 
 /// </summary>
 /// <param name="source">The source FileFormatVersions to be tested.</param>
 /// <param name="target">The target FileFormatVersions be tested against.</param>
 /// <returns>Returns true when (source &amp; target) == target.</returns>
 internal static bool Includes(this FileFormatVersions source, FileFormatVersions target)
 {
     return (source & target) == target;
 }
 /// <summary>
 /// Initializes a new instance of the OpenXmlValidator.
 /// </summary>
 /// <param name="fileFormat">The target filr format to be validated aginst.</param>
 /// <remarks>
 /// Default to FileFormat.Office2007.
 /// </remarks>
 /// <exception cref="ArgumentOutOfRangeException">Thrown when the "fileFormat" parameter is not FileFormat.Office2007, FileFormat.Office2010 or FileFormat.O15.</exception>
 public OpenXmlValidator(FileFormatVersions fileFormat)
 {
     fileFormat.ThrowExceptionIfFileFormatNotSupported("fileFormat");
     this._settings = new ValidationSettings(fileFormat);
 }
        internal static OpenXmlElement GetNextChildMc(this OpenXmlElement parent, OpenXmlElement child, MCContext mcContext, FileFormatVersions format)
        {
            var next = child.GetNextNonMiscElementSibling();
            var mcTier = child.Parent;

            if (next == null && mcTier != parent)
            {
                // the child must be under element in ProcessContent or ACB
                if (mcTier is AlternateContentChoice || mcTier is AlternateContentFallback)
                {
                    mcTier = mcTier.Parent;
                }
                Debug.Assert(mcTier != null);

                // there is no more next sibling in this level, then try to find the next siblig of the up level.
                return parent.GetNextChildMc(mcTier, mcContext, format);
            }

            return parent.GetChildMc(next, mcContext, format);
        }
 /// <summary>
 /// Whether this element is available in a specific version of Office Application.
 /// For OpenXmlUnknownElement, always return false, no matter what the version is.
 /// </summary>
 /// <param name="version">The Office file format version.</param>
 /// <returns>Returns true if the element is defined in the specified version.</returns>
 internal override bool IsInVersion(FileFormatVersions version)
 {
     return(false);
 }
 /// <summary>
 /// Initialize a new instance of ChildElementTypeAttribute.
 /// </summary>
 /// <param name="elementType">Specifies the type of the possible child element.</param>
 /// <param name="availableInOfficeVersion">Specifies the office version(s) where the child element is available.</param>
 public ChildElementInfoAttribute(Type elementType, FileFormatVersions availableInOfficeVersion)
 {
     _type = elementType;
     format = availableInOfficeVersion;
 }
        internal static OpenXmlElement GetNextChildMc(this OpenXmlElement parent, OpenXmlElement child, MCContext mcContext, FileFormatVersions format)
        {
            var next   = child.GetNextNonMiscElementSibling();
            var mcTier = child.Parent;

            if (next == null && mcTier != parent)
            {
                // the child must be under element in ProcessContent or ACB
                if (mcTier is AlternateContentChoice || mcTier is AlternateContentFallback)
                {
                    mcTier = mcTier.Parent;
                }
                Debug.Assert(mcTier != null);

                // there is no more next sibling in this level, then try to find the next siblig of the up level.
                return(parent.GetNextChildMc(mcTier, mcContext, format));
            }

            return(parent.GetChildMc(next, mcContext, format));
        }
Exemple #45
0
 public void CheckAll(FileFormatVersions version, bool expected)
 {
     Assert.Equal(expected, version.All());
 }
Exemple #46
0
 /// <inheritdoc/>
 internal override bool IsInVersion(FileFormatVersions version)
 {
     // For OpenXmlMiscNode, always return true, no matter what the version is.
     return(true);
 }
Exemple #47
0
 public void AndLaterExceptions(FileFormatVersions version)
 {
     Assert.Throws <ArgumentOutOfRangeException>(nameof(version), () => version.AndLater());
 }
        /// <summary>
        /// Trys to create an OpenXmlElement from the specified namesapce URI and local name.
        /// </summary>
        /// <param name="parent">The parent element.</param>
        /// <param name="fileFormat">The specified file format version.</param>
        /// <param name="namespaceUri">The namespace URI of the requested child element.</param>
        /// <param name="localName">The local name of the requested child element.</param>
        /// <returns>A new OpenXmlElement if the parent element can contains a child with the specified namespace and local name. Otherwise, returns null.</returns>
        internal static OpenXmlElement TryCreateValidChild(this OpenXmlElement parent, FileFormatVersions fileFormat, string namespaceUri, string localName)
        {
            Debug.Assert(parent is OpenXmlCompositeElement);
            Debug.Assert(localName != null);

            var newElement = parent.ElementFactory(string.Empty, localName, namespaceUri);
            if (newElement is OpenXmlUnknownElement || !newElement.IsInVersion(fileFormat))
            {
                return null;
            }
            return newElement;
        }
Exemple #49
0
 public void CheckAtLeast(FileFormatVersions version, FileFormatVersions minimum, bool expected)
 {
     Assert.Equal(expected, version.AtLeast(minimum));
 }
 /// <summary>
 /// Combines values for the given version and all versions that come after it
 /// </summary>
 /// <param name="version">Version to which all other versions are added</param>
 /// <returns>A version instance with <paramref name="version"/> and all later versions</returns>
 public static FileFormatVersions AndLater(this FileFormatVersions version)
 => version switch
 {
 public static bool IsInFileFormat(string ns, FileFormatVersions format)
 {
     if (format == FileFormatVersions.Office2007)
     {
         if (NamespaceIdMap._O12NamespaceSet.Contains(ns))
             return true;
         else
             return false;
     }
     else
     {
         if (format != FileFormatVersions.Office2010)
             throw new NotImplementedException();
         if (NamespaceIdMap._O14NamespaceSet.Contains(ns))
             return true;
         else
             return false;
     }
 }
 internal static OpenXmlElement GetFirstChildMc(this OpenXmlElement parent, MCContext mcContext, FileFormatVersions format)
 {
     var child = parent.GetFirstNonMiscElementChild();
     return parent.GetChildMc(child, mcContext, format);
 }
Exemple #53
0
        public void Bug583585(FileFormatVersions version)
        {
            var validator = new OpenXmlValidator(version);

            var element = new DocumentFormat.OpenXml.Presentation.ModificationVerifier();

            element.SaltData = "8fkqu/A/6B1OQrRX1Vb3oQ";

            var errors = validator.Validate(element);

            Assert.Collection(
                errors.OrderBy(t => t.Description),
                e =>
            {
                Assert.Equal("The attribute 'saltData' has invalid value '8fkqu/A/6B1OQrRX1Vb3oQ'. The string '8fkqu/A/6B1OQrRX1Vb3oQ' is not a valid 'http://www.w3.org/2001/XMLSchema:base64Binary' value.", e.Description);
                Assert.Same(element, e.Node);
                Assert.Null(e.RelatedNode);
                Assert.Equal(ValidationErrorType.Schema, e.ErrorType);
                Assert.Equal("Sch_AttributeValueDataTypeDetailed", e.Id);
                Assert.Equal("/p:modifyVerifier[1]", e.Path.XPath);
            },
                e =>
            {
                Assert.Equal("The required attribute 'cryptAlgorithmClass' is missing.", e.Description);
                Assert.Same(element, e.Node);
                Assert.Null(e.RelatedNode);
                Assert.Equal(ValidationErrorType.Schema, e.ErrorType);
                Assert.Equal("Sch_MissRequiredAttribute", e.Id);
                Assert.Equal("/p:modifyVerifier[1]", e.Path.XPath);
            },
                e =>
            {
                Assert.Equal("The required attribute 'cryptAlgorithmSid' is missing.", e.Description);
                Assert.Same(element, e.Node);
                Assert.Null(e.RelatedNode);
                Assert.Equal(ValidationErrorType.Schema, e.ErrorType);
                Assert.Equal("Sch_MissRequiredAttribute", e.Id);
                Assert.Equal("/p:modifyVerifier[1]", e.Path.XPath);
            },
                e =>
            {
                Assert.Equal("The required attribute 'cryptAlgorithmType' is missing.", e.Description);
                Assert.Same(element, e.Node);
                Assert.Null(e.RelatedNode);
                Assert.Equal(ValidationErrorType.Schema, e.ErrorType);
                Assert.Equal("Sch_MissRequiredAttribute", e.Id);
                Assert.Equal("/p:modifyVerifier[1]", e.Path.XPath);
            },
                e =>
            {
                Assert.Equal("The required attribute 'cryptProviderType' is missing.", e.Description);
                Assert.Same(element, e.Node);
                Assert.Null(e.RelatedNode);
                Assert.Equal(ValidationErrorType.Schema, e.ErrorType);
                Assert.Equal("Sch_MissRequiredAttribute", e.Id);
                Assert.Equal("/p:modifyVerifier[1]", e.Path.XPath);
            },
                e =>
            {
                Assert.Equal("The required attribute 'hashData' is missing.", e.Description);
                Assert.Same(element, e.Node);
                Assert.Null(e.RelatedNode);
                Assert.Equal(ValidationErrorType.Schema, e.ErrorType);
                Assert.Equal("Sch_MissRequiredAttribute", e.Id);
                Assert.Equal("/p:modifyVerifier[1]", e.Path.XPath);
            },
                e =>
            {
                Assert.Equal("The required attribute 'spinCount' is missing.", e.Description);
                Assert.Same(element, e.Node);
                Assert.Null(e.RelatedNode);
                Assert.Equal(ValidationErrorType.Schema, e.ErrorType);
                Assert.Equal("Sch_MissRequiredAttribute", e.Id);
                Assert.Equal("/p:modifyVerifier[1]", e.Path.XPath);
            });
        }
        private static OpenXmlElement GetChildMc(this OpenXmlElement parent, OpenXmlElement child, MCContext mcContext, FileFormatVersions format)
        {
            // Use stack to cache the next siblings in different levels.
            Stack<OpenXmlElement> nextSiblings = new Stack<OpenXmlElement>();

            while (child != null)
            {
                var acb = child as AlternateContent;
                if (acb == null && child.IsInVersion(format))
                {
                    return child;
                }
                else
                {
                    mcContext.PushMCAttributes2(child.MCAttributes, child.LookupNamespace);
                    if (acb != null)
                    {
                        nextSiblings.Push(child.GetNextNonMiscElementSibling());
                        var select = mcContext.GetContentFromACBlock(acb, format);
                        if (select != null)
                        {
                            child = select.GetFirstNonMiscElementChild();
                        }
                        else
                        {
                            // The ACB has no children elements. 
                            // case like: <acb/> <acb><choice/><fallback/></acb>
                            child = null;
                        }
                    }
                    else
                    {
                        // Ignorable element, skip it
                        if (mcContext.IsIgnorableNs(child.NamespaceUri))
                        {
                            // Any element marked with ProcessContent should be an Ignorable Element
                            if (mcContext.IsProcessContent(child))
                            {
                                nextSiblings.Push(child.GetNextNonMiscElementSibling());
                                //
                                child = child.GetFirstNonMiscElementChild();
                            }
                            else
                            {
                                child = child.GetNextNonMiscElementSibling();
                            }
                        }
                        else
                        {
                            mcContext.PopMCAttributes2();
                            return child;
                        }
                    }
                    mcContext.PopMCAttributes2();
                }

                while (child == null && nextSiblings.Count > 0)
                {
                    child = nextSiblings.Pop();
                }
            }

            // child is null.
            return child;
        }
Exemple #55
0
 public bool IsInVersion(FileFormatVersions version)
 => Version == version;