CreateRelationship() публичный Метод

public CreateRelationship ( Uri targetUri, TargetMode targetMode, string relationshipType ) : PackageRelationship
targetUri System.Uri
targetMode TargetMode
relationshipType string
Результат PackageRelationship
Пример #1
0
        /// <summary>
        /// Creates a new instance of the ExcelPackage class based on a existing file or creates a new file. 
        /// </summary>
        /// <param name="newFile">If newFile exists, it is opened.  Otherwise it is created from scratch.</param>
        private ExcelPackage(FileInfo newFile)
        {
            _outputFolderPath = newFile.DirectoryName;
            if (newFile.Exists)
            {
                // open the existing package
                _package = Package.Open(newFile.FullName, FileMode.Open, FileAccess.ReadWrite);
            }
            else
            {
                // create a new package and add the main workbook.xml part
                _package = Package.Open(newFile.FullName, FileMode.Create, FileAccess.ReadWrite);

                // save a temporary part to create the default application/xml content type
                var uriDefaultContentType = new Uri("/default.xml", UriKind.Relative);
                var partTemp = _package.CreatePart(uriDefaultContentType, "application/xml");

                var workbook = Workbook.WorkbookXml; // this will create the workbook xml in the package

                // create the relationship to the main part
                _package.CreateRelationship(Workbook.WorkbookUri,
                                            TargetMode.Internal,
                                            schemaRelationships + "/officeDocument");

                // remove the temporary part that created the default xml content type
                _package.DeletePart(uriDefaultContentType);
            }
        }
        void AddPackageManifest(Package package, PackageDefinition manifest)
        {
            var manifestPartUri = PackUriHelper.CreatePartUri(new Uri("/package.xml", UriKind.Relative));
            var manifestPart = package.CreatePart(manifestPartUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Maximum);
            using (var manifestPartStream = manifestPart.GetStream())
            {
                manifest.ToXml().Save(manifestPartStream);
            }

            package.CreateRelationship(manifestPartUri, TargetMode.External, AzureCloudServiceConventions.CtpFormatPackageDefinitionRelationshipType);
        }
		private void WriteCache(Package package)
		{
			Uri cacheUri = GetPartUri(cacheName);
			PackagePart part = package.CreatePart(cacheUri, MediaTypeNames.Application.Octet, CompressionOption.Fast);

			BinaryFormatter formatter = new BinaryFormatter();
			using (Stream stream = part.GetStream())
			{
				formatter.Serialize(stream, Cache);
			}

			package.CreateRelationship(cacheUri, TargetMode.Internal, D3AssemblyConstants.DefaultXmlNamespace);
		}
Пример #4
0
    static void WriteManifest(Package package, string nuspecPath)
    {
        var uri = PackUriHelper.CreatePartUri(new Uri(Uri.EscapeDataString(Path.GetFileName(nuspecPath)), UriKind.Relative));

        // Create the manifest relationship
        package.CreateRelationship(uri, TargetMode.Internal, "http://schemas.microsoft.com/packaging/2010/07/manifest");

        // Create the part
        var packagePart = package.CreatePart(uri, "application/octet", CompressionOption.Maximum);

        using (var stream = packagePart.GetStream())
        using (var fileStream = File.OpenRead(nuspecPath))
        {
            fileStream.CopyTo(stream);
        }
    }
Пример #5
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);
        }
        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();
        }
Пример #7
0
        AddThumbnail(
            XpsImageType imageType
            )
        {
            CheckDisposed();

            if (CurrentXpsManager == null)
            {
                throw new InvalidOperationException(SR.Get(SRID.ReachPackaging_DocumentWasClosed));
            }
            _thumbnail = CurrentXpsManager.AddThumbnail(imageType, this, Thumbnail);
            Package metroPackage = CurrentXpsManager.MetroPackage;

            metroPackage.CreateRelationship(_thumbnail.Uri,
                                            TargetMode.Internal,
                                            XpsS0Markup.ThumbnailRelationshipName
                                            );
            return(_thumbnail);
        }
Пример #8
0
        private void WriteManifest(Package package)
        {
            Uri uri = UriUtility.CreatePartUri(Id + Constants.ManifestExtension);

            // Create the manifest relationship
            package.CreateRelationship(uri, TargetMode.Internal, Constants.PackageRelationshipNamespace + ManifestRelationType);

            // Create the part
            PackagePart packagePart = package.CreatePart(uri, DefaultContentType, CompressionOption.Maximum);

            using (Stream stream = packagePart.GetStream())
            {
                Manifest manifest = Manifest.Create(this);
                manifest.Save(stream);
            }
        }
        private void WriteManifest(Package package, int minimumManifestVersion)
        {
            Uri uri = UriUtility.CreatePartUri(Id + Constants.ManifestExtension);

            // Create the manifest relationship
            package.CreateRelationship(uri, TargetMode.Internal,
                                       Constants.PackageRelationshipNamespace + ManifestRelationType);

            // Create the part
            PackagePart packagePart = package.CreatePart(uri, DefaultContentType, CompressionOption.Maximum);

            using (Stream stream = packagePart.GetStream())
            {
                Manifest manifest = Manifest.Create(this);
                //if (PackageAssemblyReferences.Any())
                //{
                //    manifest.Metadata.References = new List<ManifestReference>(
                //        PackageAssemblyReferences.Select(reference => new ManifestReference {File = reference.File}));
                //}
                manifest.Save(stream, minimumManifestVersion);
            }
        }
Пример #10
0
 /// <summary>
 /// Adds a file to the zip file
 /// </summary>
 /// <param name="File">File to add</param>
 /// <param name="FileInfo">File information</param>
 /// <param name="Package">Package to add the file to</param>
 protected virtual void AddFile(string File, FileInfo FileInfo, Package Package)
 {
     File.ThrowIfNullOrEmpty("File");
     if (!FileInfo.Exists)
         throw new ArgumentException("FileInfo does not exist");
     Uri UriPath = PackUriHelper.CreatePartUri(new Uri(File, UriKind.Relative));
     PackagePart PackagePart = Package.CreatePart(UriPath, System.Net.Mime.MediaTypeNames.Text.Xml, CompressionOption.Maximum);
     byte[] Data = FileInfo.ReadBinary();
     PackagePart.GetStream().Write(Data, 0, Data.Count());
     Package.CreateRelationship(PackagePart.Uri, TargetMode.Internal, "http://schemas.microsoft.com/opc/2006/sample/document");
 }
Пример #11
0
        internal static void PostCreation(Package package, DocumentTypes documentType = DocumentTypes.Document)
        {
            XDocument mainDoc, stylesDoc, numberingDoc;

            #region MainDocumentPart
            // Create the main document part for this package
            PackagePart mainDocumentPart;
            if (documentType == DocumentTypes.Document)
            {
                mainDocumentPart = package.CreatePart(new Uri("/word/document.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml");
            }
            else
            {
                mainDocumentPart = package.CreatePart(new Uri("/word/document.xml", UriKind.Relative), "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml");
            }
            package.CreateRelationship(mainDocumentPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument");

            // Load the document part into a XDocument object
            using (TextReader tr = new StreamReader(mainDocumentPart.GetStream(FileMode.Create, FileAccess.ReadWrite)))
            {
                mainDoc = XDocument.Parse
                (@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
                   <w:document xmlns:ve=""http://schemas.openxmlformats.org/markup-compatibility/2006"" xmlns:o=""urn:schemas-microsoft-com:office:office"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships"" xmlns:m=""http://schemas.openxmlformats.org/officeDocument/2006/math"" xmlns:v=""urn:schemas-microsoft-com:vml"" xmlns:wp=""http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"" xmlns:w10=""urn:schemas-microsoft-com:office:word"" xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main"" xmlns:wne=""http://schemas.microsoft.com/office/word/2006/wordml"" xmlns:a=""http://schemas.openxmlformats.org/drawingml/2006/main"" xmlns:c=""http://schemas.openxmlformats.org/drawingml/2006/chart"">
                   <w:body>
                    <w:sectPr w:rsidR=""003E25F4"" w:rsidSect=""00FC3028"">
                        <w:pgSz w:w=""11906"" w:h=""16838""/>
                        <w:pgMar w:top=""1440"" w:right=""1440"" w:bottom=""1440"" w:left=""1440"" w:header=""708"" w:footer=""708"" w:gutter=""0""/>
                        <w:cols w:space=""708""/>
                        <w:docGrid w:linePitch=""360""/>
                    </w:sectPr>
                   </w:body>
                   </w:document>"
                );
            }

            // Save the main document
            using (TextWriter tw = new StreamWriter(mainDocumentPart.GetStream(FileMode.Create, FileAccess.Write)))
                mainDoc.Save(tw, SaveOptions.None);
            #endregion

            #region StylePart
            stylesDoc = HelperFunctions.AddDefaultStylesXml(package);
            #endregion

            #region NumberingPart
            numberingDoc = HelperFunctions.AddDefaultNumberingXml(package);
            #endregion

            package.Close();
        }
Пример #12
0
        void testingabpckg()
        {
            //try
            //{

            string InputFolder = @"C:\Users\inbakad\Desktop\input";

            //------------

            using (System.IO.Packaging.Package ABpackage = System.IO.Packaging.Package.Open(@"C:\Users\inbakad\Desktop\output\zenon.abpkg", FileMode.Create))
            {
                //get all files to be included in package in corresponding folder
                string[] filenames = Directory.GetFiles(InputFolder, "*.*", SearchOption.AllDirectories);
                foreach (string file in filenames)
                {
                    //create packagePart for each file in folder
                    //uri shall be relative --> remove absolute path, uri shall start with "/", uri doesn't accept blanks --> replace with %20
                    if (!InputFolder.EndsWith(Path.DirectorySeparatorChar.ToString()))
                    {
                        InputFolder = InputFolder + Path.DirectorySeparatorChar;
                    }
                    string fileRelativePath = file.ToString().Replace(InputFolder, "/");
                    //prepare path for uri:
                    //fileRelativePath = fileRelativePath.Replace(" ", "%20");
                    //fileRelativePath = fileRelativePath.Replace("{", "%7b");
                    //fileRelativePath = fileRelativePath.Replace("}", "%7d");
                    //convert path info into uri format
                    fileRelativePath = fileRelativePath.Replace("\\", "/");
                    var    packagePartUri = PackUriHelper.CreatePartUri(new Uri(fileRelativePath, UriKind.Relative));
                    string extension      = Path.GetExtension(@file);
                    if (string.IsNullOrEmpty(extension))
                    {
                        extension = ".%00";
                    }
                    var packagePart = ABpackage.CreatePart(packagePartUri, "part/" + extension);
                    //get file content and write to package part
                    using (var packageStream = packagePart.GetStream(FileMode.Create, FileAccess.ReadWrite))
                    {
                        try
                        {
                            using (FileStream currentFileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
                            {
                                currentFileStream.CopyTo(packageStream);
                                Console.WriteLine("Added file: " + file);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                        ABpackage.CreateRelationship(packagePart.Uri, TargetMode.Internal, "rel");
                    }
                }
                // Flush package to ensure all data is written to it
                ABpackage.Flush();
            }


            //----------------------
            //using (System.IO.Packaging.Package ABpackage = System.IO.Packaging.Package.Open(@"C:\Users\inbakad\Desktop\output\test.abpkg", FileMode.Create)) ;
            //{

            //   // get all files to be included in package in corresponding folder
            //    string[] filenames = Directory.GetFiles(InputFolder, "*.*", SearchOption.AllDirectories);
            //   // string[] encodefiles = new string[filenames.Length];
            //    int I = 0;
            //    foreach (string file in filenames)
            //    {
            //      //  create packagePart for each file in folder

            //      //  uri shall be relative-- > remove absolute path, uri shall start with "/", uri doesn't accept blanks --> replace with %20
            //        if (!InputFolder.EndsWith(Path.DirectorySeparatorChar.ToString()))
            //                InputFolder = InputFolder + Path.DirectorySeparatorChar;
            //        string fileRelativePath = file.ToString().Replace(InputFolder, "/");


            //        var packagePartUri = PackUriHelper.CreatePartUri(new Uri(fileRelativePath, UriKind.Relative));
            //        var pckg = PackUriHelper.CreatePartUri(new Uri(fileRelativePath));
            //       // encodefiles[I] = Uri.EscapeDataString(fileRelativePath);
            //       // I++;
            //        string escaprstr = Uri.EscapeDataString(filePath);
            //        //prepare path for uri:
            //        //remove blanks
            //        fileRelativePath = fileRelativePath.Replace(" ", "%20");
            //        fileRelativePath = fileRelativePath.Replace("{", "%7b");
            //        fileRelativePath = fileRelativePath.Replace("}", "%7d");
            //        convert path info into uri format
            //          fileRelativePath = fileRelativePath.Replace("\\", "/");
            //        var packagePartUri = PackUriHelper.CreatePartUri(new Uri(fileRelativePath, UriKind.Relative));
            //        // string extension = Path.GetExtension(@file);
            //        if (string.IsNullOrEmpty(extension))
            //            extension = ".%00";
            //        var packagePart = ABpackage.CreatePart(packagePartUri, "part/" + extension);
            //        get file content and write to package part
            //        using (var packageStream = packagePart.GetStream(FileMode.Create, FileAccess.ReadWrite))
            //        {
            //            try
            //            {
            //                using (FileStream currentFileStream = new FileStream(file, FileMode.Open, FileAccess.Read))
            //                {
            //                    currentFileStream.CopyTo(packageStream);
            //                    Console.WriteLine("Added file: " + file);
            //                }
            //            }
            //            catch (Exception ex)
            //            {
            //                Console.WriteLine(ex.Message);
            //            }
            //            // ABpackage.CreateRelationship(packagePart.Uri, TargetMode.Internal, "rel");
            //        }
            //    }
            // Flush package to ensure all data is written to it

            //}
            //ABpackage.Flush();
            // return encodefiles ;
        }
Пример #13
0
 /// <summary>
 /// Writes the thumbnail part of a CDDX file.
 /// </summary>
 /// <param name="package">The package to write to.</param>
 /// <param name="document">The document contatining the preview to write.</param>
 void WriteThumbnail(Package package)
 {
     // Create the thumbnail part
     Uri thumbnailUri = PackUriHelper.CreatePartUri(new Uri("docProps\\thumbnail.xml", UriKind.Relative));
     PackagePart thumbnailPart = package.CreatePart(thumbnailUri, CircuitDiagram.Render.XmlRenderer.PreviewContentType, CompressionOption.Normal);
     package.CreateRelationship(thumbnailPart.Uri, TargetMode.Internal, RelationshipTypes.Thumbnail);
     using (var stream = thumbnailPart.GetStream(FileMode.Create))
     {
         (RenderContext as CircuitDiagram.Render.XmlRenderer).WriteXmlTo(stream);
     }
 }
Пример #14
0
        /// <summary>
        /// Writes the metadata parts of a CDDX file.
        /// </summary>
        /// <param name="package">The package to write to.</param>
        /// <param name="document">Options for saving.</param>
        void WriteMetadata(Package package)
        {
            // Write core properties
            Uri coreUri = PackUriHelper.CreatePartUri(new Uri("docProps\\core.xml", UriKind.Relative));
            PackagePart corePart = package.CreatePart(coreUri, ContentTypeNames.CoreProperties, CompressionOption.Normal);
            package.CreateRelationship(coreUri, TargetMode.Internal, RelationshipTypes.CoreProperties);

            using (var stream = corePart.GetStream(FileMode.Create))
            {
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                writer.WriteStartElement("coreProperties", "http://schemas.circuit-diagram.org/circuitDiagramDocument/2012/metadata/core-properties");
                writer.WriteAttributeString("xmlns", "dc", null, Namespaces.DublinCore);

                if (!String.IsNullOrEmpty(Document.Metadata.Creator))
                    writer.WriteElementString("creator", Namespaces.DublinCore, Document.Metadata.Creator);
                if (!String.IsNullOrEmpty(Document.Metadata.Description))
                    writer.WriteElementString("description", Namespaces.DublinCore, Document.Metadata.Description);
                if (!String.IsNullOrEmpty(Document.Metadata.Title))
                    writer.WriteElementString("title", Namespaces.DublinCore, Document.Metadata.Title);

                if (Document.Metadata.Created.HasValue)
                    writer.WriteElementString("date", Namespaces.DublinCore, Document.Metadata.Created.Value.ToUniversalTime().ToString("u", System.Globalization.CultureInfo.InvariantCulture));

                writer.WriteEndElement();
                writer.WriteEndDocument();

                writer.Flush();
            }

            // Write extended properties
            Uri extendedUri = PackUriHelper.CreatePartUri(new Uri("docProps\\extended.xml", UriKind.Relative));
            PackagePart extendedPart = package.CreatePart(extendedUri, ContentTypeNames.ExtendedProperties, CompressionOption.Normal);
            package.CreateRelationship(extendedUri, TargetMode.Internal, RelationshipTypes.ExtendedProperties);

            using (var stream = extendedPart.GetStream(FileMode.Create))
            {
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                writer.WriteStartElement("extendedProperties", "http://schemas.circuit-diagram.org/circuitDiagramDocument/2012/metadata/extended-properties");

                writer.WriteElementString("application", ApplicationInfo.Name);
                writer.WriteElementString("appVersion", ApplicationInfo.Version);

                writer.WriteEndElement();
                writer.WriteEndDocument();

                writer.Flush();
            }
        }
Пример #15
0
        /// <summary>
        /// Writes the main document part of a CDDX file, and embeds components as required.
        /// </summary>
        /// <param name="package">The package to write to.</param>
        /// <param name="document">The document containing the metadata to write.</param>
        /// <param name="options">Options for saving.</param>
        void WriteMainDocument(Package package)
        {
            // Prevent EmbedComponents from being null
            if (EmbedComponents == null)
                EmbedComponents = new Dictionary<IOComponentType, EmbedComponentData>();

            // Create the main Document part
            Uri DocumentUri = PackUriHelper.CreatePartUri(new Uri("circuitdiagram\\Document.xml", UriKind.Relative));
            PackagePart DocumentPart = package.CreatePart(DocumentUri, ContentTypeNames.MainDocument, CompressionOption.Normal);
            package.CreateRelationship(DocumentPart.Uri, TargetMode.Internal, RelationshipTypes.Document);

            using (var stream = DocumentPart.GetStream(FileMode.Create))
            {
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
                writer.Formatting = Formatting.Indented;
                writer.WriteStartDocument();
                writer.WriteStartElement("circuit", Namespaces.Document);
                writer.WriteAttributeString("version", String.Format("{0:0.0}", FormatVersion));
                writer.WriteAttributeString("xmlns", "r", null, Namespaces.Relationships);
                writer.WriteAttributeString("xmlns", "ec", null, Namespaces.DocumentComponentDescriptions);

                // Document size
                writer.WriteStartElement("properties");
                writer.WriteElementString("width", Document.Size.Width.ToString());
                writer.WriteElementString("height", Document.Size.Height.ToString());
                writer.WriteEndElement();

                // Component types
                int idCounter = 0; // generate IDs for each IOComponentType
                Dictionary<IOComponentType, int> typeIDs = new Dictionary<IOComponentType, int>(); // store IDs for use in <elements> section
                writer.WriteStartElement("definitions");
                foreach (KeyValuePair<string, List<IOComponentType>> collection in Document.GetComponentTypes())
                {
                    writer.WriteStartElement("src");

                    // Write the collection name if it is known
                    if (collection.Key != IODocument.UnknownCollection)
                        writer.WriteAttributeString("col", collection.Key);

                    foreach (IOComponentType item in collection.Value)
                    {
                        writer.WriteStartElement("add");
                        writer.WriteAttributeString("id", idCounter.ToString());

                        // Write the collection item if it belongs to a collection
                        if (collection.Key != IODocument.UnknownCollection)
                            writer.WriteAttributeString("item", item.Item);

                        // Write additional attributes for opening with the same component description
                        if (!String.IsNullOrEmpty(item.Name))
                            writer.WriteAttributeString("name", Namespaces.DocumentComponentDescriptions, item.Name);
                        if (item.GUID != Guid.Empty)
                            writer.WriteAttributeString("guid", Namespaces.DocumentComponentDescriptions, item.GUID.ToString());

                        // Write additional attributes for embedding
                        if (EmbedComponents.ContainsKey(item))
                        {
                            // Generate unique file name
                            Uri descriptionPath = PackUriHelper.CreatePartUri(new Uri("circuitdiagram/components/" + item.Name.Replace(' ', '_') + EmbedComponents[item].FileExtension, UriKind.Relative));
                            int addedInt = 0;
                            while (package.PartExists(descriptionPath))
                            {
                                descriptionPath = PackUriHelper.CreatePartUri(new Uri("circuitdiagram/components/" + item.Name.Replace(' ', '_') + addedInt.ToString() + ".cdcom", UriKind.Relative));
                                addedInt++;
                            }

                            // Write part
                            PackagePart descriptionPart = package.CreatePart(PackUriHelper.CreatePartUri(descriptionPath), EmbedComponents[item].ContentType, CompressionOption.Normal);
                            using (var descriptionStream = descriptionPart.GetStream(FileMode.Create))
                            {
                                // Copy stream
                                int num;
                                byte[] buffer = new byte[4096];
                                while ((num = EmbedComponents[item].Stream.Read(buffer, 0, buffer.Length)) != 0)
                                {
                                    descriptionStream.Write(buffer, 0, num);
                                }
                            }
                            PackageRelationship relationship = DocumentPart.CreateRelationship(descriptionPart.Uri, TargetMode.Internal, CDDX.RelationshipTypes.IncludedComponent);

                            // Write the relationship ID
                            writer.WriteAttributeString("id", Namespaces.Relationships, relationship.Id);

                            // Store the relationship ID for use later
                            EmbedComponents[item].Tag = relationship.Id;
                        }
                        else if (EmbedComponents.ContainsKey(item) && !EmbedComponents[item].IsEmbedded)
                        {
                            // Already embedded - write relationship ID
                            writer.WriteAttributeString("id", Namespaces.DocumentComponentDescriptions, EmbedComponents[item].Tag as string);
                        }

                        writer.WriteEndElement();

                        // Store type ID
                        typeIDs.Add(item, idCounter);
                        idCounter++;
                    }

                    writer.WriteEndElement();
                }
                writer.WriteEndElement();

                // Elements
                writer.WriteStartElement("elements");
                if ((Options as CDDXSaveOptions).Layout)
                {
                    foreach (IOWire wire in Document.Wires)
                    {
                        // Write wire element

                        writer.WriteStartElement("w");
                        writer.WriteAttributeString("x", wire.Location.X.ToString());
                        writer.WriteAttributeString("y", wire.Location.Y.ToString());
                        writer.WriteAttributeString("o", wire.Orientation == Orientation.Horizontal ? "h" : "v");
                        writer.WriteAttributeString("sz", wire.Size.ToString());
                        writer.WriteEndElement();
                    }
                }
                foreach (IOComponent component in Document.Components)
                {
                    // Write component element

                    writer.WriteStartElement("c");
                    if (!String.IsNullOrEmpty(component.ID))
                        writer.WriteAttributeString("id", component.ID);
                    writer.WriteAttributeString("tp", "{" + typeIDs[component.Type].ToString() + "}");

                    // Write layout
                    if ((Options as CDDXSaveOptions).Layout)
                    {
                        if (component.Location.HasValue)
                        {
                            writer.WriteAttributeString("x", component.Location.Value.X.ToString());
                            writer.WriteAttributeString("y", component.Location.Value.Y.ToString());
                        }
                        if (component.Orientation.HasValue)
                            writer.WriteAttributeString("o", component.Orientation == Orientation.Horizontal ? "h" : "v");
                        if (component.Size.HasValue)
                            writer.WriteAttributeString("sz", component.Size.Value.ToString());
                        if (component.IsFlipped.HasValue)
                            writer.WriteAttributeString("flp", (component.IsFlipped.Value ? "true" : "false"));
                    }

                    // Write properties
                    if (component.Properties.Count > 0)
                    {
                        writer.WriteStartElement("prs");

                        foreach (IOComponentProperty property in component.Properties)
                        {
                            writer.WriteStartElement("p");
                            writer.WriteAttributeString("k", property.Key.ToString());
                            writer.WriteAttributeString("v", property.Value.ToString());
                            if (!property.IsStandard)
                                writer.WriteAttributeString("st", Namespaces.DocumentComponentDescriptions, "false");
                            writer.WriteEndElement();
                        }

                        writer.WriteEndElement();
                    }

                    // Write connections
                    if ((Options as CDDXSaveOptions).Connections && component.Connections.Count > 0)
                    {
                        writer.WriteStartElement("cns");

                        foreach (KeyValuePair<string, string> connection in component.Connections)
                        {
                            writer.WriteStartElement("cn");
                            writer.WriteAttributeString("pt", connection.Key);
                            writer.WriteAttributeString("id", connection.Value);
                            writer.WriteEndElement();
                        }

                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                }
                writer.WriteEndElement();

                writer.WriteEndElement();
                writer.WriteEndDocument();

                writer.Flush();
            }
        }
Пример #16
0
        /// <summary>
        /// Adds the speficied file to the package as document part
        /// </summary>
        private static void CreateDocumentPart(Package package, FileInfo file, string contentType, bool storeInDirectory)
        {
            Uri partUriDocument;

            // Convert system path and file names to Part URIs.
            if (storeInDirectory)
                partUriDocument = PackUriHelper.CreatePartUri(new Uri(Path.Combine(file.Directory.Name, file.Name), UriKind.Relative));
            else
                partUriDocument = PackUriHelper.CreatePartUri(new Uri(file.Name, UriKind.Relative));

            // Add the Document part to the Package
            PackagePart packagePartDocument = package.CreatePart(
                partUriDocument, contentType);

            // Copy the data to the Document Part
            using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
            {
                CopyStream(fileStream, packagePartDocument.GetStream());
            }

            // Add a Package Relationship to the Document Part
            package.CreateRelationship(packagePartDocument.Uri, TargetMode.Internal, PackageRelationshipType);
        }