GetStream() public method

public GetStream ( ) : Stream
return Stream
        private static void ExtractContentFile(string rootFolder, PackagePart contentFile)
        {
            // Initially create file under the folder specified
            string contentFilePath = contentFile.Uri.OriginalString.Replace('/', Path.DirectorySeparatorChar);

            if (contentFilePath.StartsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture)))
            {
                contentFilePath = contentFilePath.TrimStart(Path.DirectorySeparatorChar);
            }

            contentFilePath = Path.Combine(rootFolder, contentFilePath);

            //Check for the folder already exists. If not then create that folder
            if (!Directory.Exists(Path.GetDirectoryName(contentFilePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(contentFilePath));
            }

            using (var newFileStream = File.Create(contentFilePath))
            {
                newFileStream.Close();
                var content = new byte[contentFile.GetStream().Length];
                contentFile.GetStream().Read(content, 0, content.Length);
                File.WriteAllBytes(contentFilePath, content);
            }
        }
Ejemplo n.º 2
0
    /// <summary>
    /// Returns the part contents in xml
    /// </summary>
    /// <param name="part">System.IO.Packaging.Packagepart</param>
    /// <returns></returns>
    static XElement GetContentsAsXml(PackagePart part)
    {
        XNamespace pkg = 
           "http://schemas.microsoft.com/office/2006/xmlPackage";
        if (part.ContentType.EndsWith("xml"))
        {
            using (Stream partstream = part.GetStream())
            using (StreamReader streamReader = new StreamReader(partstream))
            {
                string streamString = streamReader.ReadToEnd();
                XElement newXElement = 
                    new XElement(pkg + "part", new XAttribute(pkg + "name", part.Uri), 
                        new XAttribute(pkg + "contentType", part.ContentType), 
                        new XElement(pkg + "xmlData", XElement.Parse(streamString)));
                return newXElement;
            }
         }
        else
        {
            using (Stream str = part.GetStream())
            using (BinaryReader binaryReader = new BinaryReader(str))
            {
                int len = (int)binaryReader.BaseStream.Length;
                byte[] byteArray = binaryReader.ReadBytes(len);
                // the following expression creates the base64String, then chunks
                // it to lines of 76 characters long
                string base64String = (System.Convert.ToBase64String(byteArray))
                    .Select
                    (
                        (c, i) => new
                        {
                            Character = c,
                            Chunk = i / 76
                        }
                    )
                    .GroupBy(c => c.Chunk)
                    .Aggregate(
                        new StringBuilder(),
                        (s, i) =>
                            s.Append(
                                i.Aggregate(
                                    new StringBuilder(),
                                    (seed, it) => seed.Append(it.Character),
                                    sb => sb.ToString()
                                )
                            )
                            .Append(Environment.NewLine),
                        s => s.ToString()
                    );

                return new XElement(pkg + "part",
                    new XAttribute(pkg + "name", part.Uri),
                    new XAttribute(pkg + "contentType", part.ContentType),
                    new XAttribute(pkg + "compression", "store"),
                    new XElement(pkg + "binaryData", base64String)
                );
            }
        }
    }
        protected override void UpdateServiceDescriptionPart(PackagePart serviceDescriptionPart)
        {
            var definitionSerializer = new XmlSerializer(typeof(ServiceDefinition));

            var packageStream = serviceDescriptionPart.GetStream(FileMode.Open, FileAccess.ReadWrite);
            var serviceDefinition = definitionSerializer.Deserialize(packageStream) as ServiceDefinition;

            UpdateServiceDefinition(serviceDefinition);

            // rewind package stream
            packageStream.Seek(0, SeekOrigin.Begin);
            packageStream.SetLength(0);

            var writerSettings = new XmlWriterSettings()
            {
                Indent = true,
                CloseOutput = false
            };

            // write back to output
            using (var writer = XmlWriter.Create(packageStream, writerSettings))
            {
                definitionSerializer.Serialize(writer, serviceDefinition);
            }
        }
        private void UpdatePackageManifest(Package package, PackagePart updatedPart)
        {
            if (package == null)
                throw new ArgumentNullException(nameof(package));
            if (updatedPart == null)
                throw new ArgumentNullException(nameof(updatedPart));
            if (package.FileOpenAccess != FileAccess.ReadWrite)
                throw new InvalidOperationException("Package must be open for reading and writing");

            var manifestRelation = package.GetRelationship("MANIFEST");
            var manifestPart = package.GetPart(manifestRelation.TargetUri);

            // parse manifest
            var manifest = new PackageManifest(manifestPart, null);

            // rehash updated part
            var csDefPart = manifest.Items.FirstOrDefault(i => i.PartUri == updatedPart.Uri);
            if (csDefPart == null)
                throw new InvalidOperationException(string.Format("Unable to find part '{0}' in package manifest", updatedPart.Uri));

            csDefPart.Hash = manifest.HashAlgorithm.ComputeHash(updatedPart.GetStream(FileMode.Open, FileAccess.Read)); ;
            csDefPart.ModifiedDate = DateTime.UtcNow;

            var manifestStream = manifestPart.GetStream(FileMode.Open, FileAccess.Write);
            manifest.WriteToStream(manifestStream);
        }
Ejemplo n.º 5
0
        private static bool TrySignPackagePart(PackagePart packagePart, string keyPath, string keyPassword, bool signedPackage)
        {
            if (packagePart.Uri.ToString().EndsWith(".exe")
                || packagePart.Uri.ToString().EndsWith(".dll"))
            {
                string tempPath = Path.GetTempFileName();
                try
                {
                    using (var stream = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write))
                    {
                        packagePart.GetStream().CopyTo(stream);
                    }

                    if (!SigningHelper.GetAssemblyInfo(tempPath).IsSigned)
                    {
                        signedPackage = true;

                        SigningHelper.SignAssembly(tempPath, keyPath ?? string.Empty, keyPassword ?? string.Empty);

                        using (var stream = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Read))
                        {
                            stream.CopyTo(packagePart.GetStream(FileMode.Create, FileAccess.Write));
                        }
                    }
                }
                finally
                {
                    File.Delete(tempPath);
                }
            }
            return signedPackage;
        }
Ejemplo n.º 6
0
        internal ExcelPicture(ExcelDrawings drawings, XmlNode node)
            : base(drawings, node, "xdr:pic/xdr:nvPicPr/xdr:cNvPr/@name")
        {
            XmlNode picNode = node.SelectSingleNode("xdr:pic/xdr:blipFill/a:blip", drawings.NameSpaceManager);
            if (picNode != null)
            {
                RelPic = drawings.Part.GetRelationship(picNode.Attributes["r:embed"].Value);
                UriPic = PackUriHelper.ResolvePartUri(drawings.UriDrawing, RelPic.TargetUri);

                Part = drawings.Part.Package.GetPart(UriPic);
                FileInfo f = new FileInfo(UriPic.OriginalString);
                ContentType = GetContentType(f.Extension);
                _image = Image.FromStream(Part.GetStream());
                ImageConverter ic=new ImageConverter();
                var iby=(byte[])ic.ConvertTo(_image, typeof(byte[]));
                var ii = _drawings._package.LoadImage(iby, UriPic, Part);
                ImageHash = ii.Hash;

                string relID = GetXmlNodeString("xdr:pic/xdr:nvPicPr/xdr:cNvPr/a:hlinkClick/@r:id");
                if (!string.IsNullOrEmpty(relID))
                {
                    HypRel = drawings.Part.GetRelationship(relID);
                    if (HypRel.TargetUri.IsAbsoluteUri)
                    {
                        _hyperlink = new ExcelHyperLink(HypRel.TargetUri.AbsoluteUri);
                    }
                    else
                    {
                        _hyperlink = new ExcelHyperLink(HypRel.TargetUri.OriginalString, UriKind.Relative);
                    }
                    ((ExcelHyperLink)_hyperlink).ToolTip = GetXmlNodeString("xdr:pic/xdr:nvPicPr/xdr:cNvPr/a:hlinkClick/@tooltip");
                }
            }
        }
Ejemplo n.º 7
0
 private static void CopyPart(PackagePart oldPart, PackagePart newPart)
 {
     using (Stream oldPartStream = oldPart.GetStream(),
                   newPartStream = newPart.GetStream(FileMode.OpenOrCreate))
     {
         oldPartStream.CopyTo(newPartStream);
     }
 }
        void ExtractPart(PackagePart part, string destinationPath)
        {
            fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(destinationPath));

            using (var packageFileStream = part.GetStream())
            using (var destinationFileStream = fileSystem.OpenFile(destinationPath, FileMode.Create))
            {
                packageFileStream.CopyTo(destinationFileStream);
                destinationFileStream.Flush();
            }
        }
        public ZipPackageFile(PackagePart part) 
            : base(UriUtility.GetPath(part.Uri))
        {
            Debug.Assert(part != null, "part should not be null");

            byte[] buffer;
            using (Stream partStream = part.GetStream())
            {
                buffer = partStream.ReadAllBytes();
            }
            _streamFactory = () => new MemoryStream(buffer);
        }
Ejemplo n.º 10
0
 public string GetFileHash(PackagePart part)
 {
     using (var inputStream = part.GetStream())
     using (var md5 = new MD5CryptoServiceProvider())
     {   var hash = md5.ComputeHash(inputStream);
         var sb = new StringBuilder();
         foreach (var b in hash)
         {
             sb.Append(string.Format("{0:X2}", b));
         }
         return sb.ToString();
     }
 }
Ejemplo n.º 11
0
        public ZipPackageFile(PackagePart part)
        {
            Debug.Assert(part != null, "part should not be null");

            byte[] buffer;
            using (Stream partStream = part.GetStream()) {
                using (var stream = new MemoryStream()) {
                    partStream.CopyTo(stream);
                    buffer = stream.ToArray();
                }
            }
            _path = UriUtility.GetPath(part.Uri);
            _streamFactory = () => new MemoryStream(buffer);
        }
        private void UpdateServiceDescriptionPackage(PackagePart servicePackageDescriptionPart)
        {
            // open service description package
            var descPackage = Package.Open(servicePackageDescriptionPart.GetStream(FileMode.Open, FileAccess.ReadWrite), FileMode.Open, FileAccess.ReadWrite);
            var descPackageRelation = descPackage.GetRelationship("SERVICEDESCRIPTION");
            var descPackagePart = descPackage.GetPart(descPackageRelation.TargetUri);

            // update service description content
            UpdateServiceDescriptionPart(descPackagePart);

            // update inner package manifest
            UpdatePackageManifest(descPackage, descPackagePart);
            descPackage.Flush();
            descPackage.Close();
        }
Ejemplo n.º 13
0
        /// <summary>
        ///By package because  ChangeDocumentType not working well
        /// </summary>
        /// <param name="documentStream"></param>
        private void ChangeDocmToDocxUsingPackage(Stream documentStream)
        {
            // Open the document in the stream and replace the custom XML part
            using (System.IO.Packaging.Package packageFile = System.IO.Packaging.Package.Open(documentStream, FileMode.Open, FileAccess.ReadWrite))
            {
                System.IO.Packaging.PackagePart packagePart = null;
                // Find part containing the correct namespace
                foreach (var part in packageFile.GetParts())
                {
                    if (part.ContentType.Equals("application/vnd.ms-word.document.macroEnabled.main+xml", StringComparison.OrdinalIgnoreCase))
                    {
                        packagePart = part;
                        break;
                    }
                }
                if (packagePart != null)
                {
                    using (MemoryStream source = new MemoryStream())
                    {
                        CopyStream(packagePart.GetStream(), source);

                        var saveRelationBeforeDelPart = new List <PackageRelationship>();
                        foreach (var item in packagePart.GetRelationships())
                        {
                            saveRelationBeforeDelPart.Add(item);
                        }

                        Uri uriData = packagePart.Uri;
                        // Delete the existing XML part
                        if (packageFile.PartExists(uriData))
                        {
                            packageFile.DeletePart(uriData);
                        }

                        // Load the custom XML data
                        var pkgprtData = packageFile.CreatePart(uriData, "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml", System.IO.Packaging.CompressionOption.SuperFast);

                        source.Position = 0;//reset position
                        CopyStream(source, pkgprtData.GetStream(FileMode.Create));

                        foreach (var copyRel in saveRelationBeforeDelPart)
                        {
                            pkgprtData.CreateRelationship(copyRel.TargetUri, copyRel.TargetMode, copyRel.RelationshipType, copyRel.Id);
                        }
                    }
                }
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Creates a package-level or part-level relationship and its target part
        /// (if the target part wasn't already created before). If the sourceTargetFilePath does not exist,
        /// then both relationship and part will not be created.
        /// </summary>
        /// <param name="package"></param>
        /// <param name="sourcePart">Set to null for a package-level relationship</param>
        /// <param name="sourceTargetFilePath"></param>
        /// <param name="targetUri"></param>
        /// <param name="targetMimeType"></param>
        /// <param name="relationshipTypeUri"></param>
        /// <param name="targetPart">The target part that was created</param>
        /// <returns>True if relationship and part (if not already created before) was created,
        /// False if source file does not exist and thus relationship and part wasn't created.</returns>
        private static bool CreateRelationshipAndTargetPart(
            System.IO.Packaging.Package package, System.IO.Packaging.PackagePart sourcePart,
            string sourceTargetFilePath, string targetUri, string targetMimeType, string relationshipTypeUri,
            out System.IO.Packaging.PackagePart targetPart)
        {
            // TODO add console output for added parts and relationships

            targetPart = null;

            if (!File.Exists(sourceTargetFilePath))
            {
                Console.WriteLine(
                    "Warning: The following source file does not exist: " + sourceTargetFilePath +
                    ". Part and relationship will not be created.");
                return(false);
            }
            try
            {
                targetPart = package.CreatePart(
                    PackUriHelper.CreatePartUri(
                        new Uri(targetUri, UriKind.Relative)), targetMimeType, CompressionOption.Maximum);
                using (FileStream fileStream = new FileStream(sourceTargetFilePath, FileMode.Open, FileAccess.Read))
                {
                    fileStream.CopyTo(targetPart.GetStream());
                }
            }
            catch (InvalidOperationException)
            {
                Console.WriteLine(
                    "Warning: The following part URI already exists and will not be created again: " +
                    targetUri + ". Relationship will still be created.");
            }
            if (sourcePart == null)
            {
                package.CreateRelationship(
                    PackUriHelper.CreatePartUri(
                        new Uri(targetUri, UriKind.Relative)), TargetMode.Internal, relationshipTypeUri);
            }
            else
            {
                sourcePart.CreateRelationship(
                    PackUriHelper.CreatePartUri(
                        new Uri(targetUri, UriKind.Relative)), TargetMode.Internal, relationshipTypeUri);
            }
            return(true);
        }
Ejemplo n.º 15
0
        private static void Extract(PackagePart part, string outPath)
        {
            string outFileName = Path.Combine(outPath, part.Uri.OriginalString.Substring(1));

            if (!Directory.Exists(Path.GetDirectoryName(outFileName)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(outFileName));
            }

            using (System.IO.FileStream outFileStream = new System.IO.FileStream(outFileName, FileMode.Create))
            {
                using (Stream inFileStream = part.GetStream())
                {
                    CopyStream(inFileStream, outFileStream);
                }
            }
        }
Ejemplo n.º 16
0
        public void Zip(string fullPathSource, bool recursive, string whereClause, string fullPathDestination, string zipFileName, bool overWrite)
        {
            Log.WriteLog(" -- Init -- ", "Log", this.GetType().Name, this.AppConfig);
            List <FileInfo> selectedFiles = this.SelectFiles(fullPathSource, recursive, whereClause, fullPathDestination);

            if (File.Exists(string.Concat(fullPathDestination, "\\", zipFileName)) && overWrite)
            {
                File.Delete(string.Concat(fullPathDestination, "\\", zipFileName));
            }
            else if (File.Exists(string.Concat(fullPathDestination, "\\", zipFileName)))
            {
                throw new IOException("File already exists");
            }
            string location = string.Concat(fullPathDestination, "\\", zipFileName);

            if (Path.GetExtension(location).ToLower() != ".zip")
            {
                throw new IOException("File Extension in not valid");
            }
            FileStream ZipFileStream = new FileStream(location, FileMode.Create);

            using (System.IO.Packaging.Package Package = System.IO.Packaging.Package.Open(ZipFileStream, FileMode.OpenOrCreate))
            {
                foreach (FileInfo file in selectedFiles)
                {
                    try
                    {
                        string[] strArrays = new string[] { string.Concat(this.RemoveDrivefromDirectory(file.DirectoryName), "\\", file.Name) };
                        Uri      UriPath   = PackUriHelper.CreatePartUri(new Uri(Path.Combine(strArrays), UriKind.Relative));
                        System.IO.Packaging.PackagePart PackagePart = Package.CreatePart(UriPath, "text/xml", CompressionOption.Maximum);
                        string[] strArrays1 = new string[] { string.Concat(file.DirectoryName, "\\", file.Name) };
                        byte[]   Data       = File.ReadAllBytes(Path.Combine(strArrays1));
                        PackagePart.GetStream().Write(Data, 0, Data.Count <byte>());
                        Package.CreateRelationship(PackagePart.Uri, TargetMode.Internal, "http://schemas.microsoft.com/opc/2006/sample/document");
                    }
                    catch (Exception exception)
                    {
                        Exception e = exception;
                        Log.WriteLog(e.Message, "Error", this.GetType().Name, this.AppConfig);
                        throw e;
                    }
                }
            }
            ZipFileStream.Close();
        }
Ejemplo n.º 17
0
        private static void CopyObfuscatedFontPart(PackagePart oldPart, PackagePart newPart)
        {
            var guidArray = GetGUID(oldPart.Uri);

            using (Stream oldPartStream = oldPart.GetStream(),
                          newPartStream = newPart.GetStream(FileMode.OpenOrCreate),
                          memoryStream = new MemoryStream())
            {
                oldPartStream.CopyTo(memoryStream);

                for (int i = 0; i < 32; i++)
                {
                    (memoryStream as MemoryStream).GetBuffer()[i] ^= guidArray[15 - (i % 16)];
                }

                memoryStream.Seek(0, SeekOrigin.Begin);
                memoryStream.CopyTo(newPartStream);
            }
        }
Ejemplo n.º 18
0
        public ExcelDrawings(ExcelPackage xlPackage, ExcelWorksheet sheet)
        {
            _drawingsXml = new XmlDocument();
                _drawingsXml.PreserveWhitespace = true;
                _drawings = new Dictionary<int, ExcelDrawing>();

                XmlNode node = sheet.WorksheetXml.SelectSingleNode("//d:drawing", sheet.NameSpaceManager);
                CreateNSM();
                if (node != null)
                {
                    PackageRelationship drawingRelation = sheet.Part.GetRelationship(node.Attributes["r:id"].Value);
                    _uriDrawing = PackUriHelper.ResolvePartUri(sheet.WorksheetUri, drawingRelation.TargetUri);

                    _part = xlPackage.Package.GetPart(_uriDrawing);
                    _drawingsXml.Load(_part.GetStream());

                    AddDrawings();
                }
        }
Ejemplo n.º 19
0
 private static void ExtractPart(PackagePart packagePart, string pathToTarget)
 {
     string stringPart = packagePart.Uri.ToString().TrimStart('/');
     Uri partUri = new Uri(stringPart, UriKind.Relative);
     Uri uriFullPartPath =
     new Uri(new Uri(pathToTarget, UriKind.Absolute), partUri);
     Directory.CreateDirectory(
         Path.GetDirectoryName(uriFullPartPath.LocalPath));
     using (FileStream fileStream =
         new FileStream(uriFullPartPath.LocalPath, FileMode.Create))
     {
         CopyStream(packagePart.GetStream(), fileStream);
     }
 }
Ejemplo n.º 20
0
        //  --------------------------- ExtractPart ---------------------------
        /// <summary>
        ///   Extracts a specified package part to a target folder.</summary>
        /// <param name="packagePart">
        ///   The package part to extract.</param>
        /// <param name="targetDirectory">
        ///   The relative path from the 'current' directory
        ///   to the targer folder.</param>
        private static void ExtractPart(
            PackagePart packagePart, string targetDirectory)
        {
            // Create a string with the full path to the target directory.
            string currentDirectory = Directory.GetCurrentDirectory();
            string pathToTarget = currentDirectory + @"\" + targetDirectory;

            // Remove leading slash from the Part Uri,
            //   and make a new Uri from the result
            string stringPart = packagePart.Uri.ToString().TrimStart('/');
            Uri partUri = new Uri(stringPart, UriKind.Relative);

            // Create a full Uri to the Part based on the Package Uri
            Uri uriFullPartPath =
            new Uri(new Uri(pathToTarget, UriKind.Absolute), partUri);

            // Create the necessary Directories based on the Full Part Path
            Directory.CreateDirectory(
                Path.GetDirectoryName(uriFullPartPath.LocalPath));

            // Create the file with the Part content
            using (FileStream fileStream =
                new FileStream(uriFullPartPath.LocalPath, FileMode.Create))
            {
                CopyStream(packagePart.GetStream(), fileStream);
            }// end:using(FileStream fileStream) - Close & dispose fileStream.
        }
Ejemplo n.º 21
0
        protected void GetXmlDoc(string path, MemoryStream result, out Package pkg, out PackagePart part, out XmlReader xmlReader, out XDocument xmlMainXMLDoc)
        {
            var fileStream = System.IO.File.Open(path, FileMode.Open);
            CopyStream(fileStream, result);
            fileStream.Close();

            pkg = Package.Open(result, FileMode.Open, FileAccess.ReadWrite);

            var uri = new Uri("/word/document.xml", UriKind.Relative);
            part = pkg.GetPart(uri);

            xmlReader = XmlReader.Create(part.GetStream(FileMode.Open, FileAccess.Read));
            xmlMainXMLDoc = XDocument.Load(xmlReader);
        }
Ejemplo n.º 22
0
        protected XDocument SaveDoc(MemoryStream result, Package pkg, PackagePart part, XmlReader xmlReader, XDocument xmlMainXMLDoc, string templateBody)
        {
            xmlMainXMLDoc = XDocument.Parse(templateBody);

            var partWrt = new StreamWriter(part.GetStream(FileMode.Open, FileAccess.ReadWrite));
            xmlMainXMLDoc.Save(partWrt);

            partWrt.Flush();
            partWrt.Close();
            pkg.Close();

            result.Position = 0;

            xmlReader.Close();
            return xmlMainXMLDoc;
        }
        /// <summary>
        /// Parse PackageRelationship Stream
        /// </summary>
        /// <param name="part">relationship part</param>
        /// <exception cref="XmlException">Thrown if XML is malformed</exception>
        private void ParseRelationshipPart(PackagePart part)
        {
            //We can safely open the stream as FileAccess.Read, as this code
            //should only be invoked if the Package has been opened in Read or ReadWrite mode.
            Debug.Assert(_package.FileOpenAccess == FileAccess.Read || _package.FileOpenAccess == FileAccess.ReadWrite,
                         "This method should only be called when FileAccess is Read or ReadWrite");

            using (Stream s = part.GetStream(FileMode.Open, FileAccess.Read))
            {
                // load from the relationship part associated with the given part
                using (XmlReader baseReader = XmlReader.Create(s))
                {
                    using (XmlCompatibilityReader reader = new XmlCompatibilityReader(baseReader, s_relationshipKnownNamespaces))
                    {
                        //This method expects the reader to be in ReadState.Initial.
                        //It will make the first read call.
                        PackagingUtilities.PerformInitailReadAndVerifyEncoding(baseReader);

                        //Note: After the previous method call the reader should be at the first tag in the markup.
                        //MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
                        //If the reader is currently at a content node then this function call is a no-op
                        reader.MoveToContent();

                        // look for our tag and namespace pair - throw if other elements are encountered
                        // Make sure that the current node read is an Element
                        if (reader.NodeType == XmlNodeType.Element &&
                            (reader.Depth == 0) &&
                            (String.CompareOrdinal(s_relationshipsTagName, reader.LocalName) == 0) &&
                            (String.CompareOrdinal(PackagingUtilities.RelationshipNamespaceUri, reader.NamespaceURI) == 0))
                        {
                            ThrowIfXmlBaseAttributeIsPresent(reader);

                            //There should be a namespace Attribute present at this level.
                            //Also any other attribute on the <Relationships> tag is an error including xml: and xsi: attributes
                            if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0)
                            {
                                throw new XmlException(SR.RelationshipsTagHasExtraAttributes, null, reader.LineNumber, reader.LinePosition);
                            }

                            // start tag encountered for Relationships
                            // now parse individual Relationship tags
                            while (reader.Read())
                            {
                                //Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
                                //If the reader is currently at a content node then this function call is a no-op
                                reader.MoveToContent();

                                //If MoveToContent() takes us to the end of the content
                                if (reader.NodeType == XmlNodeType.None)
                                {
                                    continue;
                                }

                                if (reader.NodeType == XmlNodeType.Element &&
                                    (reader.Depth == 1) &&
                                    (String.CompareOrdinal(s_relationshipTagName, reader.LocalName) == 0) &&
                                    (String.CompareOrdinal(PackagingUtilities.RelationshipNamespaceUri, reader.NamespaceURI) == 0))
                                {
                                    ThrowIfXmlBaseAttributeIsPresent(reader);

                                    int expectedAttributesCount = 3;

                                    string targetModeAttributeValue = reader.GetAttribute(s_targetModeAttributeName);
                                    if (targetModeAttributeValue != null)
                                    {
                                        expectedAttributesCount++;
                                    }

                                    //check if there are expected number of attributes.
                                    //Also any other attribute on the <Relationship> tag is an error including xml: and xsi: attributes
                                    if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) == expectedAttributesCount)
                                    {
                                        ProcessRelationshipAttributes(reader);

                                        //Skip the EndElement for Relationship
                                        if (!reader.IsEmptyElement)
                                        {
                                            ProcessEndElementForRelationshipTag(reader);
                                        }
                                    }
                                    else
                                    {
                                        throw new XmlException(SR.RelationshipTagDoesntMatchSchema, null, reader.LineNumber, reader.LinePosition);
                                    }
                                }
                                else
                                if (!(String.CompareOrdinal(s_relationshipsTagName, reader.LocalName) == 0 && (reader.NodeType == XmlNodeType.EndElement)))
                                {
                                    throw new XmlException(SR.UnknownTagEncountered, null, reader.LineNumber, reader.LinePosition);
                                }
                            }
                        }
                        else
                        {
                            throw new XmlException(SR.ExpectedRelationshipsElementTag, null, reader.LineNumber, reader.LinePosition);
                        }
                    }
                }
            }
        }
Ejemplo n.º 24
0
        private void ExtractPart(PackagePart packagePart, string targetDir, string fileName)
        {
            string extractPath = Path.Combine(targetDir, fileName);
            Uri uriFullFilePath = new Uri(extractPath);
            //Console.WriteLine(uriFullFilePath.ToString());
            // Create the necessary directories based on the full part path
            if (!Directory.Exists(Path.GetDirectoryName(uriFullFilePath.LocalPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(uriFullFilePath.LocalPath));
            }

            if (!File.Exists(uriFullFilePath.LocalPath))
            {
                // Write the file from the part’s content stream.
                using (FileStream fileStream = File.Create(uriFullFilePath.LocalPath))
                {
                    packagePart.GetStream().CopyTo(fileStream);
                }
            }
        }
Ejemplo n.º 25
0
        private XmlElement CreateDrawingXml()
        {
            if (DrawingXml.OuterXml == "")
                {
                    DrawingXml.LoadXml(string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><xdr:wsDr xmlns:xdr=\"{0}\" xmlns:a=\"{1}\" />", ExcelPackage.schemaSheetDrawings, ExcelPackage.schemaDrawings));
                    _uriDrawing = new Uri(string.Format("/xl/drawings/drawing{0}.xml", Worksheet.SheetID),UriKind.Relative);

                    Package package = Worksheet.xlPackage.Package;
                    _part = package.CreatePart(_uriDrawing, "application/vnd.openxmlformats-officedocument.drawing+xml", CompressionOption.Maximum);

                    StreamWriter streamChart = new StreamWriter(_part.GetStream(FileMode.Create, FileAccess.Write));
                    DrawingXml.Save(streamChart);
                    streamChart.Close();
                    package.Flush();

                    PackageRelationship drawRelation = Worksheet.Part.CreateRelationship(_uriDrawing, TargetMode.Internal, ExcelPackage.schemaRelationships + "/drawing");
                    XmlElement e = Worksheet.WorksheetXml.CreateElement("drawing", ExcelPackage.schemaMain);
                    e.SetAttribute("id",ExcelPackage.schemaRelationships, drawRelation.Id);

                    Worksheet.WorksheetXml.DocumentElement.AppendChild(e);
                    package.Flush();
                }
                XmlNode colNode = _drawingsXml.SelectSingleNode("//xdr:wsDr", NameSpaceManager);
                XmlElement drawNode = _drawingsXml.CreateElement("xdr", "twoCellAnchor", ExcelPackage.schemaSheetDrawings);
                colNode.AppendChild(drawNode);

                //Add from position Element;
                XmlElement fromNode = _drawingsXml.CreateElement("xdr","from", ExcelPackage.schemaSheetDrawings);
                drawNode.AppendChild(fromNode);
                fromNode.InnerXml = "<xdr:col>0</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>0</xdr:row><xdr:rowOff>0</xdr:rowOff>";

                //Add to position Element;
                XmlElement toNode = _drawingsXml.CreateElement("xdr", "to", ExcelPackage.schemaSheetDrawings);
                drawNode.AppendChild(toNode);
                toNode.InnerXml = "<xdr:col>10</xdr:col><xdr:colOff>0</xdr:colOff><xdr:row>10</xdr:row><xdr:rowOff>0</xdr:rowOff>";
                return drawNode;
        }
Ejemplo n.º 26
0
        // Deserialize properties part.
        private void ParseCorePropertyPart(PackagePart part)
        {
            XmlReaderSettings xrs = new XmlReaderSettings();
            xrs.NameTable = _nameTable;
            using (Stream stream = part.GetStream(FileMode.Open, FileAccess.Read))

            // Create a reader that uses _nameTable so as to use the set of tag literals
            // in effect as a set of atomic identifiers.
            using (XmlReader reader = XmlReader.Create(stream, xrs))
            {
                //This method expects the reader to be in ReadState.Initial.
                //It will make the first read call.
                PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader);

                //Note: After the previous method call the reader should be at the first tag in the markup.
                //MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
                //If the reader is currently at a content node then this function call is a no-op
                if (reader.MoveToContent() != XmlNodeType.Element
                    || (object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.PackageCorePropertiesNamespace)
                    || (object)reader.LocalName != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.CoreProperties))
                {
                    throw new XmlException(SR.CorePropertiesElementExpected,
                        null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                }

                // The schema is closed and defines no attributes on the root element.
                if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 0)
                {
                    throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
                        null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                }

                // Iterate through property elements until EOF. Note the proper closing of all
                // open tags is checked by the reader itself.
                // This loop deals only with depth-1 start tags. Handling of element content
                // is delegated to dedicated functions.
                int attributesCount;

                while (reader.Read() && reader.MoveToContent() != XmlNodeType.None)
                {
                    // Ignore end-tags. We check element errors on opening tags.
                    if (reader.NodeType == XmlNodeType.EndElement)
                        continue;

                    // Any content markup that is not an element here is unexpected.
                    if (reader.NodeType != XmlNodeType.Element)
                    {
                        throw new XmlException(SR.PropertyStartTagExpected,
                            null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                    }

                    // Any element below the root should open at level 1 exclusively.
                    if (reader.Depth != 1)
                    {
                        throw new XmlException(SR.NoStructuredContentInsideProperties,
                            null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                    }

                    attributesCount = PackagingUtilities.GetNonXmlnsAttributeCount(reader);

                    // Property elements can occur in any order (xsd:all).
                    object localName = reader.LocalName;
                    PackageXmlEnum xmlStringIndex = PackageXmlStringTable.GetEnumOf(localName);
                    String valueType = PackageXmlStringTable.GetValueType(xmlStringIndex);

                    if (Array.IndexOf(s_validProperties, xmlStringIndex) == -1)  // An unexpected element is an error.
                    {
                        throw new XmlException(
                            SR.Format(SR.InvalidPropertyNameInCorePropertiesPart, reader.LocalName),
                            null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                    }

                    // Any element not in the valid core properties namespace is unexpected.
                    // The following is an object comparison, not a string comparison.
                    if ((object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlStringTable.GetXmlNamespace(xmlStringIndex)))
                    {
                        throw new XmlException(SR.UnknownNamespaceInCorePropertiesPart,
                            null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                    }

                    if (String.CompareOrdinal(valueType, "String") == 0)
                    {
                        // The schema is closed and defines no attributes on this type of element.
                        if (attributesCount != 0)
                        {
                            throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
                                null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                        }

                        RecordNewBinding(xmlStringIndex, GetStringData(reader), true /*initializing*/, reader);
                    }
                    else if (String.CompareOrdinal(valueType, "DateTime") == 0)
                    {
                        int allowedAttributeCount = (object)reader.NamespaceURI ==
                                                            PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace)
                                                        ? 1 : 0;

                        // The schema is closed and defines no attributes on this type of element.
                        if (attributesCount != allowedAttributeCount)
                        {
                            throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
                                null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                        }

                        if (allowedAttributeCount != 0)
                        {
                            ValidateXsiType(reader,
                                PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace),
                                W3cdtf);
                        }

                        RecordNewBinding(xmlStringIndex, GetDateData(reader), true /*initializing*/, reader);
                    }
                    else  // An unexpected element is an error.
                    {
                        Debug.Assert(false, "Unknown value type for properties");
                    }
                }
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Insert the contents of another document at the end of this document. 
        /// </summary>
        /// <param name="remote_document">The document to insert at the end of this document.</param>
        /// <example>
        /// Create a new document and insert an old document into it.
        /// <code>
        /// // Create a new document.
        /// using (DocX newDocument = DocX.Create(@"NewDocument.docx"))
        /// {
        ///     // Load an old document.
        ///     using (DocX oldDocument = DocX.Load(@"OldDocument.docx"))
        ///     {
        ///         // Insert the old document into the new document.
        ///         newDocument.InsertDocument(oldDocument);
        ///
        ///         // Save the new document.
        ///         newDocument.Save();
        ///     }// Release the old document from memory.
        /// }// Release the new document from memory.
        /// </code>
        /// <remarks>
        /// If the document being inserted contains Images, CustomProperties and or custom styles, these will be correctly inserted into the new document. In the case of Images, new ID's are generated for the Images being inserted to avoid ID conflicts. CustomProperties with the same name will be ignored not replaced.
        /// </remarks>
        /// </example>
        public void InsertDocument(DocX remote_document)
        {
            // We don't want to effect the origional XDocument, so create a new one from the old one.
            XDocument remote_mainDoc = new XDocument(remote_document.mainDoc);

            XDocument remote_footnotes = null;
            if (remote_document.footnotes != null)
                remote_footnotes = new XDocument(remote_document.footnotes);

            XDocument remote_endnotes = null;
            if (remote_document.endnotes != null)
                remote_endnotes = new XDocument(remote_document.endnotes);

            // Remove all header and footer references.
            remote_mainDoc.Descendants(XName.Get("headerReference", DocX.w.NamespaceName)).Remove();
            remote_mainDoc.Descendants(XName.Get("footerReference", DocX.w.NamespaceName)).Remove();

            // Get the body of the remote document.
            XElement remote_body = remote_mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));

            // Every file that is missing from the local document will have to be copied, every file that already exists will have to be merged.
            PackagePartCollection ppc = remote_document.package.GetParts();

            List<String> ignoreContentTypes = new List<string>
            {
                "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
                "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
                "application/vnd.openxmlformats-package.core-properties+xml",
                "application/vnd.openxmlformats-officedocument.extended-properties+xml",
                "application/vnd.openxmlformats-package.relationships+xml",
            };

            List<String> imageContentTypes = new List<string>
            {
                "image/jpeg",
                "image/jpg",
                "image/png",
                "image/bmp",
                "image/gif",
                "image/tiff",
                "image/icon",
                "image/pcx",
                "image/emf",
                "image/wmf"
            };
            // Check if each PackagePart pp exists in this document.
            foreach (PackagePart remote_pp in ppc)
            {
                if (ignoreContentTypes.Contains(remote_pp.ContentType) || imageContentTypes.Contains(remote_pp.ContentType))
                    continue;

                // If this external PackagePart already exits then we must merge them.
                if (package.PartExists(remote_pp.Uri))
                {
                    PackagePart local_pp = package.GetPart(remote_pp.Uri);
                    switch (remote_pp.ContentType)
                    {
                        case "application/vnd.openxmlformats-officedocument.custom-properties+xml":
                            merge_customs(remote_pp, local_pp, remote_mainDoc);
                            break;

                        // Merge footnotes (and endnotes) before merging styles, then set the remote_footnotes to the just updated footnotes
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":
                            merge_footnotes(remote_pp, local_pp, remote_mainDoc, remote_document, remote_footnotes);
                            remote_footnotes = footnotes;
                            break;
 
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":
                            merge_endnotes(remote_pp, local_pp, remote_mainDoc, remote_document, remote_endnotes);
                            remote_endnotes = endnotes;
                            break;

                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":
                            merge_styles(remote_pp, local_pp, remote_mainDoc, remote_document, remote_footnotes, remote_endnotes);
                            break;

                        // Merge styles after merging the footnotes, so the changes will be applied to the correct document/footnotes
                        case "application/vnd.ms-word.stylesWithEffects+xml":
                            merge_styles(remote_pp, local_pp, remote_mainDoc, remote_document, remote_footnotes, remote_endnotes);
                            break;

                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml":
                            merge_fonts(remote_pp, local_pp, remote_mainDoc, remote_document);
                            break;

                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":
                            merge_numbering(remote_pp, local_pp, remote_mainDoc, remote_document);
                            break;

                        default:
                            break;
                    }
                }

                // If this external PackagePart does not exits in the internal document then we can simply copy it.
                else
                {
                    var packagePart = clonePackagePart(remote_pp);
                    switch (remote_pp.ContentType)
                    {
                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml":
                            endnotesPart = packagePart;
                            endnotes = remote_endnotes;
                            break;

                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml":
                            footnotesPart = packagePart;
                            footnotes = remote_footnotes;
                            break;

                        case "application/vnd.openxmlformats-officedocument.custom-properties+xml":
                            break;

                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml":
                            stylesPart = packagePart;
                            using (TextReader tr = new StreamReader(stylesPart.GetStream()))
                                styles = XDocument.Load(tr);
                            break;

                        case "application/vnd.ms-word.stylesWithEffects+xml":
                            stylesWithEffectsPart = packagePart;
                            using (TextReader tr = new StreamReader(stylesWithEffectsPart.GetStream()))
                                stylesWithEffects = XDocument.Load(tr);
                            break;

                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml":
                            fontTablePart = packagePart;
                            using (TextReader tr = new StreamReader(fontTablePart.GetStream()))
                                fontTable = XDocument.Load(tr);
                            break;

                        case "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml":
                            numberingPart = packagePart;
                            using (TextReader tr = new StreamReader(numberingPart.GetStream()))
                                numbering = XDocument.Load(tr);
                            break;

                    }

                    clonePackageRelationship(remote_document, remote_pp, remote_mainDoc);
                }
            }

            foreach (var hyperlink_rel in remote_document.mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"))
            {
                var old_rel_Id = hyperlink_rel.Id;
                var new_rel_Id = mainPart.CreateRelationship(hyperlink_rel.TargetUri, hyperlink_rel.TargetMode, hyperlink_rel.RelationshipType).Id;
                var hyperlink_refs = remote_mainDoc.Descendants(XName.Get("hyperlink", DocX.w.NamespaceName));
                foreach (var hyperlink_ref in hyperlink_refs)
                {
                    XAttribute a0 = hyperlink_ref.Attribute(XName.Get("id", DocX.r.NamespaceName));
                    if (a0 != null && a0.Value == old_rel_Id)
                    {
                        a0.SetValue(new_rel_Id);
                    }
                }
            }

            ////ole object links
            foreach (var oleObject_rel in remote_document.mainPart.GetRelationshipsByType("http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject"))
            {
                var old_rel_Id = oleObject_rel.Id;
                var new_rel_Id = mainPart.CreateRelationship(oleObject_rel.TargetUri, oleObject_rel.TargetMode, oleObject_rel.RelationshipType).Id;
                var oleObject_refs = remote_mainDoc.Descendants(XName.Get("OLEObject", "urn:schemas-microsoft-com:office:office"));
                foreach (var oleObject_ref in oleObject_refs)
                {
                    XAttribute a0 = oleObject_ref.Attribute(XName.Get("id", DocX.r.NamespaceName));
                    if (a0 != null && a0.Value == old_rel_Id)
                    {
                        a0.SetValue(new_rel_Id);
                    }
                }
            }


            foreach (PackagePart remote_pp in ppc)
            {
                if (imageContentTypes.Contains(remote_pp.ContentType))
                {
                    merge_images(remote_pp, remote_document, remote_mainDoc, remote_pp.ContentType);
                }
            }

            int id = 0;
            var local_docPrs = mainDoc.Root.Descendants(XName.Get("docPr", DocX.wp.NamespaceName));
            foreach (var local_docPr in local_docPrs)
            {
                XAttribute a_id = local_docPr.Attribute(XName.Get("id"));
                int a_id_value;
                if (a_id != null && int.TryParse(a_id.Value, out a_id_value))
                    if (a_id_value > id)
                        id = a_id_value;
            }
            id++;

            // docPr must be sequential
            var docPrs = remote_body.Descendants(XName.Get("docPr", DocX.wp.NamespaceName));
            foreach (var docPr in docPrs)
            {
                docPr.SetAttributeValue(XName.Get("id"), id);
                id++;
            }

            // Add the remote documents contents to this document.
            XElement local_body = mainDoc.Root.Element(XName.Get("body", DocX.w.NamespaceName));
            local_body.Add(remote_body.Elements());

            // Copy any missing root attributes to the local document.
            foreach (XAttribute a in remote_mainDoc.Root.Attributes())
            {
                if (mainDoc.Root.Attribute(a.Name) == null)
                {
                    mainDoc.Root.SetAttributeValue(a.Name, a.Value);
                }
            }

        }
Ejemplo n.º 28
0
        protected PackagePart clonePackagePart(PackagePart pp)
        {
            PackagePart new_pp = package.CreatePart(pp.Uri, pp.ContentType);

            using (Stream s_read = pp.GetStream())
            {
                using (Stream s_write = new_pp.GetStream(FileMode.Create))
                {
                    byte[] buffer = new byte[32768];
                    int read;
                    while ((read = s_read.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        s_write.Write(buffer, 0, read);
                    }
                }
            }

            return new_pp;
        }
Ejemplo n.º 29
0
        private void merge_customs(PackagePart remote_pp, PackagePart local_pp, XDocument remote_mainDoc)
        {
            // Get the remote documents custom.xml file.
            XDocument remote_custom_document;
            using (TextReader tr = new StreamReader(remote_pp.GetStream()))
                remote_custom_document = XDocument.Load(tr);

            // Get the local documents custom.xml file.
            XDocument local_custom_document;
            using (TextReader tr = new StreamReader(local_pp.GetStream()))
                local_custom_document = XDocument.Load(tr);

            IEnumerable<int> pids =
            (
                from d in remote_custom_document.Root.Descendants()
                where d.Name.LocalName == "property"
                select int.Parse(d.Attribute(XName.Get("pid")).Value)
            );

            int pid = pids.Max() + 1;

            foreach (XElement remote_property in remote_custom_document.Root.Elements())
            {
                bool found = false;
                foreach (XElement local_property in local_custom_document.Root.Elements())
                {
                    XAttribute remote_property_name = remote_property.Attribute(XName.Get("name"));
                    XAttribute local_property_name = local_property.Attribute(XName.Get("name"));

                    if (remote_property != null && local_property_name != null && remote_property_name.Value.Equals(local_property_name.Value))
                        found = true;
                }

                if (!found)
                {
                    remote_property.SetAttributeValue(XName.Get("pid"), pid);
                    local_custom_document.Root.Add(remote_property);

                    pid++;
                }
            }

            // Save the modified local custom styles.xml file.
            using (TextWriter tw = new StreamWriter(local_pp.GetStream(FileMode.Create, FileAccess.Write)))
                local_custom_document.Save(tw, SaveOptions.None);
        }
Ejemplo n.º 30
0
        private void merge_images(PackagePart remote_pp, DocX remote_document, XDocument remote_mainDoc, String contentType)
        {
            // Before doing any other work, check to see if this image is actually referenced in the document.
            // In my testing I have found cases of Images inside documents that are not referenced
            var remote_rel = remote_document.mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(remote_pp.Uri.OriginalString.Replace("/word/", ""))).FirstOrDefault();
            if (remote_rel == null) {
            	remote_rel = remote_document.mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(remote_pp.Uri.OriginalString)).FirstOrDefault();
            	if (remote_rel == null)
            		return;
            }
            String remote_Id = remote_rel.Id;

            String remote_hash = ComputeMD5HashString(remote_pp.GetStream());
            var image_parts = package.GetParts().Where(pp => pp.ContentType.Equals(contentType));

            bool found = false;
            foreach (var part in image_parts)
            {
                String local_hash = ComputeMD5HashString(part.GetStream());
                if (local_hash.Equals(remote_hash))
                {
                    // This image already exists in this document.
                    found = true;

                    var local_rel = mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(part.Uri.OriginalString.Replace("/word/", ""))).FirstOrDefault();
                    if (local_rel == null)
                    {
                        local_rel = mainPart.GetRelationships().Where(r => r.TargetUri.OriginalString.Equals(part.Uri.OriginalString)).FirstOrDefault();
                    }
                    if (local_rel != null)
                    {
                        String new_Id = local_rel.Id;

                        // Replace all instances of remote_Id in the local document with local_Id
                        var elems = remote_mainDoc.Descendants(XName.Get("blip", DocX.a.NamespaceName));
                        foreach (var elem in elems)
                        {
                            XAttribute embed = elem.Attribute(XName.Get("embed", DocX.r.NamespaceName));
                            if (embed != null && embed.Value == remote_Id)
                            {
                                embed.SetValue(new_Id);
                            }
                        }

                        // Replace all instances of remote_Id in the local document with local_Id (for shapes as well)
                        var v_elems = remote_mainDoc.Descendants(XName.Get("imagedata", DocX.v.NamespaceName));
                        foreach (var elem in v_elems)
                        {
                            XAttribute id = elem.Attribute(XName.Get("id", DocX.r.NamespaceName));
                            if (id != null && id.Value == remote_Id)
                            {
                                id.SetValue(new_Id);
                            }
                        }
                    }

                    break;
                }
            }

            // This image does not exist in this document.
            if (!found)
            {
                String new_uri = remote_pp.Uri.OriginalString;
                new_uri = new_uri.Remove(new_uri.LastIndexOf("/"));
                //new_uri = new_uri.Replace("word/", "");
                new_uri += "/" + Guid.NewGuid().ToString() + contentType.Replace("image/", ".");
                if (!new_uri.StartsWith("/"))
                    new_uri = "/" + new_uri;

                PackagePart new_pp = package.CreatePart(new Uri(new_uri, UriKind.Relative), remote_pp.ContentType);

                using (Stream s_read = remote_pp.GetStream())
                {
                    using (Stream s_write = new_pp.GetStream(FileMode.Create))
                    {
                        byte[] buffer = new byte[32768];
                        int read;
                        while ((read = s_read.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            s_write.Write(buffer, 0, read);
                        }
                    }
                }

                PackageRelationship pr = mainPart.CreateRelationship(new Uri(new_uri, UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");

                String new_Id = pr.Id;

                //Check if the remote relationship id is a default rId from Word
                Match defRelId = Regex.Match(remote_Id, @"rId\d+", RegexOptions.IgnoreCase);

                // Replace all instances of remote_Id in the local document with local_Id
                var elems = remote_mainDoc.Descendants(XName.Get("blip", DocX.a.NamespaceName));
                foreach (var elem in elems)
                {
                    XAttribute embed = elem.Attribute(XName.Get("embed", DocX.r.NamespaceName));
                    if (embed != null && embed.Value == remote_Id)
                    {
                        embed.SetValue(new_Id);
                    }
                }

                if (!defRelId.Success)
				{
	               	// Replace all instances of remote_Id in the local document with local_Id
	                var elems_local = mainDoc.Descendants(XName.Get("blip", DocX.a.NamespaceName));
	                foreach (var elem in elems_local)
	                {
	                    XAttribute embed = elem.Attribute(XName.Get("embed", DocX.r.NamespaceName));
	                    if (embed != null && embed.Value == remote_Id)
	                    {
	                        embed.SetValue(new_Id);
	                    }
	                }
					
	                                
	                // Replace all instances of remote_Id in the local document with local_Id
	                var v_elems_local = mainDoc.Descendants(XName.Get("imagedata", DocX.v.NamespaceName));
	                foreach (var elem in v_elems_local)
	                {
	                    XAttribute id = elem.Attribute(XName.Get("id", DocX.r.NamespaceName));
	                    if (id != null && id.Value == remote_Id)
	                    {
	                        id.SetValue(new_Id);
	                    }
	                }
				}


                // Replace all instances of remote_Id in the local document with local_Id (for shapes as well)
                var v_elems = remote_mainDoc.Descendants(XName.Get("imagedata", DocX.v.NamespaceName));
                foreach (var elem in v_elems)
                {
                    XAttribute id = elem.Attribute(XName.Get("id", DocX.r.NamespaceName));
                    if (id != null && id.Value == remote_Id)
                    {
                        id.SetValue(new_Id);
                    }
                }
            }
        }
Ejemplo n.º 31
0
 public ZipPackageFile(PackagePart part)
     : this(UriUtility.GetPath(part.Uri), part.GetStream().ToStreamFactory())
 {
 }
Ejemplo n.º 32
0
        public override Stream GetResponseStream()
        {
            CheckDisposed();

            // redirect
            if (FromPackageCache)
                return _cachedResponse.GetResponseStream();

            EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXGetStreamBegin);

#if DEBUG
            if (PackWebRequestFactory._traceSwitch.Enabled)
                System.Diagnostics.Trace.TraceInformation(
                        DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
                        System.Threading.Thread.CurrentThread.ManagedThreadId + ": " +
                        "PackWebResponse - GetResponseStream()");
#endif
            // create and return only a single stream for multiple calls
            if (_responseStream == null)
            {
                // can't do this until the response is available
                WaitForResponse();  // after this call, we have a viable _fullResponse object because WaitForResponse would have thrown otherwise

                // determine content length
                long streamLength = _fullResponse.ContentLength;

#if DEBUG
                if (_forceWebResponseLengthFailureSwitch.Enabled)
                    streamLength = -1;

                // special handling for servers that won't or can't give us the length of the resource - byte-range downloading is impossible
                if (streamLength <= 0)
                {
                    if (PackWebRequestFactory._traceSwitch.Enabled)
                        System.Diagnostics.Trace.TraceInformation(
                                DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
                                System.Threading.Thread.CurrentThread.ManagedThreadId + ": " +
                                "PackWebResponse - GetResponseStream() - stream length not available - disabling progressive download");
                }
#endif

                //  Start reading data from the response stream.
                _responseStream = _fullResponse.GetResponseStream();

                // require NetStream for progressivity and for network streams that don't
                // directly support seeking.
                if (!_responseStream.CanSeek || !_innerUri.IsFile)
                {
                    // Create a smart stream that will spawn byte-range requests as needed
                    // and support seeking. Each read has overhead of Mutex and many of the
                    // reads come through asking for 4 bytes at a time
                    _responseStream = new NetStream(
                        _responseStream, streamLength,
                        _innerUri, _webRequest, _fullResponse);

                    // wrap our stream for efficiency (short reads are expanded)
                    _responseStream = new BufferedStream(_responseStream);
                }

                // handle degenerate case where there is no part name
                if (_partName == null)
                {
                    _fullStreamLength = streamLength;    // entire container
                    _mimeType = WpfWebRequestHelper.GetContentType(_fullResponse);

                    // pass this so that ResponseStream holds a reference to us until the stream is closed
                    _responseStream = new ResponseStream(_responseStream, this);
                }
                else
                {
                    // open container on netStream
                    Package c = Package.Open(_responseStream);
                    if (!c.PartExists(_partName))
                        throw new WebException(SR.Get(SRID.WebResponsePartNotFound));

                    PackagePart p = c.GetPart(_partName);
                    Stream s = p.GetStream(FileMode.Open, FileAccess.Read);

                    _mimeType = new MS.Internal.ContentType(p.ContentType);      // save this for use in ContentType property - may still be null
                    _fullStreamLength = s.Length;   // just this stream

                    // Wrap in a ResponseStream so that this container will be released
                    // when the stream is closed
                    _responseStream = new ResponseStream(s, this, _responseStream, c);
                }

                // length available? (-1 means the server chose not to report it)
                if (_fullStreamLength >= 0)
                {
                    _lengthAvailable = true;
                }
            }

            EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXGetStreamEnd);

            return _responseStream;
        }
Ejemplo n.º 33
0
 /// <summary>
 /// Extracts an individual file
 /// </summary>
 /// <param name="Document">Document to extract</param>
 /// <param name="Folder">Folder to extract it into</param>
 protected virtual void Extract(PackagePart Document, string Folder)
 {
     Folder.ThrowIfNullOrEmpty("Folder");
     string Location = Folder + System.Web.HttpUtility.UrlDecode(Document.Uri.ToString()).Replace('\\', '/');
     new DirectoryInfo(Path.GetDirectoryName(Location)).Create();
     byte[] Data = new byte[1024];
     using (FileStream FileStream = new FileStream(Location, FileMode.Create))
     {
         Stream DocumentStream = Document.GetStream();
         while (true)
         {
             int Size = DocumentStream.Read(Data, 0, 1024);
             FileStream.Write(Data, 0, Size);
             if (Size != 1024)
                 break;
         }
     }
 }
Ejemplo n.º 34
0
        internal ExcelPicture(ExcelDrawings drawings, XmlNode node, FileInfo imageFile)
            : base(drawings, node, "xdr:pic/xdr:nvPicPr/xdr:cNvPr/@name")
        {
            XmlElement picNode = node.OwnerDocument.CreateElement("xdr", "pic", ExcelPackage.schemaSheetDrawings);
            node.InsertAfter(picNode, node.SelectSingleNode("xdr:to", NameSpaceManager));
            picNode.InnerXml = PicStartXml();

            node.InsertAfter(node.OwnerDocument.CreateElement("xdr", "clientData", ExcelPackage.schemaSheetDrawings), picNode);

            Package package = drawings.Worksheet.xlPackage.Package;
            SetContentType(imageFile.Extension);
            _image = Image.FromFile(imageFile.FullName);
            ImageConverter ic = new ImageConverter();
            byte[] img = (byte[])ic.ConvertTo(_image, typeof(byte[]));

            string relID = GetPictureRelID(img);

            if (relID == "")
            {
                UriPic = GetNewUri(package, "/xl/media/image{0}" + imageFile.Extension);
                Part = package.CreatePart(UriPic, ContentType, CompressionOption.NotCompressed);

                //Save the picture to package.
                byte[] file = File.ReadAllBytes(imageFile.FullName);
                var strm = Part.GetStream(FileMode.Create, FileAccess.Write);
                strm.Write(file, 0, file.Length);

                PackageRelationship picRelation = drawings.Part.CreateRelationship(UriPic, TargetMode.Internal, ExcelPackage.schemaRelationships + "/image");
                relID = picRelation.Id;
                AddNewPicture(img, relID);

            }
            else
            {
                var rel = _drawings.Part.GetRelationship(relID);
                UriPic = rel.TargetUri;
            }
            SetPosDefaults(Image);
            //Create relationship
            node.SelectSingleNode("xdr:pic/xdr:blipFill/a:blip/@r:embed", NameSpaceManager).Value = relID;
            package.Flush();
        }
Ejemplo n.º 35
0
            /// <summary>
            /// Cache version of GetResponseStream
            /// </summary>
            /// <returns></returns>
            internal Stream GetResponseStream()
            {
                // prevent concurrent access to GetPart() which is not thread-safe
                lock (_cacheEntry)
                {
#if DEBUG
            if (PackWebRequestFactory._traceSwitch.Enabled)
                System.Diagnostics.Trace.TraceInformation(
                        DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
                        System.Threading.Thread.CurrentThread.ManagedThreadId + ": " +
                        "CachedResponse - Getting response stream");
#endif
                    // only one copy
                    if (_parent._responseStream == null)
                    {
                        // full container request?
                        if (_parent._partName == null)
                        {
                            Debug.Assert(false, "Cannot return full-container stream from cached container object");
                        }
                        else
                        {
#if DEBUG
                            if (PackWebRequestFactory._traceSwitch.Enabled)
                                System.Diagnostics.Trace.TraceInformation(
                                        DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
                                        System.Threading.Thread.CurrentThread.ManagedThreadId + ": " +
                                        "CachedResponse - Getting part " + _parent._partName);
#endif
                            // open the requested stream
                            PackagePart p = _cacheEntry.GetPart(_parent._partName);
#if DEBUG
                            if (PackWebRequestFactory._traceSwitch.Enabled)
                                System.Diagnostics.Trace.TraceInformation(
                                        DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
                                        System.Threading.Thread.CurrentThread.ManagedThreadId + ": " +
                                        "CachedResponse - Getting part stream ");
#endif
                            Stream s = p.GetStream(FileMode.Open, FileAccess.Read);

                            // Unless package is thread-safe, wrap the returned stream so that
                            // package access is serialized
                            if (!_cachedPackageIsThreadSafe)
                            {
                                // Return a stream that provides thread-safe access
                                // to the cached package by locking on the cached Package
                                s = new SynchronizingStream(s, _cacheEntry);
                            }

#if DEBUG
                            if (PackWebRequestFactory._traceSwitch.Enabled)
                                System.Diagnostics.Trace.TraceInformation(
                                        DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
                                        System.Threading.Thread.CurrentThread.ManagedThreadId + ": " +
                                        "CachedResponse - Getting part contenttype");
#endif
                            _parent._mimeType = new MS.Internal.ContentType(p.ContentType);

                            // cache this in case they ask for it after the stream has been closed
                            _parent._lengthAvailable = s.CanSeek;
                            if (s.CanSeek)
                            {
#if DEBUG
                                if (PackWebRequestFactory._traceSwitch.Enabled)
                                    System.Diagnostics.Trace.TraceInformation(
                                            DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
                                            System.Threading.Thread.CurrentThread.ManagedThreadId + ": " +
                                            "CachedResponse - Length is available from stream");
#endif
                                _parent._fullStreamLength = s.Length;
                            }
#if DEBUG
                            else
                            {
                                if (PackWebRequestFactory._traceSwitch.Enabled)
                                    System.Diagnostics.Trace.TraceInformation(
                                            DateTime.Now.ToLongTimeString() + " " + DateTime.Now.Millisecond + " " +
                                            System.Threading.Thread.CurrentThread.ManagedThreadId + ": " +
                                            "CachedResponse - Length is not available from stream" + _parent._partName);
                            }
#endif
                            // re-use existing member variable
                            _parent._responseStream = s;
                        }
                    }
                }

                return _parent._responseStream;
            }
Ejemplo n.º 36
0
 private string ExtractPart(PackagePart packagePart, string targetDirectory)
 {
     string packageRelative = Uri.UnescapeDataString(packagePart.Uri.ToString().TrimStart('/'));
     string fullPath = Path.Combine(targetDirectory, packageRelative);
     Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
     using (var fileStream = new FileStream(fullPath, FileMode.Create))
     {
         CopyStream(packagePart.GetStream(), fileStream);
     }
     return fullPath;
 }
Ejemplo n.º 37
0
        // Deserialize properties part.
        private void ParseCorePropertyPart(PackagePart part)
        {
            XmlReaderSettings xrs = new XmlReaderSettings();

            xrs.NameTable = _nameTable;
            using (Stream stream = part.GetStream(FileMode.Open, FileAccess.Read))

                // Create a reader that uses _nameTable so as to use the set of tag literals
                // in effect as a set of atomic identifiers.
                using (XmlReader reader = XmlReader.Create(stream, xrs))
                {
                    //This method expects the reader to be in ReadState.Initial.
                    //It will make the first read call.
                    PackagingUtilities.PerformInitialReadAndVerifyEncoding(reader);

                    //Note: After the previous method call the reader should be at the first tag in the markup.
                    //MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
                    //If the reader is currently at a content node then this function call is a no-op
                    if (reader.MoveToContent() != XmlNodeType.Element ||
                        (object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.PackageCorePropertiesNamespace) ||
                        (object)reader.LocalName != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.CoreProperties))
                    {
                        throw new XmlException(SR.CorePropertiesElementExpected,
                                               null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                    }

                    // The schema is closed and defines no attributes on the root element.
                    if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) != 0)
                    {
                        throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
                                               null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                    }

                    // Iterate through property elements until EOF. Note the proper closing of all
                    // open tags is checked by the reader itself.
                    // This loop deals only with depth-1 start tags. Handling of element content
                    // is delegated to dedicated functions.
                    int attributesCount;

                    while (reader.Read() && reader.MoveToContent() != XmlNodeType.None)
                    {
                        // Ignore end-tags. We check element errors on opening tags.
                        if (reader.NodeType == XmlNodeType.EndElement)
                        {
                            continue;
                        }

                        // Any content markup that is not an element here is unexpected.
                        if (reader.NodeType != XmlNodeType.Element)
                        {
                            throw new XmlException(SR.PropertyStartTagExpected,
                                                   null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                        }

                        // Any element below the root should open at level 1 exclusively.
                        if (reader.Depth != 1)
                        {
                            throw new XmlException(SR.NoStructuredContentInsideProperties,
                                                   null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                        }

                        attributesCount = PackagingUtilities.GetNonXmlnsAttributeCount(reader);

                        // Property elements can occur in any order (xsd:all).
                        object         localName      = reader.LocalName;
                        PackageXmlEnum xmlStringIndex = PackageXmlStringTable.GetEnumOf(localName);
                        string?        valueType      = PackageXmlStringTable.GetValueType(xmlStringIndex);

                        if (Array.IndexOf(s_validProperties, xmlStringIndex) == -1) // An unexpected element is an error.
                        {
                            throw new XmlException(
                                      SR.Format(SR.InvalidPropertyNameInCorePropertiesPart, reader.LocalName),
                                      null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                        }

                        // Any element not in the valid core properties namespace is unexpected.
                        // The following is an object comparison, not a string comparison.
                        if ((object)reader.NamespaceURI != PackageXmlStringTable.GetXmlStringAsObject(PackageXmlStringTable.GetXmlNamespace(xmlStringIndex)))
                        {
                            throw new XmlException(SR.UnknownNamespaceInCorePropertiesPart,
                                                   null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                        }

                        if (string.CompareOrdinal(valueType, "String") == 0)
                        {
                            // The schema is closed and defines no attributes on this type of element.
                            if (attributesCount != 0)
                            {
                                throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
                                                       null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                            }

                            RecordNewBinding(xmlStringIndex, GetStringData(reader), true /*initializing*/, reader);
                        }
                        else if (string.CompareOrdinal(valueType, "DateTime") == 0)
                        {
                            int allowedAttributeCount = (object)reader.NamespaceURI ==
                                                        PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace)
                                                        ? 1 : 0;

                            // The schema is closed and defines no attributes on this type of element.
                            if (attributesCount != allowedAttributeCount)
                            {
                                throw new XmlException(SR.Format(SR.PropertyWrongNumbOfAttribsDefinedOn, reader.Name),
                                                       null, ((IXmlLineInfo)reader).LineNumber, ((IXmlLineInfo)reader).LinePosition);
                            }

                            if (allowedAttributeCount != 0)
                            {
                                ValidateXsiType(reader,
                                                PackageXmlStringTable.GetXmlStringAsObject(PackageXmlEnum.DublinCoreTermsNamespace),
                                                W3cdtf);
                            }

                            RecordNewBinding(xmlStringIndex, GetDateData(reader), true /*initializing*/, reader);
                        }
                        else // An unexpected element is an error.
                        {
                            Debug.Fail("Unknown value type for properties");
                        }
                    }
                }
        }