示例#1
0
        // Return true if an open XML document is enforcing read-only
        private static bool IsOpenXMLReadOnlyEnforced(string filename)
        {
            // Read an OpenXML type document
            using (Package package = Package.Open(path: filename, packageMode: FileMode.Open, packageAccess: FileAccess.Read))
            {
                if (null == package)
                {
                    return(false);
                }
                try
                {
                    // Document security is set in the extended properties
                    // https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2010/cc845474(v%3doffice.14)
                    string extendedType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties";
                    PackageRelationshipCollection extendedProps = package.GetRelationshipsByType(extendedType);
                    if (null != extendedProps)
                    {
                        IEnumerator extendedPropsList = extendedProps.GetEnumerator();
                        if (extendedPropsList.MoveNext())
                        {
                            Uri         extendedPropsUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), ((PackageRelationship)extendedPropsList.Current).TargetUri);
                            PackagePart props            = package.GetPart(extendedPropsUri);
                            if (null != props)
                            {
                                // Read the internal docProps/app.xml XML file
                                XDocument xmlDoc     = XDocument.Load(props.GetStream());
                                XElement  securityEl = xmlDoc.Root.Element(XName.Get("DocSecurity", xmlDoc.Root.GetDefaultNamespace().NamespaceName));
                                if (null != securityEl)
                                {
                                    if (!String.IsNullOrWhiteSpace(securityEl.Value))
                                    {
                                        // See https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2010/cc840043%28v%3doffice.14%29
                                        return((Int16.Parse(securityEl.Value) & 4) == 4);
                                    }
                                }

                                package.Close();
                                // PowerPoint doesn't use DocSecurity (*sigh*) so need another check
                                XElement appEl = xmlDoc.Root.Element(XName.Get("Application", xmlDoc.Root.GetDefaultNamespace().NamespaceName));
                                if (null != appEl)
                                {
                                    if (!String.IsNullOrWhiteSpace(appEl.Value) &&
                                        appEl.Value.IndexOf("PowerPoint", StringComparison.InvariantCultureIgnoreCase) >= 0)
                                    {
                                        PresentationDocument presentationDocument = PresentationDocument.Open(path: filename, isEditable: false);
                                        if (null != presentationDocument &&
                                            presentationDocument.PresentationPart.Presentation.ModificationVerifier != null)
                                        {
                                            return(true);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception) { }
                return(false);
            }
        }
示例#2
0
        /// <summary>
        /// Retrieves an entry part marked as a WPF payload entry part
        /// by appropriate package relationship.
        /// </summary>
        /// <returns>
        /// PackagePart containing a Wpf package entry.
        /// Null if such part does not exist in this package.
        /// </returns>
        private PackagePart GetWpfEntryPart()
        {
            PackagePart wpfEntryPart = null;

            // Find a relationship to entry part
            PackageRelationshipCollection entryPartRelationships = _package.GetRelationshipsByType(XamlRelationshipFromPackageToEntryPart);
            PackageRelationship           entryPartRelationship  = null;

            foreach (PackageRelationship packageRelationship in entryPartRelationships)
            {
                entryPartRelationship = packageRelationship;
                break;
            }

            // Get a part referred by this relationship
            if (entryPartRelationship != null)
            {
                // Get entry part uri
                Uri entryPartUri = entryPartRelationship.TargetUri;

                // Get the enrty part
                wpfEntryPart = _package.GetPart(entryPartUri);
            }

            return(wpfEntryPart);
        }
        private void ClearPackagePartsWithRelationshipType(string relType, PackagePart parent, string partUri)
        {
            PackageRelationshipCollection rels = parent == null?Package.GetRelationshipsByType(relType) : parent.GetRelationshipsByType(relType);

            List <string> relIds = new List <string>();

            foreach (PackageRelationship r in rels)
            {
                if (r.TargetMode == TargetMode.Internal)
                {
                    if (partUri == null || r.TargetUri.ToString() == partUri)
                    {
                        Package.DeletePart(r.TargetUri);
                        relIds.Add(r.Id);
                    }
                }
            }

            foreach (string relId in relIds)
            {
                if (parent == null)
                {
                    Package.DeleteRelationship(relId);
                }
                else
                {
                    parent.DeleteRelationship(relId);
                }
            }
        }
示例#4
0
        internal void CopyDecks(Package package)
        {
            string path = Path.Combine(GamesRepository.BasePath, "Decks");
            PackageRelationshipCollection decks = package.GetRelationshipsByType("http://schemas.octgn.org/set/deck");
            var buffer = new byte[0x1000];

            foreach (PackageRelationship deckRel in decks)
            {
                PackagePart deck    = package.GetPart(deckRel.TargetUri);
                string      deckuri = Path.GetFileName(deck.Uri.ToString());
                if (deckuri == null)
                {
                    continue;
                }
                string deckFilename = Path.Combine(path, deckuri);
                using (Stream deckStream = deck.GetStream(FileMode.Open, FileAccess.Read))
                    using (
                        FileStream targetStream = File.Open(deckFilename, FileMode.Create, FileAccess.Write, FileShare.Read)
                        )
                    {
                        while (true)
                        {
                            int read = deckStream.Read(buffer, 0, buffer.Length);
                            if (read == 0)
                            {
                                break;
                            }
                            targetStream.Write(buffer, 0, read);
                        }
                    }
            }
        }
示例#5
0
        public POIXMLProperties(OPCPackage docPackage)
        {
            this.pkg  = docPackage;
            this.core = new POIXMLProperties.CoreProperties((PackagePropertiesPart)this.pkg.GetPackageProperties());
            PackageRelationshipCollection relationshipsByType1 = this.pkg.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties");

            if (relationshipsByType1.Size == 1)
            {
                this.extPart = this.pkg.GetPart(relationshipsByType1.GetRelationship(0));
                this.ext     = new POIXMLProperties.ExtendedProperties(ExtendedPropertiesDocument.Parse(this.extPart.GetInputStream()));
            }
            else
            {
                this.extPart = (PackagePart)null;
                this.ext     = new POIXMLProperties.ExtendedProperties(POIXMLProperties.NEW_EXT_INSTANCE.Copy());
            }
            PackageRelationshipCollection relationshipsByType2 = this.pkg.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties");

            if (relationshipsByType2.Size == 1)
            {
                this.custPart = this.pkg.GetPart(relationshipsByType2.GetRelationship(0));
                this.cust     = new POIXMLProperties.CustomProperties(CustomPropertiesDocument.Parse(this.custPart.GetInputStream()));
            }
            else
            {
                this.custPart = (PackagePart)null;
                this.cust     = new POIXMLProperties.CustomProperties(POIXMLProperties.NEW_CUST_INSTANCE.Copy());
            }
        }
示例#6
0
        public void CheckPartRelationships()
        {
            AddThreeParts();
            Assert.AreEqual(4, package.GetParts().Count(), "#a");
            PackagePart         part = package.GetPart(uris [0]);
            PackageRelationship r1   = part.CreateRelationship(part.Uri, TargetMode.Internal, "self");
            PackageRelationship r2   = package.CreateRelationship(part.Uri, TargetMode.Internal, "fake");
            PackageRelationship r3   = package.CreateRelationship(new Uri("/fake/uri", UriKind.Relative), TargetMode.Internal, "self");

            Assert.AreEqual(6, package.GetParts().Count(), "#b");
            Assert.AreEqual(1, part.GetRelationships().Count(), "#1");
            Assert.AreEqual(1, part.GetRelationshipsByType("self").Count(), "#2");
            Assert.AreEqual(r1, part.GetRelationship(r1.Id), "#3");
            Assert.AreEqual(2, package.GetRelationships().Count(), "#4");
            Assert.AreEqual(1, package.GetRelationshipsByType("self").Count(), "#5");
            Assert.AreEqual(r3, package.GetRelationship(r3.Id), "#6");

            Assert.AreEqual(6, package.GetParts().Count(), "#c");
            Assert.AreEqual(part.Uri, r1.SourceUri, "#7");
            Assert.AreEqual(new Uri("/", UriKind.Relative), r3.SourceUri, "#8");

            PackageRelationship r4 = part.CreateRelationship(uris [2], TargetMode.Internal, "other");

            Assert.AreEqual(part.Uri, r4.SourceUri);

            PackageRelationshipCollection relations = package.GetPart(uris [2]).GetRelationships();

            Assert.AreEqual(0, relations.Count());
            Assert.AreEqual(6, package.GetParts().Count(), "#d");
        }
示例#7
0
        /**
         * Recursively copy namespace parts to the destination namespace
         */
        private static void Copy(OPCPackage pkg, PackagePart part, OPCPackage tgt, PackagePart part_tgt) {
        PackageRelationshipCollection rels = part.Relationships;
        if(rels != null) 
            foreach (PackageRelationship rel in rels) {
            PackagePart p;
            if(rel.TargetMode == TargetMode.External){
                part_tgt.AddExternalRelationship(rel.TargetUri.ToString(), rel.RelationshipType, rel.Id);
                //external relations don't have associated namespace parts
                continue;
            }
            Uri uri = rel.TargetUri;

            if(uri.Fragment != null) {
                part_tgt.AddRelationship(uri, (TargetMode)rel.TargetMode, rel.RelationshipType, rel.Id);
                continue;
            }
            PackagePartName relName = PackagingUriHelper.CreatePartName(rel.TargetUri);
            p = pkg.GetPart(relName);
            part_tgt.AddRelationship(p.PartName, (TargetMode)rel.TargetMode, rel.RelationshipType, rel.Id);




            PackagePart dest;
            if(!tgt.ContainPart(p.PartName)){
                dest = tgt.CreatePart(p.PartName, p.ContentType);
                Stream out1 = dest.GetOutputStream();
                IOUtils.Copy(p.GetInputStream(), out1);
                out1.Close();
                Copy(pkg, p, tgt, dest);
            }
        }
    }
示例#8
0
        /**
         * Clone the specified namespace.
         *
         * @param   pkg   the namespace to clone
         * @param   file  the destination file
         * @return  the Cloned namespace
         */
        public static OPCPackage Clone(OPCPackage pkg, string path)
        {
            OPCPackage dest = OPCPackage.Create(path);
            PackageRelationshipCollection rels = pkg.Relationships;

            foreach (PackageRelationship rel in rels)
            {
                PackagePart part = pkg.GetPart(rel);
                PackagePart part_tgt;
                if (rel.RelationshipType.Equals(PackageRelationshipTypes.CORE_PROPERTIES))
                {
                    CopyProperties(pkg.GetPackageProperties(), dest.GetPackageProperties());
                    continue;
                }
                dest.AddRelationship(part.PartName, (TargetMode)rel.TargetMode, rel.RelationshipType);
                part_tgt = dest.CreatePart(part.PartName, part.ContentType);

                Stream out1 = part_tgt.GetOutputStream();
                IOUtils.Copy(part.GetInputStream(), out1);
                out1.Close();

                if (part.HasRelationships)
                {
                    Copy(pkg, part, dest, part_tgt);
                }
            }
            dest.Close();

            //the temp file will be deleted when JVM terminates
            //new File(path).deleteOnExit();
            return(OPCPackage.Open(path));
        }
示例#9
0
        public void TestTrailingSpacesInURI_53282()
        {
            OPCPackage pkg = null;

            using (Stream stream = OpenXml4NetTestDataSamples.OpenSampleStream("53282.xlsx"))
            {
                pkg = OPCPackage.Open(stream);
            }

            PackageRelationshipCollection sheetRels = pkg.GetPartsByName(new Regex("/xl/worksheets/sheet1.xml"))[0].Relationships;

            Assert.AreEqual(3, sheetRels.Size);
            PackageRelationship rId1 = sheetRels.GetRelationshipByID("rId1");

            Assert.AreEqual(TargetMode.External, rId1.TargetMode);
            Uri targetUri = rId1.TargetUri;

            Assert.AreEqual("mailto:[email protected]%C2%A0", targetUri.OriginalString);
            Assert.AreEqual("[email protected]\u00A0", targetUri.Scheme);

            MemoryStream out1 = new MemoryStream();

            pkg.Save(out1);


            pkg = OPCPackage.Open(new ByteArrayInputStream(out1.ToArray()));
            out1.Close();
            sheetRels = pkg.GetPartsByName(new Regex("/xl/worksheets/sheet1.xml"))[(0)].Relationships;
            Assert.AreEqual(3, sheetRels.Size);
            rId1 = sheetRels.GetRelationshipByID("rId1");
            Assert.AreEqual(TargetMode.External, rId1.TargetMode);
            targetUri = rId1.TargetUri;
            Assert.AreEqual("mailto:[email protected]%C2%A0", targetUri.OriginalString);
            Assert.AreEqual("[email protected]\u00A0", targetUri.Scheme);
        }
        private static Uri GetStructureUriFromRelationship(Uri contentUri, string relationshipName)
        {
            Uri result = null;

            if (contentUri != null && relationshipName != null)
            {
                Uri partUri = PackUriHelper.GetPartUri(contentUri);
                if (partUri != null)
                {
                    Uri     packageUri = PackUriHelper.GetPackageUri(contentUri);
                    Package package    = PreloadedPackages.GetPackage(packageUri);
                    if (package == null && SecurityHelper.CheckEnvironmentPermission())
                    {
                        package = PackageStore.GetPackage(packageUri);
                    }
                    if (package != null)
                    {
                        PackagePart part = package.GetPart(partUri);
                        PackageRelationshipCollection relationshipsByType = part.GetRelationshipsByType(relationshipName);
                        Uri uri = null;
                        foreach (PackageRelationship packageRelationship in relationshipsByType)
                        {
                            uri = PackUriHelper.ResolvePartUri(partUri, packageRelationship.TargetUri);
                        }
                        if (uri != null)
                        {
                            result = PackUriHelper.Create(packageUri, uri);
                        }
                    }
                }
            }
            return(result);
        }
示例#11
0
 private void LoadSpec()
 {
     if (originPart != null)
     {
         PackageRelationshipCollection relationships = originPart.GetRelationshipsByType(SPEC_RELATIONSHIP_TYPE);
         specPart = relationships?.Select(s => aasxPackage.GetPart(s.TargetUri))?.FirstOrDefault();
     }
 }
示例#12
0
        private static void CheckRelationships(string[] expected, PackageRelationshipCollection relationships)
        {
            HashSet <string> expectedRelationships = new HashSet <string>(expected);

            foreach (PackageRelationship relationship in relationships)
            {
                Assert.IsTrue(expectedRelationships.Remove(relationship.TargetUri.OriginalString));
            }
            Assert.IsTrue(expectedRelationships.Count == 0);
        }
示例#13
0
        protected void Rebase(OPCPackage pkg)
        {
            PackageRelationshipCollection relationshipsByType = this.packagePart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument");

            if (relationshipsByType.Size != 1)
            {
                throw new InvalidOperationException("Tried to rebase using http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument but found " + (object)relationshipsByType.Size + " parts of the right type");
            }
            this.packageRel  = relationshipsByType.GetRelationship(0);
            this.packagePart = this.packagePart.GetRelatedPart(this.packageRel);
        }
示例#14
0
        public void Process()
        {
            CollectSignatureDefinitions();
            PackageRelationshipCollection relationships = _package.GetRelationships();

            ProcessRelationsips(_package, relationships);
            PackagePartCollection parts = _package.GetParts();

            ProcessParts(parts);
            FixSignatureDefinitionsContentType();
        }
示例#15
0
 private String getCorePropertyURI(PackageRelationshipCollection packageRels, ref String sourceURI)
 {
     foreach (PackageRelationship packrel in packageRels)
     {
         if (packrel.Id.Equals("CoreProperties"))
         {
             sourceURI = packrel.SourceUri.ToString();
             return(packrel.TargetUri.ToString());
         }
     }
     throw new FormatException("Core properties is missing from the package!");
 }
示例#16
0
        private void LoadOrCreateOrigin()
        {
            PackageRelationshipCollection relationships = aasxPackage.GetRelationshipsByType(ORIGIN_RELATIONSHIP_TYPE);

            originPart = relationships?.Where(r => r.TargetUri == ORIGIN_URI)?.Select(p => aasxPackage.GetPart(p.TargetUri))?.FirstOrDefault();
            if (originPart == null)
            {
                originPart = aasxPackage.CreatePart(ORIGIN_URI, System.Net.Mime.MediaTypeNames.Text.Plain, CompressionOption.Maximum);
                originPart.GetStream(FileMode.Create).Dispose();
                aasxPackage.CreateRelationship(originPart.Uri, TargetMode.Internal, ORIGIN_RELATIONSHIP_TYPE);
            }
        }
示例#17
0
        public void Assert_50154(OPCPackage pkg)
        {
            Uri         drawingUri  = new Uri("/xl/drawings/drawing1.xml", UriKind.Relative);
            PackagePart drawingPart = pkg.GetPart(PackagingUriHelper.CreatePartName(drawingUri));
            PackageRelationshipCollection drawingRels = drawingPart.Relationships;

            Assert.AreEqual(6, drawingRels.Size);

            // expected one image
            Assert.AreEqual(1, drawingPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/image").Size);
            // and three hyperlinks
            Assert.AreEqual(5, drawingPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink").Size);

            PackageRelationship rId1 = drawingPart.GetRelationship("rId1");
            Uri parent = drawingPart.PartName.URI;
            Uri rel1   = new Uri(Path.Combine(parent.ToString(), rId1.TargetUri.ToString()), UriKind.Relative);
            Uri rel11  = PackagingUriHelper.RelativizeUri(drawingPart.PartName.URI, rId1.TargetUri);

            Assert.AreEqual("'Another Sheet'!A1", HttpUtility.UrlDecode(rel1.ToString().Split(new char[] { '#' })[1]));
            Assert.AreEqual("'Another Sheet'!A1", HttpUtility.UrlDecode(rel11.ToString().Split(new char[] { '#' })[1]));

            PackageRelationship rId2 = drawingPart.GetRelationship("rId2");
            Uri rel2 = PackagingUriHelper.RelativizeUri(drawingPart.PartName.URI, rId2.TargetUri);

            Assert.AreEqual("../media/image1.png", rel2.OriginalString);

            PackageRelationship rId3 = drawingPart.GetRelationship("rId3");
            Uri baseUri = new Uri("ooxml://npoi.org"); //For test only.
            Uri target  = new Uri(baseUri, rId3.TargetUri);

            Assert.AreEqual("#ThirdSheet!A1", target.Fragment);

            PackageRelationship rId4 = drawingPart.GetRelationship("rId4");

            target = new Uri(baseUri, rId4.TargetUri);
            Assert.AreEqual("#'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A1", HttpUtility.UrlDecode(target.Fragment));

            PackageRelationship rId5 = drawingPart.GetRelationship("rId5");
            //Uri rel5 = new Uri(Path.Combine(parent.ToString(), rId5.TargetUri.ToString()), UriKind.Relative);
            Uri rel5 = rId5.TargetUri;

            // back slashed have been Replaced with forward
            Assert.AreEqual("file:///D:/chan-chan.mp3", rel5.ToString());

            PackageRelationship rId6 = drawingPart.GetRelationship("rId6");
            //Uri rel6 = new Uri(ResolveRelativePath(parent.ToString(), HttpUtility.UrlDecode(rId6.TargetUri.ToString())), UriKind.Relative);
            Uri rel6 = rId6.TargetUri;

            Assert.AreEqual("../../../../../../../cygwin/home/yegor/dinom/&&&[access].2010-10-26.log", HttpUtility.UrlDecode(rel6.OriginalString.Split(new char[] { '#' })[0]));
            Assert.AreEqual("'\u0410\u043F\u0430\u0447\u0435 \u041F\u041E\u0418'!A5", HttpUtility.UrlDecode(rel6.OriginalString.Split(new char[] { '#' })[1]));
        }
示例#18
0
        private void ClearRelationshipsAndPartFromPackagePart(PackagePart sourcePackagePart, string relationshipType)
        {
            PackageRelationshipCollection relationships = sourcePackagePart.GetRelationshipsByType(relationshipType);

            foreach (var relationship in relationships.ToList())
            {
                sourcePackagePart.DeleteRelationship(relationship.Id);

                if (aasxPackage.PartExists(relationship.TargetUri))
                {
                    aasxPackage.DeletePart(relationship.TargetUri);
                }
            }
        }
示例#19
0
        protected PackagePart[] GetRelatedByType(string contentType)
        {
            PackageRelationshipCollection relationshipsByType = this.GetPackagePart().GetRelationshipsByType(contentType);

            PackagePart[] packagePartArray = new PackagePart[relationshipsByType.Size];
            int           index            = 0;

            foreach (PackageRelationship rel in relationshipsByType)
            {
                packagePartArray[index] = this.GetPackagePart().GetRelatedPart(rel);
                ++index;
            }
            return(packagePartArray);
        }
示例#20
0
        /**
         * When you open something like a theme, call this to
         *  re-base the XML Document onto the core child of the
         *  current core document
         */
        protected void Rebase(OPCPackage pkg)
        {
            PackageRelationshipCollection cores =
                packagePart.GetRelationshipsByType(coreDocumentRel);

            if (cores.Size != 1)
            {
                throw new InvalidOperationException(
                          "Tried to rebase using " + coreDocumentRel +
                          " but found " + cores.Size + " parts of the right type"
                          );
            }
            packagePart = packagePart.GetRelatedPart(cores.GetRelationship(0));
        }
示例#21
0
        private List <PackagePart> GetAllPackagePartsWithRelationshipType(string relType, PackagePart parent)
        {
            PackageRelationshipCollection rels = parent == null?Package.GetRelationshipsByType(relType) : parent.GetRelationshipsByType(relType);

            List <PackagePart> pkgList = new List <PackagePart>();

            foreach (PackageRelationship rel in rels)
            {
                if (rel.TargetMode == TargetMode.Internal)
                {
                    pkgList.Add(Package.GetPart(rel.TargetUri));
                }
            }
            return(pkgList);
        }
示例#22
0
        public void TestContentType()
        {
            String filepath = OpenXml4NetTestDataSamples.GetSampleFileName("sample.docx");
            // Retrieves core properties part
            OPCPackage p = OPCPackage.Open(filepath, PackageAccess.READ);
            PackageRelationshipCollection rels = p.GetRelationshipsByType(PackageRelationshipTypes.CORE_PROPERTIES);
            PackageRelationship           corePropertiesRelationship = rels.GetRelationship(0);
            PackagePart coreDocument = p.GetPart(corePropertiesRelationship);

            Assert.AreEqual("application/vnd.openxmlformats-package.core-properties+xml", coreDocument.ContentType);
            // TODO - finish writing this test
            Assume.That(false, "finish writing this test");

            ContentTypeManager ctm = new ZipContentTypeManager(coreDocument.GetInputStream(), p);
        }
示例#23
0
        /**
         * Retrieves all the PackageParts which are defined as
         *  relationships of the base document with the
         *  specified content type.
         */
        protected PackagePart[] GetRelatedByType(String contentType)
        {
            PackageRelationshipCollection partsC =
                GetPackagePart().GetRelationshipsByType(contentType);

            PackagePart[] parts = new PackagePart[partsC.Size];
            int           count = 0;

            foreach (PackageRelationship rel in partsC)
            {
                parts[count] = GetPackagePart().GetRelatedPart(rel);
                count++;
            }
            return(parts);
        }
示例#24
0
        /**
         * When you open something like a theme, call this to
         *  re-base the XML Document onto the core child of the
         *  current core document
         */
        protected void Rebase(OPCPackage pkg)
        {
            PackageRelationshipCollection cores =
                packagePart.GetRelationshipsByType(PackageRelationshipTypes.CORE_DOCUMENT);

            if (cores.Size != 1)
            {
                throw new InvalidOperationException(
                          "Tried to rebase using " + PackageRelationshipTypes.CORE_DOCUMENT +
                          " but found " + cores.Size + " parts of the right type"
                          );
            }
            packageRel  = cores.GetRelationship(0);
            packagePart = POIXMLDocument.GetTargetPart(pkg, packageRel);
        }
示例#25
0
        /**
         *  Fetches the InputStream to read the contents, based
         *  of the specified core part, for which we are defined
         *  as a suitable relationship
         */
        public Stream GetContents(PackagePart corePart)
        {
            PackageRelationshipCollection prc =
                corePart.GetRelationshipsByType(_relation);
            IEnumerator <PackageRelationship> it = prc.GetEnumerator();

            if (it.MoveNext())
            {
                PackageRelationship rel     = it.Current;
                PackagePartName     relName = PackagingUriHelper.CreatePartName(rel.TargetUri);
                PackagePart         part    = corePart.Package.GetPart(relName);
                return(part.GetInputStream());
            }
            log.Log(POILogger.WARN, "No part " + _defaultName + " found");
            return(null);
        }
示例#26
0
        private void ClearRelationshipAndPartFromPackage(string relationshipType, Uri targetUri)
        {
            PackageRelationshipCollection relationships = aasxPackage.GetRelationshipsByType(relationshipType);

            foreach (var relationship in relationships.ToList())
            {
                if (relationship.TargetUri == targetUri)
                {
                    aasxPackage.DeleteRelationship(relationship.Id);
                }
            }

            if (aasxPackage.PartExists(targetUri))
            {
                aasxPackage.DeletePart(targetUri);
            }
        }
示例#27
0
        public void TestSetVBAProject()
        {
            FileInfo file;

            byte[] allBytes = new byte[256];
            for (int i = 0; i < 256; i++)
            {
                allBytes[i] = (byte)(i - 128);
            }

            XSSFWorkbook wb1 = new XSSFWorkbook();

            wb1.CreateSheet();
            wb1.SetVBAProject(new ByteArrayInputStream(allBytes));
            file = TempFile.CreateTempFile("poi-", ".xlsm");
            Stream out1 = new FileStream(file.FullName, FileMode.Open, FileAccess.ReadWrite);

            wb1.Write(out1);
            out1.Close();
            wb1.Close();


            // Check the package contains what we'd expect it to
            OPCPackage  pkg    = OPCPackage.Open(file);
            PackagePart wbPart = pkg.GetPart(PackagingUriHelper.CreatePartName("/xl/workbook.xml"));

            Assert.IsTrue(wbPart.HasRelationships);
            PackageRelationshipCollection relationships = wbPart.Relationships.GetRelationships(XSSFRelation.VBA_MACROS.Relation);

            Assert.AreEqual(1, relationships.Size);
            Assert.AreEqual(XSSFRelation.VBA_MACROS.DefaultFileName, relationships.GetRelationship(0).TargetUri.ToString());
            PackagePart vbaPart = pkg.GetPart(PackagingUriHelper.CreatePartName(XSSFRelation.VBA_MACROS.DefaultFileName));

            Assert.IsNotNull(vbaPart);
            Assert.IsFalse(vbaPart.IsRelationshipPart);
            Assert.AreEqual(XSSFRelation.VBA_MACROS.ContentType, vbaPart.ContentType);
            byte[] fromFile = IOUtils.ToByteArray(vbaPart.GetInputStream());
            CollectionAssert.AreEqual(allBytes, fromFile);
            // Load back the XSSFWorkbook just to check nothing explodes
            XSSFWorkbook wb2 = new XSSFWorkbook(pkg);

            Assert.AreEqual(1, wb2.NumberOfSheets);
            Assert.AreEqual(XSSFWorkbookType.XLSM, wb2.WorkbookType);
            pkg.Close();
        }
示例#28
0
        private void ProcessRelationsips(object owner, PackageRelationshipCollection rels)
        {
            List <PackageRelationship> list = new List <PackageRelationship>();

            foreach (PackageRelationship item in rels)
            {
                list.Add(item);
            }
            if (owner is Package)
            {
                Package package = (Package)owner;
                foreach (PackageRelationship packageRelationship in list)
                {
                    package.DeleteRelationship(packageRelationship.Id);
                }
                using (List <PackageRelationship> .Enumerator enumerator2 = list.GetEnumerator())
                {
                    while (enumerator2.MoveNext())
                    {
                        PackageRelationship packageRelationship2 = enumerator2.Current;
                        package.CreateRelationship(packageRelationship2.TargetUri, packageRelationship2.TargetMode, _xpsConstants.ConvertRelationshipType(packageRelationship2.RelationshipType), packageRelationship2.Id);
                    }
                    return;
                }
            }
            if (owner is PackagePart)
            {
                PackagePart packagePart = (PackagePart)owner;
                foreach (PackageRelationship packageRelationship3 in list)
                {
                    packagePart.DeleteRelationship(packageRelationship3.Id);
                }
                using (List <PackageRelationship> .Enumerator enumerator2 = list.GetEnumerator())
                {
                    while (enumerator2.MoveNext())
                    {
                        PackageRelationship packageRelationship4 = enumerator2.Current;
                        packagePart.CreateRelationship(packageRelationship4.TargetUri, packageRelationship4.TargetMode, _xpsConstants.ConvertRelationshipType(packageRelationship4.RelationshipType), packageRelationship4.Id);
                    }
                    return;
                }
            }
            throw new ArgumentException("Owner must be a Package or a PackagePart instance.");
        }
示例#29
0
        private List <HtmlStore> ParseDocx(string fileName)
        {
            using (_package = Package.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                PackageRelationship rel     = _package.GetRelationships().Where(c => c.RelationshipType == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument").First();
                PackagePart         docPart = _package.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), rel.TargetUri));
                _docRels = docPart.GetRelationships();

                XDocument doc = null;
                using (Stream st = docPart.GetStream(FileMode.Open, FileAccess.Read))
                {
                    StreamReader sr = new StreamReader(st);
                    doc = XDocument.Load(sr, LoadOptions.None);
                    ParseDocument(doc);
                }
                if (!_isAnswerMode && _sb.Length > 0)
                {
                    string addStr = ReplaceWrongChars(_sb.ToString());
                    if (addStr.Length > 0)
                    {
                        AddQuestion(_sb.ToString());
                    }
                }
                else if (_isAnswerMode)
                {
                    AddAnswer(_sb.ToString());
                }
            }
            int index = 1;

            foreach (var quest in _questions)
            {
                quest.Html         = ReplaceWrongChars(ReplaceWrongChars(quest.Html.Replace(Environment.NewLine, "<br/>")));
                quest.QuestionType = QuestionTypeHelper.GetQuestionType(quest);
                quest.QuestIndex   = index;
                index++;
                foreach (var ans in quest.SubItems)
                {
                    ans.Html = ReplaceWrongChars(ReplaceWrongChars(ans.Html.Replace(Environment.NewLine, "<br/>")));
                }
            }
            _package.Close();
            return(_questions);
        }
示例#30
0
        public POIXMLProperties(OPCPackage docPackage)
        {
            this.pkg = docPackage;

            // Core properties
            core = new CoreProperties((PackagePropertiesPart)pkg.GetPackageProperties());

            // Extended properties
            PackageRelationshipCollection extRel =
                pkg.GetRelationshipsByType(PackageRelationshipTypes.EXTENDED_PROPERTIES);

            if (extRel.Size == 1)
            {
                extPart = pkg.GetPart(extRel.GetRelationship(0));
                ExtendedPropertiesDocument props = ExtendedPropertiesDocument.Parse(
                    extPart.GetInputStream()
                    );
                ext = new ExtendedProperties(props);
            }
            else
            {
                extPart = null;
                ext     = new ExtendedProperties((ExtendedPropertiesDocument)NEW_EXT_INSTANCE.Copy());
            }

            // Custom properties
            PackageRelationshipCollection custRel =
                pkg.GetRelationshipsByType(PackageRelationshipTypes.CUSTOM_PROPERTIES);

            if (custRel.Size == 1)
            {
                custPart = pkg.GetPart(custRel.GetRelationship(0));
                CustomPropertiesDocument props = CustomPropertiesDocument.Parse(
                    custPart.GetInputStream()
                    );
                cust = new CustomProperties(props);
            }
            else
            {
                custPart = null;
                cust     = new CustomProperties((CustomPropertiesDocument)NEW_CUST_INSTANCE.Copy());
            }
        }
示例#31
0
        private static void CheckRelationships(string[] expected, PackageRelationshipCollection relationships)
        {
            HashSet<string> expectedRelationships = new HashSet<string>(expected);

            foreach (PackageRelationship relationship in relationships)
                Assert.IsTrue(expectedRelationships.Remove(relationship.TargetUri.OriginalString));
            Assert.IsTrue(expectedRelationships.Count == 0);
        }
示例#32
0
        /**
         * Add a relationship to a part (except relationships part).
         * <p>
         * Check rule M1.25: The Relationships part shall not have relationships to
         * any other part. Package implementers shall enforce this requirement upon
         * the attempt to create such a relationship and shall treat any such
         * relationship as invalid.
         * </p>
         * @param targetPartName
         *            Name of the target part. This one must be relative to the
         *            source root directory of the part.
         * @param targetMode
         *            Mode [Internal|External].
         * @param relationshipType
         *            Type of relationship.
         * @param id
         *            Relationship unique id.
         * @return The newly created and added relationship
         * 
         * @throws InvalidFormatException
         *             If the URI point to a relationship part URI.
         * @see org.apache.poi.OpenXml4Net.opc.RelationshipSource#AddRelationship(org.apache.poi.OpenXml4Net.opc.PackagePartName,
         *      org.apache.poi.OpenXml4Net.opc.TargetMode, java.lang.String, java.lang.String)
         */
        public PackageRelationship AddRelationship(PackagePartName targetPartName,
                TargetMode targetMode, String relationshipType, String id)
        {
            _container.ThrowExceptionIfReadOnly();

            if (targetPartName == null)
            {
                throw new ArgumentException("targetPartName");
            }
            //if (targetMode == null)
            //{
            //    throw new ArgumentException("targetMode");
            //}
            if (relationshipType == null)
            {
                throw new ArgumentException("relationshipType");
            }

            if (this.IsRelationshipPart || targetPartName.IsRelationshipPartURI())
            {
                throw new InvalidOperationException(
                        "Rule M1.25: The Relationships part shall not have relationships to any other part.");
            }

            if (_relationships == null)
            {
                _relationships = new PackageRelationshipCollection();
            }

            return _relationships.AddRelationship(targetPartName.URI,
                    targetMode, relationshipType, id);
        }
示例#33
0
        /**
         * Save relationships into the part.
         *
         * @param rels
         *            The relationships collection to marshall.
         * @param relPartName
         *            Part name of the relationship part to marshall.
         * @param zos
         *            Zip output stream in which to save the XML content of the
         *            relationships serialization.
         */
        public static bool MarshallRelationshipPart(
                PackageRelationshipCollection rels, PackagePartName relPartName,
                ZipOutputStream zos)
        {
            // Building xml
            XmlDocument xmlOutDoc = new XmlDocument();
            // make something like <Relationships
            // xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
            System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xmlOutDoc.NameTable);
            xmlnsManager.AddNamespace("x", PackageNamespaces.RELATIONSHIPS);

            XmlNode root = xmlOutDoc.AppendChild(xmlOutDoc.CreateElement(PackageRelationship.RELATIONSHIPS_TAG_NAME, PackageNamespaces.RELATIONSHIPS));

            // <Relationship
            // TargetMode="External"
            // Id="rIdx"
            // Target="http://www.custom.com/images/pic1.jpg"
            // Type="http://www.custom.com/external-resource"/>

            Uri sourcePartURI = PackagingUriHelper
                    .GetSourcePartUriFromRelationshipPartUri(relPartName.URI);

            foreach (PackageRelationship rel in rels)
            {
                // the relationship element
                XmlElement relElem = xmlOutDoc.CreateElement(PackageRelationship.RELATIONSHIP_TAG_NAME,PackageNamespaces.RELATIONSHIPS);

                // the relationship ID
                relElem.SetAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel.Id);

                // the relationship Type
                relElem.SetAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel
                        .RelationshipType);

                // the relationship Target
                String targetValue;
                Uri uri = rel.TargetUri;
                if (rel.TargetMode == TargetMode.External)
                {
                    // Save the target as-is - we don't need to validate it,
                    //  alter it etc
                    targetValue = uri.OriginalString;

                    // add TargetMode attribute (as it is external link external)
                    relElem.SetAttribute(
                            PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME,
                            "External");
                }
                else
                {
                    targetValue = PackagingUriHelper.RelativizeUri(
                            sourcePartURI, rel.TargetUri, true).ToString();
                }
                relElem.SetAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME,
                        targetValue);
                xmlOutDoc.DocumentElement.AppendChild(relElem);
            }

            xmlOutDoc.Normalize();

            // String schemaFilename = Configuration.getPathForXmlSchema()+
            // File.separator + "opc-relationships.xsd";

            // Save part in zip
            ZipEntry ctEntry = new ZipEntry(ZipHelper.GetZipURIFromOPCName(
                    relPartName.URI.ToString()).OriginalString);
            try
            {
                zos.PutNextEntry(ctEntry);

                StreamHelper.SaveXmlInStream(xmlOutDoc, zos);
                zos.CloseEntry();
            }
            catch (IOException e)
            {
                logger.Log(POILogger.ERROR,"Cannot create zip entry " + relPartName, e);
                return false;
            }
            return true; // success
        }
示例#34
0
        /**
         * Remove a part from this package as well as its relationship part, if one
         * exists, and all parts listed in the relationship part. Be aware that this
         * do not delete relationships which target the specified part.
         * 
         * @param PartName
         *            The name of the part to delete.
         * @throws InvalidFormatException
         *             Throws if the associated relationship part of the specified
         *             part is not valid.
         */
        public void RemovePartRecursive(PackagePartName PartName)
        {
            // Retrieves relationship part, if one exists
            PackagePart relPart = this.partList[PackagingUriHelper
                    .GetRelationshipPartName(PartName)];
            // Retrieves PackagePart object from the package
            PackagePart partToRemove = this.partList[PartName];

            if (relPart != null)
            {
                PackageRelationshipCollection partRels = new PackageRelationshipCollection(
                        partToRemove);
                foreach (PackageRelationship rel in partRels)
                {
                    PackagePartName PartNameToRemove = PackagingUriHelper
                            .CreatePartName(PackagingUriHelper.ResolvePartUri(rel
                                    .SourceUri, rel.TargetUri));
                    RemovePart(PartNameToRemove);
                }

                // Finally delete its relationship part if one exists
                this.RemovePart(relPart.PartName);
            }

            // Delete the specified part
            this.RemovePart(partToRemove.PartName);
        }
示例#35
0
 /**
  * Ensure the package relationships collection instance is built.
  * 
  * @throws InvalidFormatException
  *             Throws if
  */
 private void LoadRelationships()
 {
     if (this.relationships == null && !this.IsRelationshipPart)
     {
         this.ThrowExceptionIfRelationship();
         relationships = new PackageRelationshipCollection(this);
     }
 }
示例#36
0
        /**
         * Add a relationship to a part (except relationships part).
         * <p>
         * Check rule M1.25: The Relationships part shall not have relationships to
         * any other part. Package implementers shall enforce this requirement upon
         * the attempt to create such a relationship and shall treat any such
         * relationship as invalid.
         * </p>
         * @param targetURI
         *            URI of the target part. Must be relative to the source root
         *            directory of the part.
         * @param targetMode
         *            Mode [Internal|External].
         * @param relationshipType
         *            Type of relationship.
         * @param id
         *            Relationship unique id.
         * @return The newly created and added relationship
         * 
         * @throws InvalidFormatException
         *             If the URI point to a relationship part URI.
         * @see org.apache.poi.OpenXml4Net.opc.RelationshipSource#AddRelationship(org.apache.poi.OpenXml4Net.opc.PackagePartName,
         *      org.apache.poi.OpenXml4Net.opc.TargetMode, java.lang.String, java.lang.String)
         */
        public PackageRelationship AddRelationship(Uri targetURI,
                TargetMode targetMode, String relationshipType, String id)
        {
            container.ThrowExceptionIfReadOnly();

            if (targetURI == null)
            {
                throw new ArgumentException("targetPartName");
            }
            //if (targetMode == null)
            //{
            //    throw new ArgumentException("targetMode");
            //}
            if (relationshipType == null)
            {
                throw new ArgumentException("relationshipType");
            }

            // Try to retrieve the target part

            if (this.IsRelationshipPart
                    || PackagingUriHelper.IsRelationshipPartURI(targetURI))
            {
                throw new InvalidOperationException(
                        "Rule M1.25: The Relationships part shall not have relationships to any other part.");
            }

            if (relationships == null)
            {
                relationships = new PackageRelationshipCollection();
            }

            return relationships.AddRelationship(targetURI,
                    targetMode, relationshipType, id);
        }
示例#37
0
 /**
  * Implementation of the getRelationships method().
  * 
  * @param filter
  *            Relationship type filter. If <i>null</i> then the filter is
  *            disabled and return all the relationships.
  * @return All relationships from this part that have the specified type.
  * @throws InvalidFormatException
  *             Throws if an error occurs during parsing the relationships
  *             part.
  * @throws InvalidOperationException
  *             Throws if the package is open en write only mode.
  * @see #getRelationshipsByType(String)
  */
 private PackageRelationshipCollection GetRelationshipsCore(String filter)
 {
     this.container.ThrowExceptionIfWriteOnly();
     if (relationships == null)
     {
         this.ThrowExceptionIfRelationship();
         relationships = new PackageRelationshipCollection(this);
     }
     return new PackageRelationshipCollection(relationships, filter);
 }
示例#38
0
        /**
         * Adds an external relationship to a part (except relationships part).
         * 
         * The targets of external relationships are not subject to the same
         * validity checks that internal ones are, as the contents is potentially
         * any file, URL or similar.
         * 
         * @param target
         *            External target of the relationship
         * @param relationshipType
         *            Type of relationship.
         * @param id
         *            Relationship unique id.
         * @return The newly created and added relationship
         * @see org.apache.poi.OpenXml4Net.opc.RelationshipSource#addExternalRelationship(java.lang.String,
         *      java.lang.String)
         */
        public PackageRelationship AddExternalRelationship(String target,
                String relationshipType, String id)
        {
            if (target == null)
            {
                throw new ArgumentException("target");
            }
            if (relationshipType == null)
            {
                throw new ArgumentException("relationshipType");
            }

            if (relationships == null)
            {
                relationships = new PackageRelationshipCollection();
            }

            Uri targetURI;
            try
            {
                targetURI = new Uri(target,UriKind.RelativeOrAbsolute);
            }
            catch (UriFormatException e)
            {
                throw new ArgumentException("Invalid target - " + e);
            }

            return relationships.AddRelationship(targetURI, TargetMode.External,
                    relationshipType, id);
        }
示例#39
0
 /**
  * Ensure that the relationships collection is not null.
  */
 public void EnsureRelationships()
 {
     if (this.relationships == null)
     {
         try
         {
             this.relationships = new PackageRelationshipCollection(this);
         }
         catch (InvalidFormatException)
         {
             this.relationships = new PackageRelationshipCollection();
         }
     }
 }
        /// <summary> 
        /// Visit relationships without disturbing the PackageRelationshipCollection iterator 
        /// </summary>
        /// <param name="relationships">collection of relationships to visit</param> 
        /// <param name="visit">function to call with each relationship in the list</param>
        /// <param name="context">context object - may be null</param>
        private void SafeVisitRelationships(PackageRelationshipCollection relationships, RelationshipOperation visit, Object context)
        { 
            // make a local copy that will not be invalidated by any activity of the visitor function
            List<PackageRelationship> relationshipsToVisit = new List<PackageRelationship>(relationships); 
 
            // now invoke the delegate for each member
            for (int i = 0; i < relationshipsToVisit.Count; i++) 
            {
                // exit if visitor wants us to
                if (!visit(relationshipsToVisit[i], context))
                    break; 
            }
        } 
 /// <summary>
 /// Visit relationships without disturbing the PackageRelationshipCollection iterator 
 /// </summary> 
 /// <param name="relationships">collection of relationships to visit</param>
 /// <param name="visit">function to call with each relationship in the list</param> 
 private void SafeVisitRelationships(PackageRelationshipCollection relationships, RelationshipOperation visit)
 {
     SafeVisitRelationships(relationships, visit, null);
 } 
示例#42
0
		public PackageRelationshipCollection GetRelationshipsByType (string relationshipType)
		{
			CheckIsRelationship ();
			PackageRelationshipCollection collection = new PackageRelationshipCollection ();
			foreach (PackageRelationship r in Relationships.Values)
				if (r.RelationshipType == relationshipType)
					collection.Relationships.Add (r);
			
			return collection;
		}