// find the content type of a part in the package
        private string findContentType(ZipReader reader, string target)
        {
            // get extension without leading '.'
            string    extension    = Path.GetExtension(target).Substring(1);
            Stream    contentTypes = reader.GetEntry(OOX_CONTENT_TYPE_FILE);
            XmlReader r            = XmlReader.Create(contentTypes);
            bool      overrided    = false;
            string    contentType  = null;

            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element)
                {
                    if (r.LocalName.Equals("Default") && r.GetAttribute("Extension").Equals(extension) && !overrided)
                    {
                        contentType = r.GetAttribute("ContentType");
                    }
                    else if (r.LocalName.Equals("Override") && r.GetAttribute("PartName").Equals(target))
                    {
                        overrided   = true;
                        contentType = r.GetAttribute("ContentType");
                    }
                }
            }
            if (contentType == null)
            {
                throw new ValidationException("Content type not found for " + target);
            }
            return(contentType);
        }
Beispiel #2
0
        // find the content type of a part in the package
        private String findContentType(ZipReader reader, String target)
        {
            String extension = null;

            if (target.IndexOf(".") != -1)
            {
                extension = target.Substring(target.IndexOf(".") + 1);
            }
            Stream    contentTypes = reader.GetEntry(OOX_CONTENT_TYPE_FILE);
            XmlReader r            = XmlReader.Create(contentTypes);
            bool      overrided    = false;
            String    contentType  = null;

            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element)
                {
                    if (r.LocalName == "Default" && extension != null && r.GetAttribute("Extension") == extension && !overrided)
                    {
                        contentType = r.GetAttribute("ContentType");
                    }
                    else if (r.LocalName == "Override" && r.GetAttribute("PartName") == target)
                    {
                        overrided   = true;
                        contentType = r.GetAttribute("ContentType");
                    }
                }
            }
            if (contentType == null)
            {
                throw new NotAnOoxDocumentException("Content type not found for " + target);
                //throw new PptxValidatorException("Content type not found for " + target);
            }
            return(contentType);
        }
Beispiel #3
0
        public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
        {
            try
            {
                Stream stream = null;

                if (entries.Contains(absoluteUri.AbsoluteUri))
                {
                    stream = archive.GetEntry((string)entries[absoluteUri.AbsoluteUri]);
                }
                if (stream == null)
                {
                    stream = new MemoryStream();
                }
                // Cannot have a 0 byte xml document !
                else if (stream.Length == 0)
                {
                    throw new IOException(entries[absoluteUri.AbsoluteUri] + " is 0 length");
                }
                return(stream);
            }
            catch (Exception)
            {
                // failsafe on a dummy xml document
                return(EmbeddedResourceResolver.GetSharedResource("source.xml"));
            }
        }
Beispiel #4
0
        private static PackageProject ExtractPackageProject(string fileName)
        {
            PackageProject packageProject = null;

            using (var packageReader = new ZipReader(fileName))
            {
                var packageEntry = packageReader.GetEntry("package.zip");
                using (var memoryStream = new MemoryStream())
                {
                    StreamUtils.CopyStream(packageEntry.GetStream(), memoryStream, 0x4000);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new ZipReader(memoryStream))
                    {
                        foreach (var entry in reader.Entries)
                        {
                            if (!entry.Name.Is(Constants.ProjectKey))
                            {
                                continue;
                            }

                            packageProject = IOUtils.LoadSolution(StreamUtil.LoadString(entry.GetStream()));
                            break;
                        }
                    }
                }
            }

            return(packageProject);
        }
Beispiel #5
0
        /// <summary>
        ///  main transform which needs the orginal File
        /// </summary>
        /// <param name="directionXSL">transform direction</param>
        /// <param name="resourceResolver">xsl location</param>
        /// <param name="originalFile">original File</param>
        /// <param name="inputFile">File after pretreatment</param>
        /// <param name="outputFile">output file</param>
        protected void MainTransform(string directionXSL, XmlUrlResolver resourceResolver, string originalFile, string inputFile, string outputFile)
        {
            XPathDocument     xslDoc;
            XmlReaderSettings xrs            = new XmlReaderSettings();
            XmlReader         source         = null;
            XmlWriter         writer         = null;
            OoxZipResolver    zipResolver    = null;
            string            zipXMLFileName = "input.xml";

            try
            {
                //xrs.ProhibitDtd = true;

                xslDoc          = new XPathDocument(((ResourceResolver)resourceResolver).GetInnerStream(directionXSL));
                xrs.XmlResolver = resourceResolver;
                string    sr      = ZipXMLFile(inputFile);
                ZipReader archive = ZipFactory.OpenArchive(sr);
                source = XmlReader.Create(archive.GetEntry(zipXMLFileName));

                XslCompiledTransform xslt     = new XslCompiledTransform();
                XsltSettings         settings = new XsltSettings(true, false);
                xslt.Load(xslDoc, settings, resourceResolver);

                if (!originalFile.Equals(string.Empty))
                {
                    zipResolver = new OoxZipResolver(originalFile, resourceResolver);
                }
                XsltArgumentList parameters = new XsltArgumentList();
                parameters.XsltMessageEncountered += new XsltMessageEncounteredEventHandler(MessageCallBack);

                // zip format
                parameters.AddParam("outputFile", "", outputFile);
                // writer = new OoxZipWriter(inputFile);
                writer = new UofZipWriter(outputFile);

                if (zipResolver != null)
                {
                    xslt.Transform(source, parameters, writer, zipResolver);
                }
                else
                {
                    xslt.Transform(source, parameters, writer);
                }
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
                if (source != null)
                {
                    source.Close();
                }
            }
        }
Beispiel #6
0
        public List <SyncItem> LoadItems()
        {
            var items = new List <SyncItem>();

            using (new SecurityDisabler())
            {
                using (new ProxyDisabler())
                {
                    var      reader = new ZipReader(PackagePath, Encoding.UTF8);
                    ZipEntry entry  = reader.GetEntry("package.zip");

                    using (var stream = new MemoryStream())
                    {
                        StreamUtil.Copy(entry.GetStream(), stream, 0x4000);

                        reader = new ZipReader(stream);

                        foreach (ZipEntry zipEntry in reader.Entries)
                        {
                            var entryData = new ZipEntryData(zipEntry);
                            try
                            {
                                if (entryData.Key.EndsWith("/xml"))
                                {
                                    string xml =
                                        new StreamReader(entryData.GetStream().Stream, Encoding.UTF8).ReadToEnd();
                                    if (!string.IsNullOrWhiteSpace(xml))
                                    {
                                        XmlDocument document = XmlUtil.LoadXml(xml);
                                        if (document != null)
                                        {
                                            SyncItem loadedItem = LoadItem(document);
                                            if (loadedItem != null)
                                            {
                                                items.Add(loadedItem);
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                Console.WriteLine("Unable to load xml from file {0}", entryData.Key);
                            }
                        }
                    }
                }
            }

            Console.WriteLine("Read {0} items from package {1}", items.Count, PackagePath);

            return(items);
        }
        public List<SyncItem> LoadItems()
        {
            var items = new List<SyncItem>();

            using (new SecurityDisabler())
            {
                using (new ProxyDisabler())
                {
                    var reader = new ZipReader(PackagePath, Encoding.UTF8);
                    ZipEntry entry = reader.GetEntry("package.zip");

                    using (var stream = new MemoryStream())
                    {
                        StreamUtil.Copy(entry.GetStream(), stream, 0x4000);

                        reader = new ZipReader(stream);

                        foreach (ZipEntry zipEntry in reader.Entries)
                        {
                            var entryData = new ZipEntryData(zipEntry);
                            try
                            {
                                if (entryData.Key.EndsWith("/xml"))
                                {
                                    string xml =
                                        new StreamReader(entryData.GetStream().Stream, Encoding.UTF8).ReadToEnd();
                                    if (!string.IsNullOrWhiteSpace(xml))
                                    {
                                        XmlDocument document = XmlUtil.LoadXml(xml);
                                        if (document != null)
                                        {
                                            SyncItem loadedItem = LoadItem(document);
                                            if (loadedItem != null)
                                            {
                                                items.Add(loadedItem);
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                Console.WriteLine("Unable to load xml from file {0}", entryData.Key);
                            }
                        }
                    }
                }
            }

            Console.WriteLine("Read {0} items from package {1}", items.Count, PackagePath);

            return items;
        }
Beispiel #8
0
        /// <summary>
        /// Get the relations for the specified part.
        /// </summary>
        /// <param name="zipReader">ZipReader for reading from the OOXML package</param>
        /// <param name="forPartPath">Part for which to get relations</param>
        /// <returns>List of Relationship nodes belonging to forFile</returns>
        protected static XmlNodeList GetRelations(ZipReader zipReader, String forPartPath)
        {
            string relPath   = GetRelationPath(forPartPath);
            Stream relStream = zipReader.GetEntry(relPath);

            XmlDocument relDocument = new XmlDocument();

            relDocument.Load(relStream);

            XmlNodeList rels = relDocument["Relationships"].GetElementsByTagName("Relationship");

            return(rels);
        }
Beispiel #9
0
        public PackageManifest GetManifest(string filename)
        {
            var manifest = new PackageManifest();

            ZipReader reader;

            try
            {
                reader = new ZipReader(filename, Encoding.UTF8);
            }
            catch (Exception exception)
            {
                throw new InvalidOperationException("Failed to open package", exception);
            }

            string   tempFileName = Path.GetTempFileName();
            ZipEntry entry        = reader.GetEntry("package.zip");

            if (entry != null)
            {
                using (FileStream stream = File.Create(tempFileName))
                {
                    StreamUtil.Copy(entry.GetStream(), stream, 0x4000);
                }
                reader.Dispose();
                reader = new ZipReader(tempFileName, Encoding.UTF8);
            }
            try
            {
                foreach (ZipEntry entry2 in reader.Entries)
                {
                    var data = new ZipEntryData(entry2);

                    var packageManifestEntry = ZipEntryDataParser.GetManifestEntry(data.Key);

                    if (!(packageManifestEntry is PackageManifestEntryNotFound))
                    {
                        manifest.Entries.Add(packageManifestEntry);
                    }
                }
            }
            finally
            {
                reader.Dispose();
                File.Delete(tempFileName);
            }

            return(manifest);
        }
Beispiel #10
0
        /// <summary>
        /// Method that extracts the actual XmlElement that will be used as this XmlContainer's
        /// XmlDocumentElement based on the relations and a ZipReader for the OOXML package.
        ///
        /// The default implementation simply returns the root of the first referenced part if
        /// there is only one part.
        ///
        /// Override this in subclasses to implement behaviour for more complex cases.
        /// </summary>
        /// <param name="zipReader">ZipReader for reading from the OOXML package</param>
        /// <param name="rels">List of Relationship nodes belonging to root part</param>
        /// <returns>The XmlElement that will become this record's XmlDocumentElement</returns>
        protected virtual XmlElement ExtractDocumentElement(ZipReader zipReader, XmlNodeList rels)
        {
            if (rels.Count != 1)
            {
                throw new Exception("Expected actly one Relationship in XmlContainer OOXML doc");
            }

            string partPath   = rels[0].Attributes["Target"].Value;
            Stream partStream = zipReader.GetEntry(partPath);

            XmlDocument partDoc = new XmlDocument();

            partDoc.Load(partStream);

            return(partDoc.DocumentElement);
        }
        public PackageManifest GetManifest(string filename)
        {
            var manifest = new PackageManifest();

            ZipReader reader;
            try
            {
                reader = new ZipReader(filename, Encoding.UTF8);
            }
            catch (Exception exception)
            {          
                throw new InvalidOperationException("Failed to open package", exception);
            }

            string tempFileName = Path.GetTempFileName();
            ZipEntry entry = reader.GetEntry("package.zip");
            if (entry != null)
            {
                using (FileStream stream = File.Create(tempFileName))
                {
                    StreamUtil.Copy(entry.GetStream(), stream, 0x4000);
                }
                reader.Dispose();
                reader = new ZipReader(tempFileName, Encoding.UTF8);
            }
            try
            {
                foreach (ZipEntry entry2 in reader.Entries)
                {
                    var data = new ZipEntryData(entry2);

                    var packageManifestEntry = ZipEntryDataParser.GetManifestEntry(data.Key);

                    if (! (packageManifestEntry is PackageManifestEntryNotFound))
                    {
                        manifest.Entries.Add(packageManifestEntry);
                    }
                }
            }
            finally
            {
                reader.Dispose();
                File.Delete(tempFileName);
            }

            return manifest;
        }
Beispiel #12
0
        public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
        {
            Stream stream = null;

            if (entries.Contains(absoluteUri.AbsoluteUri))
            {
                string relativepathinpackage = (string)entries[absoluteUri.AbsoluteUri];
                stream = archive.GetEntry(relativepathinpackage);
            }

            if (stream == null)
            {
                return(base.GetEntity(absoluteUri, role, ofObjectToReturn));
            }

            return(stream);
        }
        public AntidotePackageDefinition GetSources()
        {
            var itemsIds  = new List <AntidoteItemSourceDefinition>();
            var filesInfo = new List <AntidoteFileSourceDefinition>();

            ZipReader zipReader    = new ZipReader(filename, Encoding.UTF8);
            string    tempFileName = Path.GetTempFileName();
            ZipEntry  entry1       = zipReader.GetEntry("package.zip");

            if (entry1 != null)
            {
                using (FileStream fileStream = File.Create(tempFileName))
                    StreamUtil.Copy(entry1.GetStream(), fileStream, 16384);
                zipReader.Dispose();
                zipReader = new ZipReader(tempFileName, Encoding.UTF8);
            }
            try
            {
                foreach (ZipEntry entry2 in zipReader.Entries)
                {
                    if (entry2.IsItem())
                    {
                        itemsIds.Add((AntidoteItemSourceDefinition)entry2);
                    }
                    if (entry2.IsFile())
                    {
                        string filePath = Path.Combine(HostingEnvironment.ApplicationHost.GetPhysicalPath(), entry2.GetFilePath());
                        filesInfo.Add(new AntidoteFileSourceDefinition {
                            FileInfo = new FileInfo(filePath)
                        });
                    }
                }
                return(new AntidotePackageDefinition
                {
                    FilesInfo = filesInfo,
                    ItemsId = itemsIds.Distinct()
                });
            }
            finally
            {
                zipReader.Dispose();
                File.Delete(tempFileName);
            }
        }
        private void Read([NotNull] string fileName)
        {
            Debug.ArgumentNotNull(fileName, nameof(fileName));

            using (var reader = new ZipReader(fileName))
            {
                var zipEntry = reader.GetEntry(@"package.zip");
                if (zipEntry != null)
                {
                    ReadPackage(zipEntry.GetStream());
                    return;
                }

                foreach (var entry in reader.Entries)
                {
                    ReadEntry(entry);
                }
            }
        }
Beispiel #15
0
        /// <summary>
        /// Method that extracts the actual XmlElement that will be used as this XmlContainer's
        /// XmlDocumentElement based on the relations and a ZipReader for the OOXML package.
        ///
        /// The default implementation simply returns the root of the first referenced part if
        /// there is only one part.
        ///
        /// Override this in subclasses to implement behaviour for more complex cases.
        /// </summary>
        /// <param name="zipReader">ZipReader for reading from the OOXML package</param>
        /// <param name="rootRels">List of Relationship nodes belonging to root part</param>
        /// <returns>The XmlElement that will become this record's XmlDocumentElement</returns>
        protected override XmlElement ExtractDocumentElement(ZipReader zipReader, XmlNodeList rootRels)
        {
            if (rootRels.Count != 1)
            {
                throw new Exception("Expected actly one Relationship in Theme OOXML doc");
            }

            String      managerPath      = rootRels[0].Attributes["Target"].Value;
            String      managerDirectory = Path.GetDirectoryName(managerPath).Replace("\\", "/");
            XmlNodeList managerRels;

            try
            {
                managerRels = GetRelations(zipReader, managerPath);
            }
            catch (Exception)
            {
                this.XmlDocumentElement = null;
                return(null);
            }



            if (managerRels.Count != 1)
            {
                throw new Exception("Expected actly one Relationship for Theme manager");
            }

            String partPath   = String.Format("{0}/{1}", managerDirectory, managerRels[0].Attributes["Target"].Value);
            Stream partStream = zipReader.GetEntry(partPath);

            XmlDocument partDoc = new XmlDocument();

            partDoc.Load(partStream);

            XmlNode e = partDoc.DocumentElement;

            DIaLOGIKa.b2xtranslator.Tools.Utils.replaceOutdatedNamespaces(ref e);

            return((XmlElement)e);
        }
Beispiel #16
0
        public void ValidateRels(string partDir, XmlReader r)
        {
            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element && r.LocalName == "Relationship")
                {
                    String target = partDir + "/" + r.GetAttribute("Target");
                    if (target != "ppt/pmPRSettings.xml")
                    {
                        // Added by lohith - if a file is external no need to have it within package
                        if (!(r.GetAttribute("TargetMode") == "External"))
                        {
                            // Is the target item exist in the package ?
                            Stream item = null;

                            try
                            {
                                item = reader.GetEntry(target);
                            }
                            catch (Exception)
                            {
                                throw new NotAnOoxDocumentException("The file \"" + target + "\" is described in the \"/ppt/_rels/presentation.xml.rels\" file but does not exist in the package.");
                                //throw new PptxValidatorException("The file \"" + target + "\" is described in the \"/ppt/_rels/presentation.xml.rels\" file but does not exist in the package.");
                            }

                            // 5.1. A content type can be found in [Content_Types].xml file
                            if (target.IndexOf("../") == -1)
                            {
                                String ct = this.findContentType(reader, "/" + target);

                                // 5.2. If it's an xml file, it has to be valid
                                if (ct.EndsWith("+xml"))
                                {
                                    this.validateXml(item);
                                }
                            }
                        }
                    }
                }
            }
        }
        public AntidotePackageDefinition GetSources()
        {
            var itemsIds = new List<AntidoteItemSourceDefinition>();
            var filesInfo = new List<AntidoteFileSourceDefinition>();

            ZipReader zipReader = new ZipReader(filename, Encoding.UTF8);
            string tempFileName = Path.GetTempFileName();
            ZipEntry entry1 = zipReader.GetEntry("package.zip");
            if (entry1 != null)
            {
                using (FileStream fileStream = File.Create(tempFileName))
                    StreamUtil.Copy(entry1.GetStream(), fileStream, 16384);
                zipReader.Dispose();
                zipReader = new ZipReader(tempFileName, Encoding.UTF8);
            }
            try
            {
                foreach (ZipEntry entry2 in zipReader.Entries)
                {
                    if (entry2.IsItem())
                    {
                        itemsIds.Add((AntidoteItemSourceDefinition)entry2);
                    }
                    if (entry2.IsFile())
                    {
                        string filePath = Path.Combine(HostingEnvironment.ApplicationHost.GetPhysicalPath(), entry2.GetFilePath());
                        filesInfo.Add(new AntidoteFileSourceDefinition { FileInfo = new FileInfo(filePath) });
                    }
                }
                return new AntidotePackageDefinition
                {
                        FilesInfo = filesInfo,
                        ItemsId = itemsIds.Distinct()
                    };
            }
            finally
            {
                zipReader.Dispose();
                File.Delete(tempFileName);
            }
        }
Beispiel #18
0
        // Code to verify whether a file is valid pptx file or not
        //bug number:1698280
        //Code chcanges 2 of 2
        private bool validatePptx(ZipReader reader)
        {
            Stream    contentTypes = reader.GetEntry(OOX_CONTENT_TYPE_FILE);
            XmlReader r            = XmlReader.Create(contentTypes);

            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element && r.LocalName == "Override")
                {
                    if (r.GetAttribute("ContentType").Equals("application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml") ||
                        r.GetAttribute("ContentType").Equals("application/vnd.openxmlformats-officedocument.presentationml.template.main+xml") ||
                        r.GetAttribute("ContentType").Equals("application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml") ||
                        r.GetAttribute("ContentType").Equals("application/vnd.ms-powerpoint.template.macroEnabled.main+xml"))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
        protected virtual ZipReader OpenPackageFile([NotNull] string fileName)
        {
            var zipReader = new ZipReader(fileName, Encoding.UTF8);

            var entry = zipReader.GetEntry("package.zip");

            if (entry == null)
            {
                return(zipReader);
            }

            var tempFileName = Path.GetTempFileName();

            using (var fileStream = File.Create(tempFileName))
            {
                entry.GetStream().CopyTo(fileStream);
            }

            zipReader.Dispose();

            return(new ZipReader(tempFileName, Encoding.UTF8));
        }
Beispiel #20
0
        protected virtual void CopyLevel(ZipReader archive, string relFile, XmlTextWriter xtw, List <string> namespaces)
        {
            XmlReader           reader;
            List <RelationShip> rels;
            XmlReaderSettings   xrs = new XmlReaderSettings();

            xrs.IgnoreWhitespace = false;

            try
            {
                // copy relationship part and extract relationships
                reader = XmlReader.Create(archive.GetEntry(relFile));

                if (!_copiedParts.ContainsKey(relFile))
                {
                    xtw.WriteStartElement(NS_PREFIX, "part", PACKAGE_NS);
                    xtw.WriteAttributeString(NS_PREFIX, "name", PACKAGE_NS, relFile);
                    xtw.WriteAttributeString(NS_PREFIX, "type", PACKAGE_NS, RELATIONSHIP_NS);
                    rels = CopyPart(reader, xtw, RELATIONSHIP_NS, relFile, archive);
                    _copiedParts.Add(relFile, true);
                    reader.Close();
                    xtw.WriteEndElement();
                    xtw.Flush();

                    // copy referenced parts
                    foreach (RelationShip rel in rels)
                    {
                        if (namespaces.Contains(rel.Type))
                        {
                            try
                            {
                                string basePath = relFile.Substring(0, relFile.LastIndexOf("_rels/"));
                                string path     = rel.Target.Substring(0, rel.Target.LastIndexOf('/') + 1);
                                string file     = rel.Target.Substring(rel.Target.LastIndexOf('/') + 1);

                                path = CombinePath(basePath, path);
                                // if there is a relationship part for the current part
                                // copy relationships and referenced files recursively
                                CopyLevel(archive, path + "_rels/" + file + ".rels", xtw, namespaces);

                                string partName = CombinePath(basePath, rel.Target);
                                reader = XmlReader.Create(archive.GetEntry(basePath + rel.Target));

                                if (!_copiedParts.ContainsKey(partName))
                                {
                                    xtw.WriteStartElement(NS_PREFIX, "part", PACKAGE_NS);
                                    xtw.WriteAttributeString(NS_PREFIX, "name", PACKAGE_NS, partName);
                                    xtw.WriteAttributeString(NS_PREFIX, "type", PACKAGE_NS, rel.Type);
                                    xtw.WriteAttributeString(NS_PREFIX, "rId", PACKAGE_NS, rel.Id);

                                    CopyPart(reader, xtw, rel.Type, partName, archive);
                                    _copiedParts.Add(partName, true);
                                    reader.Close();

                                    xtw.WriteEndElement();
                                    xtw.Flush();
                                }
                            }
                            catch (ZipEntryNotFoundException)
                            {
                            }
                        }
                        else
                        {
                            System.Diagnostics.Trace.WriteLine(string.Format("WARNING: Namespace {0} not included.", rel.Type));
                        }
                    }
                }
            }
            catch (ZipEntryNotFoundException)
            {
            }
        }
        protected override List <RelationShip> CopyPart(XmlReader xtr, XmlTextWriter xtw, string ns, string partName, ZipReader archive)
        {
            bool isInRel             = false;
            bool extractRels         = ns.Equals(RELATIONSHIP_NS);
            bool isCell              = false;
            List <RelationShip> rels = new List <RelationShip>();

            int idSheet     = 0;
            int idRow       = 1;
            int idFont      = 0;
            int idFill      = 0;
            int idBorder    = 0;
            int idXf        = 0;
            int idCellStyle = 0;
            int idDxf       = 0;
            int idSi        = 0;
            int idCf        = 0;

            int RowNumber     = 0;
            int PrevRowNumber = 0;

            int ColNumber     = 0;
            int PrevColNumber = 0;

            String     ConditionalCell        = "";
            String     ConditionalCellRow     = "";
            List <int> ConditionalCellRowList = new List <int>();
            Boolean    CheckIfBigConditional  = new Boolean();

            intConditionalWithStyle = new Hashtable();
            string s = "";
            int    ConditionalStyle = -1;

            XmlReader SearchConditionalReader;

            RelationShip rel = new RelationShip();

            if (!(partName.Contains(".vml")))
            {
                while (xtr.Read())
                {
                    switch (xtr.NodeType)
                    {
                    case XmlNodeType.Attribute:
                        break;

                    case XmlNodeType.CDATA:
                        xtw.WriteCData(xtr.Value);
                        break;

                    case XmlNodeType.Comment:
                        xtw.WriteComment(xtr.Value);
                        break;

                    case XmlNodeType.DocumentType:
                        xtw.WriteDocType(xtr.Name, null, null, null);
                        break;

                    case XmlNodeType.Element:
                        if (String.Compare(xtr.LocalName, "sheetData") == 0)
                        {
                            SearchConditionalReader = XmlReader.Create(archive.GetEntry(partName));
                            ConditionalCell         = Conditional(SearchConditionalReader, ns, partName);
                            CheckIfBigConditional   = CheckIfBigConditionalRow(ConditionalCell);

                            if (!CheckIfBigConditional)
                            {
                                ConditionalCellRowList = ConditionalCellRowNumberList(ConditionalCell);
                            }

                            ConditionalCellRowList.Sort();
                        }

                        if (extractRels && xtr.LocalName == "Relationship" && xtr.NamespaceURI == RELATIONSHIP_NS)
                        {
                            isInRel = true;
                            rel     = new RelationShip();
                        }

                        if (xtr.LocalName.Equals("row") && (ConditionalCell != ""))
                        {
                            if (xtr.HasAttributes)
                            {
                                while (xtr.MoveToNextAttribute())
                                {
                                    if (xtr.LocalName.Equals("r"))
                                    {
                                        RowNumber = System.Int32.Parse(xtr.Value.ToString());
                                    }
                                }

                                InsertEmptyRowsWithConditional(ConditionalCellRowList, ConditionalCell, xtw, RowNumber, PrevRowNumber, CheckIfBigConditional, false);
                                xtr.MoveToElement();

                                xtw.WriteStartElement(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI);

                                if (xtr.HasAttributes)
                                {
                                    while (xtr.MoveToNextAttribute())
                                    {
                                        xtw.WriteAttributeString(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI, xtr.Value);
                                    }
                                }

                                xtr.MoveToElement();
                            }
                            PrevRowNumber = RowNumber;
                        }
                        else
                        {
                            isCell = xtr.LocalName.Equals("c") && xtr.NamespaceURI.Equals(SPREADSHEET_ML_NS);

                            if (xtr.HasAttributes && isCell && ConditionalCell != "" && ConditionalCellRowList.Contains(RowNumber))
                            {
                                while (xtr.MoveToNextAttribute())
                                {
                                    if (xtr.LocalName == "r")
                                    {
                                        ColNumber = GetColId(xtr.Value);
                                        InsertCellInRow(RowNumber, ConditionalCell, xtw, PrevColNumber, ColNumber);
                                        PrevColNumber = ColNumber;
                                    }
                                }
                                xtr.MoveToElement();
                            }

                            xtw.WriteStartElement(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI);

                            if (xtr.HasAttributes)
                            {
                                while (xtr.MoveToNextAttribute())
                                {
                                    if (extractRels && isInRel)
                                    {
                                        if (xtr.LocalName == "Type")
                                        {
                                            rel.Type = xtr.Value;
                                        }
                                        else if (xtr.LocalName == "Target")
                                        {
                                            rel.Target = xtr.Value;
                                        }
                                        else if (xtr.LocalName == "Id")
                                        {
                                            rel.Id = xtr.Value;
                                        }
                                    }

                                    string value = xtr.Value;
                                    // normalize type ST_OnOff
                                    if (value == "on" || value == "true")
                                    {
                                        value = "1";
                                    }
                                    else if (value == "off" || value == "false")
                                    {
                                        value = "0";
                                    }

                                    xtw.WriteAttributeString(xtr.Prefix, xtr.LocalName, xtr.NamespaceURI, value);

                                    switch (xtr.LocalName)
                                    {
                                    case "r":
                                        if (isCell)
                                        {
                                            string coord = GetColId(value).ToString(System.Globalization.CultureInfo.InvariantCulture)
                                                           + "|"
                                                           + GetRowId(value).ToString(System.Globalization.CultureInfo.InvariantCulture);

                                            xtw.WriteAttributeString(NS_PREFIX, "p", PACKAGE_NS, coord);
                                            if (ConditionalCell != "" && ConditionalCellRowList.Contains(GetRowId(value)))
                                            {
                                                ConditionalStyle = CheckIfConditional(GetRowId(value), GetColId(value), ConditionalCell);
                                                if (ConditionalStyle != -1)
                                                {
                                                    xtw.WriteAttributeString(NS_PREFIX, "ConditionalStyle", PACKAGE_NS, ConditionalStyle.ToString());
                                                }
                                            }
                                            //xtw.WriteAttributeString(NS_PREFIX, "c", PACKAGE_NS, GetColId(value).ToString(System.Globalization.CultureInfo.InvariantCulture));
                                            //xtw.WriteAttributeString(NS_PREFIX, "r", PACKAGE_NS, GetRowId(value).ToString(System.Globalization.CultureInfo.InvariantCulture));
                                        }
                                        break;

                                    case "s":
                                        s = xtr.Value;
                                        break;
                                    }
                                }


                                if (ConditionalStyle > -1)
                                {
                                    if (intConditionalWithStyle.Contains(ConditionalStyle))
                                    {
                                        String OldValue = Convert.ToString(intConditionalWithStyle[ConditionalStyle]);

                                        if (!("|" + OldValue).Contains("|" + s + "|"))
                                        {
                                            intConditionalWithStyle.Remove(ConditionalStyle);
                                            intConditionalWithStyle.Add(ConditionalStyle, (OldValue + s + "|"));
                                        }
                                    }
                                    else
                                    {
                                        intConditionalWithStyle.Add(ConditionalStyle, (s + "|"));
                                    }
                                }

                                ConditionalStyle = -1;

                                xtr.MoveToElement();
                            }
                        }

                        if (isInRel)
                        {
                            isInRel = false;
                            rels.Add(rel);
                        }

                        switch (xtr.LocalName)
                        {
                        // reset id counters
                        case "sheets": idSheet = 0; break;

                        case "sheetData": idRow = 1; break;

                        case "fonts": idFont = 0; break;

                        case "fills": idFill = 0; break;

                        case "borders": idBorder = 0; break;

                        case "cellXfs":
                        case "cellStyleXfs":
                            idXf = 0;
                            break;

                        case "cellStyles": idCellStyle = 0; break;

                        case "dxfs": idDxf = 0; break;

                        case "sst": idSi = 0; break;

                        // add id values
                        case "sheet":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idSheet++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "row":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idRow++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "font":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idFont++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "fill":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idFill++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "border":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idBorder++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "xf":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idXf++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "cellStyle":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idCellStyle++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "dxf":
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idDxf++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "si":     // sharedStrings
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idSi++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "worksheet":
                        case "chartSpace":
                            xtw.WriteAttributeString(NS_PREFIX, "part", PACKAGE_NS, _partId.ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;

                        case "conditionalFormatting":
                            xtw.WriteAttributeString(NS_PREFIX, "part", PACKAGE_NS, _partId.ToString(System.Globalization.CultureInfo.InvariantCulture));
                            xtw.WriteAttributeString(NS_PREFIX, "id", PACKAGE_NS, (idCf++).ToString(System.Globalization.CultureInfo.InvariantCulture));
                            if (intConditionalWithStyle.Contains(idCf - 1))
                            {
                                xtw.WriteAttributeString(NS_PREFIX, "ConditionalInheritance", PACKAGE_NS, Convert.ToString(intConditionalWithStyle[idCf - 1]));
                            }
                            break;

                        case "col":
                        case "sheetFormatPr":
                        case "mergeCell":
                        case "drawing":
                        case "hyperlink":

                        case "ser":
                        case "val":
                        case "xVal":
                        case "cat":
                        case "plotArea":
                        case "grouping":
                        case "spPr":
                        case "errBars":
                            xtw.WriteAttributeString(NS_PREFIX, "part", PACKAGE_NS, _partId.ToString(System.Globalization.CultureInfo.InvariantCulture));
                            break;
                        }

                        if (xtr.IsEmptyElement)
                        {
                            if (ConditionalCell != "" && string.Compare(xtr.LocalName.ToString(), "sheetData") == 0)
                            {
                                InsertEmptyRowsWithConditional(ConditionalCellRowList, ConditionalCell, xtw, 65537, 0, CheckIfBigConditional, false);
                            }

                            xtw.WriteEndElement();
                        }
                        break;

                    case XmlNodeType.EndElement:
                        if (string.Compare(xtr.LocalName.ToString(), "sheetData") == 0 && (ConditionalCell != ""))
                        {
                            InsertEmptyRowsWithConditional(ConditionalCellRowList, ConditionalCell, xtw, 65537, PrevRowNumber, CheckIfBigConditional, true);
                        }
                        if (string.Compare(xtr.LocalName.ToString(), "row") == 0 && (ConditionalCell != ""))
                        {
                            InsertCellInRow(RowNumber, ConditionalCell, xtw, PrevColNumber, 257);
                        }

                        xtw.WriteEndElement();
                        break;

                    case XmlNodeType.EntityReference:
                        xtw.WriteEntityRef(xtr.Name);
                        break;

                    case XmlNodeType.ProcessingInstruction:
                        xtw.WriteProcessingInstruction(xtr.Name, xtr.Value);
                        break;

                    case XmlNodeType.SignificantWhitespace:
                        xtw.WriteWhitespace(xtr.Value);
                        break;

                    case XmlNodeType.Text:
                        xtw.WriteString(xtr.Value);
                        break;

                    case XmlNodeType.Whitespace:
                        xtw.WriteWhitespace(xtr.Value);
                        break;

                    case XmlNodeType.XmlDeclaration:
                        // omit XML declaration
                        break;

                    default:
                        Debug.Assert(false);
                        break;
                    }
                }
            }

            _partId++;

            return(rels);
        }
Beispiel #22
0
        ///// <summary>
        ///// Initialize according to the input file type
        ///// </summary>
        ///// <param name="inputFileType">DocType of input file</param>
        ///// <returns>return IUOFTranslator</returns>
        //public static IUOFTranslator CheckFileType(DocType inputFileType)
        //{
        //    switch (inputFileType)
        //    {
        //        case DocType.Word: return new WordTranslator();
        //        case DocType.Powerpoint: return new PresentationTranslator();
        //        case DocType.Excel: return new SpreadsheetTranslator();
        //        default: throw new Exception("not an office 2010 file");
        //    }
        //}

        /// <summary>
        /// check Microsoft file type
        /// </summary>
        /// <param name="srcFileName">source file name</param>
        /// <returns>document type</returns>
        public static MSDocType CheckMSFileType(string srcFileName)
        {
            FileInfo fi = new FileInfo(srcFileName);

            if (File.Exists(srcFileName))
            {
                XmlReader source  = null;
                ZipReader archive = ZipFactory.OpenArchive(srcFileName);

                // get the main entry xml file
                string entry = string.Empty;
                switch (fi.Extension.ToLower())
                {
                case ".docx": entry = TranslatorMgrConstants.WordDocument_xml; break;

                case ".pptx": entry = TranslatorMgrConstants.PresentationDocument_xml; break;

                case ".xlsx": entry = TranslatorMgrConstants.SpreadsheetDocument_xml; break;
                }
                source = XmlReader.Create(archive.GetEntry(entry));

                XmlDocument xdoc = new XmlDocument();
                xdoc.Load(source);

                // namespace of strict document
                XmlNamespaceManager nm = new XmlNamespaceManager(xdoc.NameTable);
                nm.AddNamespace("w", TranslatorMgrConstants.XMLNS_W);
                nm.AddNamespace("p", TranslatorMgrConstants.XMLNS_P);
                nm.AddNamespace("ws", TranslatorMgrConstants.XMLNS_WS);

                switch (fi.Extension.ToLower())
                {
                case ".docx":
                {
                    // @w:conformance
                    if (xdoc.SelectSingleNode("w:document", nm) != null)
                    {
                        return(MSDocType.StrictWord);
                    }
                    else
                    {
                        return(MSDocType.TransitionalWord);
                    }
                }

                case ".pptx":
                {
                    if (xdoc.SelectSingleNode("p:presentation", nm) != null)
                    {
                        return(MSDocType.StrictPowerpoint);
                    }
                    else
                    {
                        return(MSDocType.TransitionalPowerpoint);
                    }
                }

                case ".xlsx":
                {
                    if (xdoc.SelectSingleNode("ws:workbook", nm) != null)
                    {
                        return(MSDocType.StrictExcel);
                    }
                    else
                    {
                        return(MSDocType.TransitionalExcel);
                    }
                }

                default: return(MSDocType.Unknown);
                }
            }
            else
            {
                return(MSDocType.Unknown);
            }
        }
Beispiel #23
0
        /// <summary>
        /// Check the validity of an Office Open XML file.
        /// </summary>
        /// <param name="fileName">The path of the docx file.</param>
        public void validate(string fileName)
        {
            // 0. The file must exist and be a valid Zip archive
            ZipReader reader = null;

            try
            {
                reader = ZipFactory.OpenArchive(fileName);
            }
            catch (Exception e)
            {
                throw new ValidationException("Problem opening the docx file : " + e.Message);
            }

            // 1. [Content_Types].xml must be present and valid
            Stream contentTypes = null;

            try
            {
                contentTypes = reader.GetEntry(OOX_CONTENT_TYPE_FILE);
            }
            catch (Exception)
            {
                throw new ValidationException("The docx package must have a \"/[Content_Types].xml\" file");
            }
            this.validateXml(contentTypes);

            // 2. _rels/.rels must be present and valid
            Stream relationShips = null;

            try
            {
                relationShips = reader.GetEntry(OOX_RELATIONSHIP_FILE);
            }
            catch (Exception)
            {
                throw new ValidationException("The docx package must have a \"/_rels/.rels\" file");
            }
            this.validateXml(relationShips);

            // 3. _rel/.rels must contain a relationship of type openDocument
            relationShips = reader.GetEntry(OOX_RELATIONSHIP_FILE);
            XmlReader r         = XmlReader.Create(relationShips);
            String    docTarget = null;

            while (r.Read() && docTarget == null)
            {
                if (r.NodeType == XmlNodeType.Element && r.GetAttribute("Type") == OOX_DOCUMENT_RELATIONSHIP_TYPE)
                {
                    docTarget = r.GetAttribute("Target");
                }
            }
            if (docTarget == null)
            {
                throw new ValidationException("openDocument relation not found in \"/_rels/.rels\"");
            }

            // 4. For each item in _rels/.rels
            relationShips = reader.GetEntry(OOX_RELATIONSHIP_FILE);
            r             = XmlReader.Create(relationShips);
            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element && r.LocalName == "Relationship")
                {
                    String target = r.GetAttribute("Target");



                    // 4.1. The target item must exist in the package
                    Stream item = null;
                    try
                    {
                        item = reader.GetEntry(target);
                    }
                    catch (Exception)
                    {
                        throw new ValidationException("The file \"" + target + "\" is described in the \"/_rels/.rels\" file but does not exist in the package.");
                    }

                    // 4.2. A content type can be found in [Content_Types].xml file
                    String ct = this.findContentType(reader, "/" + target);

                    // 4.3. If it's an xml file, it has to be valid
                    if (ct.EndsWith("+xml"))
                    {
                        this.validateXml(item);
                    }
                }
            }

            // Does a part relationship exist ?
            Stream partRel       = null;
            String partDir       = docTarget.Substring(0, docTarget.IndexOf("/"));
            String partRelPath   = partDir + "/_rels/" + docTarget.Substring(docTarget.IndexOf("/") + 1) + ".rels";
            bool   partRelExists = true;

            try
            {
                partRel = reader.GetEntry(partRelPath);
            }
            catch (Exception)
            {
                partRelExists = false;
            }

            if (partRelExists)
            {
                this.validateXml(partRel);

                // 5. For each item in /word/_rels/document.xml.rels
                partRel = reader.GetEntry(partRelPath);
                r       = XmlReader.Create(partRel);
                while (r.Read())
                {
                    if (r.NodeType == XmlNodeType.Element && r.LocalName == "Relationship")
                    {
                        String target = partDir + "/" + r.GetAttribute("Target");

                        // Is the target item exist in the package ?
                        Stream item       = null;
                        bool   fileExists = true;
                        try
                        {
                            item = reader.GetEntry(target);
                        }
                        catch (Exception)
                        {
                            //throw new OoxValidatorException("The file \"" + target + "\" is described in the \"/word/_rels/document.xml.rels\" file but does not exist in the package.");
                            fileExists = false;
                        }

                        if (fileExists)
                        {
                            // 5.1. A content type can be found in [Content_Types].xml file
                            String ct = this.findContentType(reader, "/" + target);

                            // 5.2. If it's an xml file, it has to be valid
                            if (ct.EndsWith("+xml"))
                            {
                                this.validateXml(item);
                            }
                        }
                    }
                }
            }

            // 6. do all referenced relationships exist in the part relationship file

            // retrieve all ids referenced in the document

            Stream doc = reader.GetEntry(docTarget);

            r = XmlReader.Create(doc);
            ArrayList ids = new ArrayList();

            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element && r.GetAttribute("id", OOX_DOC_REL_NS) != null)
                {
                    ids.Add(r.GetAttribute("id", OOX_DOC_REL_NS));
                }
            }

            // check if each id exists in the partRel file

            if (ids.Count != 0)
            {
                if (!partRelExists)
                {
                    throw new ValidationException("Referenced id exist but no part relationship file found");
                }
                relationShips = reader.GetEntry(partRelPath);
                r             = XmlReader.Create(relationShips);
                while (r.Read())
                {
                    if (r.NodeType == XmlNodeType.Element && r.LocalName == "Relationship")
                    {
                        if (ids.Contains(r.GetAttribute("Id")))
                        {
                            ids.Remove(r.GetAttribute("Id"));
                        }
                    }
                }
                if (ids.Count != 0)
                {
                    throw new ValidationException("One or more relationship id have not been found in the partRelationship file : " + ids[0]);
                }
            }
        }
Beispiel #24
0
        protected override void DoOoxToUofMainTransform(string originalFile, string inputFile, string outputFile, string resourceDir)
        {
            string wordPrePath   = Path.GetDirectoryName(inputFile) + Path.DirectorySeparatorChar;
            string grpTmp        = Path.GetDirectoryName(inputFile) + "\\" + "grpTmp.xml";//把grpTmp.xml放在temp下的缓存文件夹下
            string drawingRelTmp = Path.GetDirectoryName(inputFile) + "\\" + "drawingRelTmp.xml";
            string picture_xml   = "ppt\\media";
            string mediaPath     = wordPrePath + picture_xml;

            XmlDocument xdoc = new XmlDocument();

            xdoc.Load(inputFile);//tempdoc1.xml
            XmlNamespaceManager nm = new XmlNamespaceManager(xdoc.NameTable);

            nm.AddNamespace("p", TranslatorConstants.XMLNS_P);
            nm.AddNamespace("a", TranslatorConstants.XMLNS_A);
            nm.AddNamespace("w", TranslatorConstants.XMLNS_W);
            nm.AddNamespace("dsp", TranslatorConstants.XMLNS_DSP);
            FileStream fs = new FileStream(grpTmp, FileMode.Create);

            try
            {
                GrpShPre(xdoc, nm, "p", fs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }

            // chart转换成图片
            string charts_xml = wordPrePath + "ppt\\charts";

            if (Directory.Exists(charts_xml))
            {
                string[] charts = Directory.GetFiles(charts_xml, "chart*");
                if (charts.Length > 0)
                {
                    if (!Directory.Exists(mediaPath))
                    {
                        Directory.CreateDirectory(mediaPath);
                    }
                }
                foreach (string chartXMLFile in charts)
                {
                    SaveChartAsPic(chartXMLFile, mediaPath + Path.AltDirectorySeparatorChar + Path.GetFileName(chartXMLFile) + ".jpg", System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Jpeg);
                }
            }

            //ole对象处理lyy
            string tmpPic = wordPrePath + "tmpOle.xml";

            if (Directory.Exists(wordPrePath + "ppt\\embeddings"))
            {
                xdoc.Load(grpTmp);
                xdoc = OlePretreatment(xdoc, "p:presentation", wordPrePath, nm);
                xdoc.Save(tmpPic);
                grpTmp = tmpPic;
            }
            // 图片预处理

            tmpPic = wordPrePath + "tmpPic.xml";
            if (Directory.Exists(mediaPath))
            {
                xdoc.Load(grpTmp);
                xdoc = PicPretreatment(xdoc, "p:presentation", mediaPath, nm);
                xdoc.Save(tmpPic);
                grpTmp = tmpPic;
            }
            //ole对象处理
            AddDrawingRel(xdoc, nm, drawingRelTmp);

            XmlReaderSettings xrs    = new XmlReaderSettings();
            XmlReader         source = null;

            string toMainSheet    = ZipXMLFile(drawingRelTmp);
            string zipXMLFileName = "input.xml";

            //string sr = ZipXMLFile(inputFile);
            ZipReader archive = ZipFactory.OpenArchive(toMainSheet);

            source = XmlReader.Create(archive.GetEntry(zipXMLFileName));

            //xdoc.Load(drawingRelTmp);

            XslCompiledTransform transFrom = new XslCompiledTransform();
            XsltSettings         setting   = new XsltSettings(true, false);
            XmlUrlResolver       xur       = new XmlUrlResolver();
            XPathNavigator       nav       = ((IXPathNavigable)xdoc).CreateNavigator();//root

            fs = null;
            string mainOutputFile = Path.GetDirectoryName(inputFile) + "\\" + "mainOutputFile.xml";//缓存文件中保存mainOutputFile.xml


            fs = new FileStream(mainOutputFile, FileMode.Create);
            string mainSheet = Path.GetDirectoryName(inputFile).ToString() + "\\" + TranslatorConstants.OOXToUOF_XSL;//从缓存中调用oox2uof.xsl

            transFrom.Load(mainSheet, setting, xur);
            //Assembly ass = Assembly.Load("ppt_oox2uof");//调用ppt_oox2uof.dll程序集
            //Type t = ass.GetType("oox2uof");//name=oox2uof.xslt
            //transFrom.Load(t);
            //transFrom.Transform(nav, null, fs);

            transFrom.Transform(source, null, fs);
            fs.Close();
            mainOutput = mainOutputFile;


            //XmlUrlResolver resourceResolver = null;

            //try
            //{

            //    resourceResolver = new ResourceResolver(Assembly.GetExecutingAssembly(),
            //        this.GetType().Namespace + "." + TranslatorConstants.RESOURCE_LOCATION + "." + "Powerpoint.oox2uof");
            // MainTransform(TranslatorConstants.OOXToUOF_XSL, resourceResolver, originalFile, grpTmp, outputFile);

            ////}
            //catch (Exception ex)
            //{
            //    logger.Warn(ex.Message);
            //}
        }
Beispiel #25
0
        /// <summary>
        /// Check the validity of an Office Open XML file.
        /// </summary>
        /// <param name="fileName">The path of the docx file.</param>
        public void validate(String fileName)
        {
            // 0. The file must exist and be a valid Zip archive

            try
            {
                reader = ZipFactory.OpenArchive(fileName);
            }
            catch (ZipException e)
            {
                throw new NotAnOoxDocumentException("Problem opening the pptx file : " + e.Message);
            }
            catch (Exception e)
            {
                throw new PptxValidatorException("Problem opening the pptx file : " + e.Message);
            }

            // 1. [Content_Types].xml must be present and valid
            Stream contentTypes = null;

            try
            {
                contentTypes = reader.GetEntry(OOX_CONTENT_TYPE_FILE);
            }
            catch (Exception)
            {
                //modified by lohith - to display user friendly message
                throw new NotAnOoxDocumentException("The pptx package must have a \"/[Content_Types].xml\" file");
                //throw new PptxValidatorException("The pptx package must have a \"/[Content_Types].xml\" file");
            }
            this.validateXml(contentTypes);

            // Code to verify whether a file is valid pptx file or not
            //bug no. 1698280
            //Code chcanges 1 of 2
            if (!this.validatePptx(reader))
            {
                throw new NotAnOoxDocumentException("The pptx package must have a Presentation.xml file");
            }

            // End



            // 2. _rels/.rels must be present and valid
            Stream relationShips = null;

            try
            {
                relationShips = reader.GetEntry(OOX_RELATIONSHIP_FILE);
            }
            catch (Exception)
            {
                //modified by lohith - to display user friendly message
                throw new NotAnOoxDocumentException("The pptx package must have a a \"/_rels/.rels\" file");

                //throw new PptxValidatorException("The pptx package must have a \"/_rels/.rels\" file");
            }
            this.validateXml(relationShips);

            // 3. _rel/.rels must contain a relationship of type openDocument
            relationShips = reader.GetEntry(OOX_RELATIONSHIP_FILE);
            XmlReader r         = XmlReader.Create(relationShips);
            String    docTarget = null;

            while (r.Read() && docTarget == null)
            {
                if (r.NodeType == XmlNodeType.Element && r.GetAttribute("Type") == OOX_DOCUMENT_RELATIONSHIP_TYPE)
                {
                    docTarget = r.GetAttribute("Target");
                }
            }
            if (docTarget == null)
            {
                //modified by lohith - to display user friendly message
                throw new NotAnOoxDocumentException("openDocument relation not found in \"/_rels/.rels\"");

                //throw new PptxValidatorException("openDocument relation not found in \"/_rels/.rels\"");
            }


            // 4. For each item in _rels/.rels
            relationShips = reader.GetEntry(OOX_RELATIONSHIP_FILE);
            r             = XmlReader.Create(relationShips);
            while (r.Read())
            {
                if (r.NodeType == XmlNodeType.Element && r.LocalName == "Relationship")
                {
                    String target = r.GetAttribute("Target");

                    // 4.1. The target item must exist in the package
                    Stream item = null;
                    try
                    {
                        item = reader.GetEntry(target);
                    }
                    catch (Exception)
                    {
                        //modified by lohith - to display user friendly message
                        throw new NotAnOoxDocumentException("The file \"" + target + "\" is described in the \"/_rels/.rels\" file but does not exist in the package.");

                        //throw new PptxValidatorException("The file \"" + target + "\" is described in the \"/_rels/.rels\" file but does not exist in the package.");
                    }

                    // 4.2. A content type can be found in [Content_Types].xml file
                    String ct = this.findContentType(reader, "/" + target);

                    // 4.3. If it's an xml file, it has to be valid
                    if (ct.EndsWith("+xml"))
                    {
                        this.validateXml(item);
                    }
                }
            }

            Stream partRel       = null;
            String partDir       = docTarget.Substring(0, docTarget.IndexOf("/"));
            String partRelPath   = partDir + "/_rels/" + docTarget.Substring(docTarget.IndexOf("/") + 1) + ".rels";
            bool   partRelExists = true;

            try
            {
                partRel = reader.GetEntry(partRelPath);
            }
            catch (Exception)
            {
                partRelExists = false;
            }

            if (partRelExists)
            {
                this.validateXml(partRel);

                // 5. For each item in /ppt/_rels/presentation.xml.rels
                partRel = reader.GetEntry(partRelPath);
                r       = XmlReader.Create(partRel);
                ValidateRels(partDir, r);

                //retrieve all ids referenced in the document
                r.Close();
                Stream doc = reader.GetEntry(docTarget);
                r = XmlReader.Create(doc);
                ArrayList ids = new ArrayList();
                while (r.Read())
                {
                    if (r.LocalName == "custShow")
                    {
                        r.Skip();
                    }
                    else
                    {
                        if (r.NodeType == XmlNodeType.Element && r.GetAttribute("id", OOX_DOC_REL_NS) != null)
                        {
                            ids.Add(r.GetAttribute("id", OOX_DOC_REL_NS));
                        }
                    }
                }

                // check if each id exists in the partRel file
                if (ids.Count != 0)
                {
                    if (!partRelExists)
                    {
                        //modified by lohith - to display user friendly message
                        throw new NotAnOoxDocumentException("Referenced id exist but no part relationship file found");

                        //throw new PptxValidatorException("Referenced id exist but no part relationship file found");
                    }
                    relationShips = reader.GetEntry(partRelPath);
                    r             = XmlReader.Create(relationShips);
                    while (r.Read())
                    {
                        if (r.NodeType == XmlNodeType.Element && r.LocalName == "Relationship")
                        {
                            if (ids.Contains(r.GetAttribute("Id")))
                            {
                                ids.Remove(r.GetAttribute("Id"));
                            }
                        }
                    }
                    if (ids.Count != 0)
                    {
                        //modified by lohith - to display user friendly message
                        throw new NotAnOoxDocumentException("One or more relationship id have not been found in the partRelationship file : " + ids[0]);

                        //throw new PptxValidatorException("One or more relationship id have not been found in the partRelationship file : " + ids[0]);
                    }
                }
            }

            //6. For each item in /ppt/slideMasters/_rels/slideMasters.xml.rels
            docTarget = null;
            partRel   = reader.GetEntry(partRelPath);
            r         = XmlReader.Create(partRel);
            while (r.Read() && docTarget == null)
            {
                if (r.NodeType == XmlNodeType.Element && r.GetAttribute("Type") == OOX_SIDEMASTER_RELATIONSHIP_TYPE)
                {
                    docTarget   = r.GetAttribute("Target");
                    partDir     = OOX_SIDEMASTER_RELATIONSHIP_FILE;
                    partRelPath = partDir + "/_rels/" + docTarget.Substring(docTarget.IndexOf("/") + 1) + ".rels";

                    partRel = reader.GetEntry(partRelPath);
                    r       = XmlReader.Create(partRel);
                    ValidateRels(partDir, r);
                }
            }

            //7. Validation for SlideLayouts if required will be added here.

            //8. For each slide in a presentation, validation needs to be added here

            //9. During developement required validations for pptx feature e.g notes master, numbering etc. will be added.

            //10. are all referenced relationships exist in the part relationship file
        }
        /// <summary>
        /// Performs the action that is passed while reading the Sitecore package.
        /// </summary>
        /// <param name="action"></param>
        private static void ApplyToZipEntries(Action<ZipEntryData> action)
        {
            using (new SecurityDisabler())
            {
                using (new ProxyDisabler())
                {
                    ZipReader reader = new ZipReader(file.FullName, Encoding.UTF8);
                    ZipEntry entry = reader.GetEntry("package.zip");

                    using (MemoryStream stream = new MemoryStream())
                    {
                        StreamUtil.Copy(entry.GetStream(), stream, 0x4000);

                        reader = new ZipReader(stream);

                        foreach (ZipEntryData entryData in reader.Entries.Select(zipEntry => new ZipEntryData(zipEntry)))
                        {
                            action(entryData);
                        }
                    }
                }
            }
        }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="packageFileName"></param>
    /// <returns></returns>
    private project ExtractPackageAndGetProjectInformation(string packageFileName)
    {
        project projectInformation = null;
        ZipReader reader = null;
        string tempFileName = string.Empty;
        try
        {
            reader = new ZipReader(packageFileName, Encoding.UTF8);
            tempFileName = Path.GetTempFileName();
            ZipEntry entry = reader.GetEntry("package.zip");
            if (entry != null)
            {
                using (FileStream stream = File.Create(tempFileName))
                {
                    StreamUtil.Copy(entry.GetStream(), stream, 0x4000);
                }
                reader.Dispose();
                reader = new ZipReader(tempFileName, Encoding.UTF8);
            }

            // Get Project XML File
            entry = reader.GetEntry("installer/project");

            using (MemoryStream memoryStream = new MemoryStream())
            {
                StreamUtil.Copy(entry.GetStream(), memoryStream, 0x4000);

                // Let's go to start of stream
                memoryStream.Seek(0, SeekOrigin.Begin);

                // Convert XML to class

                // Package can contain list of
                // Items
                // Files
                XmlSerializer serializer = new XmlSerializer(typeof(project));
                projectInformation = (project)serializer.Deserialize(memoryStream);

            }

        }
        catch (Exception ex)
        {
            projectInformation = null;
            Sitecore.Diagnostics.Log.Error("While extracting package and getting information something went wrong", ex, this);
        }
        finally
        {
            if (reader != null)
                reader.Dispose();
            if (!string.IsNullOrEmpty(tempFileName))
                File.Delete(tempFileName);
        }

        return projectInformation;
    }