PartExists() public méthode

public PartExists ( Uri partUri ) : bool
partUri System.Uri
Résultat bool
Exemple #1
0
        /// <summary>
        /// CertificatePart constructor
        /// </summary>
        internal CertificatePart(System.IO.Packaging.Package container, Uri partName)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            if (partName == null)
            {
                throw new ArgumentNullException("partName");
            }

            partName = PackUriHelper.ValidatePartUri(partName);

            // create if not found
            if (container.PartExists(partName))
            {
                // open the part
                _part = container.GetPart(partName);

                // ensure the part is of the expected type
                if (_part.ValidatedContentType().AreTypeAndSubTypeEqual(_certificatePartContentType) == false)
                {
                    throw new FileFormatException(SR.CertificatePartContentTypeMismatch);
                }
            }
            else
            {
                // create the part
                _part = container.CreatePart(partName, _certificatePartContentType.ToString());
            }
        }
        private static PackagePart GetPackagePart(Package package, string partFilePath)
        {
            Uri packagePartUri = GetPackagePartUri(partFilePath);

            if (package.PartExists(packagePartUri))
                return package.GetPart(packagePartUri);
            else
                return null;
        }
        /// <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);
                        }
                    }
                }
            }
        }
        void WriteRelationships()
        {
            bool exists = Package.PartExists(RelationshipsPartUri);

            if (exists && Relationships.Count == 0)
            {
                Package.DeletePart(RelationshipsPartUri);
                return;
            }

            if (!exists)
            {
                PackagePart part = Package.CreatePart(RelationshipsPartUri, Package.RelationshipContentType);
                part.IsRelationship = true;
            }
            using (Stream s = Package.GetPart(RelationshipsPartUri).GetStream())
                Package.WriteRelationships(Relationships, s);
        }
        //------------------------------------------------------
        //
        //  Private Methods
        //
        //------------------------------------------------------
        #region Private Methods
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="package">package</param>
        /// <param name="part">part will be null if package is the source of the relationships</param>
        /// <remarks>Shared constructor</remarks>
        private InternalRelationshipCollection(Package package, PackagePart part)
        {
            Debug.Assert(package != null, "package parameter passed should never be null");

            _package    = package;
            _sourcePart = part;

            //_sourcePart may be null representing that the relationships are at the package level
            _uri           = GetRelationshipPartUri(_sourcePart);
            _relationships = new List <PackageRelationship>(4);

            // Load if available (not applicable to write-only mode).
            if ((package.FileOpenAccess == FileAccess.Read ||
                 package.FileOpenAccess == FileAccess.ReadWrite) && package.PartExists(_uri))
            {
                _relationshipPart = package.GetPart(_uri);
                ThrowIfIncorrectContentType(_relationshipPart.ValidatedContentType);
                ParseRelationshipPart(_relationshipPart);
            }

            //Any initialization in the constructor should not set the dirty flag to true.
            _dirty = false;
        }
 public static void AddFileToPackage(Package package, string uri, string filePath, string contentType)
 {
     FileInfo info = new FileInfo(filePath);
     uri = MakeUriSafe(uri);
     if (!info.Exists)
     {
         throw new FileNotFoundException(Strings.Package_FileCouldNotBeAdded, filePath);
     }
     Uri partUri = new Uri(uri, UriKind.Relative);
     string extension = info.Extension;
     if (package.PartExists(partUri))
     {
         package.DeletePart(partUri);
     }
     PackagePart part = package.CreatePart(partUri, contentType, CompressionOption.Maximum);
     using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
     {
         using (Stream stream2 = part.GetStream())
         {
             CopyStream(stream, stream2);
         }
         stream.Close();
     }
 }
Exemple #7
0
        internal static PackagePart CreateOrGetSettingsPart(Package package)
        {
            PackagePart settingsPart;

            Uri settingsUri = new Uri("/word/settings.xml", UriKind.Relative);
            if (!package.PartExists(settingsUri))
            {
                settingsPart = package.CreatePart(settingsUri, "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml", CompressionOption.Maximum);

                PackagePart mainDocumentPart = package.GetParts().Single(p => p.ContentType.Equals(DOCUMENT_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase) ||
                                                                              p.ContentType.Equals(TEMPLATE_DOCUMENTTYPE, StringComparison.CurrentCultureIgnoreCase));

                mainDocumentPart.CreateRelationship(settingsUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings");

                XDocument settings = XDocument.Parse
                (@"<?xml version='1.0' encoding='utf-8' standalone='yes'?>
                <w:settings 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:w10='urn:schemas-microsoft-com:office:word' xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' xmlns:sl='http://schemas.openxmlformats.org/schemaLibrary/2006/main'>
                  <w:zoom w:percent='100' />
                  <w:defaultTabStop w:val='720' />
                  <w:characterSpacingControl w:val='doNotCompress' />
                  <w:compat />
                  <w:rsids>
                    <w:rsidRoot w:val='00217F62' />
                    <w:rsid w:val='001915A3' />
                    <w:rsid w:val='00217F62' />
                    <w:rsid w:val='00A906D8' />
                    <w:rsid w:val='00AB5A74' />
                    <w:rsid w:val='00F071AE' />
                  </w:rsids>
                  <m:mathPr>
                    <m:mathFont m:val='Cambria Math' />
                    <m:brkBin m:val='before' />
                    <m:brkBinSub m:val='--' />
                    <m:smallFrac m:val='off' />
                    <m:dispDef />
                    <m:lMargin m:val='0' />
                    <m:rMargin m:val='0' />
                    <m:defJc m:val='centerGroup' />
                    <m:wrapIndent m:val='1440' />
                    <m:intLim m:val='subSup' />
                    <m:naryLim m:val='undOvr' />
                  </m:mathPr>
                  <w:themeFontLang w:val='en-IE' w:bidi='ar-SA' />
                  <w:clrSchemeMapping w:bg1='light1' w:t1='dark1' w:bg2='light2' w:t2='dark2' w:accent1='accent1' w:accent2='accent2' w:accent3='accent3' w:accent4='accent4' w:accent5='accent5' w:accent6='accent6' w:hyperlink='hyperlink' w:followedHyperlink='followedHyperlink' />
                  <w:shapeDefaults>
                    <o:shapedefaults v:ext='edit' spidmax='2050' />
                    <o:shapelayout v:ext='edit'>
                      <o:idmap v:ext='edit' data='1' />
                    </o:shapelayout>
                  </w:shapeDefaults>
                  <w:decimalSymbol w:val='.' />
                  <w:listSeparator w:val=',' />
                </w:settings>"
                );

                XElement themeFontLang = settings.Root.Element(XName.Get("themeFontLang", DocX.w.NamespaceName));
                themeFontLang.SetAttributeValue(XName.Get("val", DocX.w.NamespaceName), CultureInfo.CurrentCulture);

                // Save the settings document.
                using (TextWriter tw = new StreamWriter(settingsPart.GetStream()))
                    settings.Save(tw);
            }
            else
                settingsPart = package.GetPart(settingsUri);
            return settingsPart;
        }
Exemple #8
0
        public Card FromXmlReader(XmlReader reader, Game game, Set set, PackagePart definition, Package package)
        {
            var ret = new Card();
            var Properties = new SortedList<PropertyDef, object>(game.CustomProperties.Count());
            reader.MoveToAttribute("name");
            ret.Name = reader.Value;
            reader.MoveToAttribute("id");
            ret.Id = new Guid(reader.Value);
            //           isMutable = false;
            if (reader.MoveToAttribute("alternate"))
            {
                try { ret.Alternate = new Guid(reader.Value); }
                catch (Exception e)
                {
                    throw new ArgumentException(String.Format("The value {0} is not of expected type for property Alternate. Alternate must be a GUID.",
                                                reader.Value));
                }
            }
            else { ret.Alternate = System.Guid.Empty; }
            if (reader.MoveToAttribute("dependent"))
            {
                try
                {
                    ret.Dependent = new Guid(reader.Value).ToString();
                }
                catch
                {
                    try
                    {
                        ret.Dependent = Boolean.Parse(reader.Value).ToString();
                    }
                    catch
                    {

                        throw new ArgumentException(String.Format("The value {0} is not of expected type for property Dependent. Dependent must be either true/false, or the Guid of the card to use instead.",
                                                      reader.Value));
                    }
                }
            }
            else { ret.Dependent = String.Empty; }
            Uri cardImageUri = definition.GetRelationship("C" + ret.Id.ToString("N")).TargetUri;
            ret.ImageUri = cardImageUri.OriginalString;
            if (!package.PartExists(cardImageUri))
                throw new Exception(string.Format("Image for card '{0}', with URI '{1}' was not found in the package.",
                                                  ret.Name, ret.ImageUri));
            reader.Read(); // <card>

            while (reader.IsStartElement("property"))
            {
                reader.MoveToAttribute("name");
                PropertyDef prop = game.CustomProperties.FirstOrDefault(p => p.Name == reader.Value);
                if (prop == null)
                    throw new ArgumentException(string.Format("The property '{0}' is unknown", reader.Value));
                reader.MoveToAttribute("value");
                try
                {
                    switch (prop.Type)
                    {
                        case PropertyType.String:
                            Properties.Add(prop, reader.Value);
                            break;
                        case PropertyType.Integer:
                            Properties.Add(prop, Int32.Parse(reader.Value));
                            break;
                        case PropertyType.Char:
                            Properties.Add(prop, Char.Parse(reader.Value));
                            break;
                        default:
                            throw new NotImplementedException();
                    }
                }
                catch (FormatException)
                {
                    throw new ArgumentException(String.Format("The value {0} is not of expected type for property {1}",
                                                                reader.Value, prop.Name));
                }
                reader.Read(); // <property/>
            }
            ret.Properties = Properties;

            reader.Read(); // </card>
            return ret;
        }
 public static void RemoveFileFromPackage(Package package, string uri)
 {
     Uri partUri = new Uri(uri, UriKind.Relative);
     if (package.PartExists(partUri))
     {
         package.DeletePart(partUri);
     }
 }
Exemple #10
0
 public static void RenamePath(Package package, string oldUri, string newUri)
 {
     Uri partUri = new Uri(oldUri, UriKind.Relative);
     Uri uri2 = new Uri(newUri, UriKind.Relative);
     if (package.PartExists(partUri))
     {
         PackagePart part = package.GetPart(partUri);
         PackagePart part2 = package.CreatePart(uri2, part.ContentType, part.CompressionOption);
         using (Stream stream = part.GetStream())
         {
             using (Stream stream2 = part2.GetStream())
             {
                 CopyStream(stream, stream2);
             }
         }
         package.DeletePart(partUri);
     }
 }
Exemple #11
0
 internal Uri GetNewUri(Package package, string sUri)
 {
     int id = 1;
     Uri uri;
     do
     {
         uri = new Uri(string.Format(sUri, id++), UriKind.Relative);
     }
     while (package.PartExists(uri));
     return uri;
 }
        //------------------------------------------------------
        //
        //  Public Methods
        //
        //------------------------------------------------------

        #region Public Methods

        /// <summary>
        /// This method returns the list of selected PackageRelationships as per the
        /// given criteria, from a part in the Package provided
        /// </summary>
        /// <param name="package">Package object from which we get the relationsips</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">If package parameter is null</exception>
        public List <PackageRelationship> Select(Package package)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }

            List <PackageRelationship> relationships = new List <PackageRelationship>(0);

            switch (SelectorType)
            {
            case PackageRelationshipSelectorType.Id:
                if (SourceUri.Equals(PackUriHelper.PackageRootUri))
                {
                    if (package.RelationshipExists(SelectionCriteria))
                    {
                        relationships.Add(package.GetRelationship(SelectionCriteria));
                    }
                }
                else
                {
                    if (package.PartExists(SourceUri))
                    {
                        PackagePart part = package.GetPart(SourceUri);
                        if (part.RelationshipExists(SelectionCriteria))
                        {
                            relationships.Add(part.GetRelationship(SelectionCriteria));
                        }
                    }
                }
                break;

            case PackageRelationshipSelectorType.Type:
                if (SourceUri.Equals(PackUriHelper.PackageRootUri))
                {
                    foreach (PackageRelationship r in package.GetRelationshipsByType(SelectionCriteria))
                    {
                        relationships.Add(r);
                    }
                }
                else
                {
                    if (package.PartExists(SourceUri))
                    {
                        foreach (PackageRelationship r in package.GetPart(SourceUri).GetRelationshipsByType(SelectionCriteria))
                        {
                            relationships.Add(r);
                        }
                    }
                }
                break;

            default:
                //Debug.Assert is fine here since the parameters have already been validated. And all the properties are
                //readonly
                Debug.Assert(false, "This option should never be called");
                break;
            }

            return(relationships);
        }
Exemple #13
0
        //------------------------------------------------------
        //
        //  Public Methods
        //
        //------------------------------------------------------

        #region WebResponse Overloads
        /// <summary>
        /// Retrieves a stream for reading bytes from the requested resource
        /// </summary>
        /// <returns>stream</returns>
        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.GetSeekableStream(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);
        }
        /// <summary>
        /// CertificatePart constructor
        /// </summary>
        internal CertificatePart(Package container, Uri partName)
        {
            if (container == null)
                throw new ArgumentNullException("container");
            
            if (partName == null)
                throw new ArgumentNullException("partName");

            partName = PackUriHelper.ValidatePartUri(partName);
            
            // create if not found
            if (container.PartExists(partName))
            {
                // open the part
                _part = container.GetPart(partName);

                // ensure the part is of the expected type
                if (_part.ValidatedContentType.AreTypeAndSubTypeEqual(_certificatePartContentType) == false)
                    throw new FileFormatException(SR.Get(SRID.CertificatePartContentTypeMismatch));
            }
            else
            {
                // create the part
                _part = container.CreatePart(partName, _certificatePartContentType.ToString());
            }
        }
Exemple #15
0
        private bool AddToArchive(Package zip, string fileToAdd,Backup bck)
        {
            // Replace spaces with an underscore (_)
            string uriFileName = fileToAdd.Replace(" ", "_");

            // A Uri always starts with a forward slash "/"
            string zipUri = string.Concat("/", Path.GetFileName(uriFileName));

            Uri partUri = new Uri(zipUri, UriKind.Relative);
            string contentType = MediaTypeNames.Application.Zip;

            if (!zip.PartExists(partUri))
            {
                zip.DeletePart(partUri);
            }
            if (!zip.PartExists(partUri))
            {
                PackagePart pkgPart = zip.CreatePart(partUri, contentType, ConvertCompIntoCompressOption(bck.compressLevel));

                // Read all of the bytes from the file to add to the zip file
                Byte[] bites = null;

                if (bck.isVss)
                {
                    MessageBox.Show(sShadowPath + fileToAdd);
                    //bites = wApi.GetFileData(sShadowPath + Path.GetFileName(fileToAdd));
                }
                else
                {
                    try
                    {
                        bites = File.ReadAllBytes(fileToAdd);
                    }
                    catch (Exception e)
                    {
                        bites = null;
                    }
                }

                //Compress and write the bytes to the zip file

                if (bites != null)
                {

                    pkgPart.GetStream().Write(bites, 0, bites.Length);
                    return true;
                }
                else
                    return false;

            }
            else
                return false;
        }
        //------------------------------------------------------
        //
        //  Public Methods
        //
        //------------------------------------------------------

        #region Public Methods

        /// <summary>
        /// This method returns the list of selected PackageRelationships as per the
        /// given criteria, from a part in the Package provided
        /// </summary>
        /// <param name="package">Package object from which we get the relationsips</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">If package parameter is null</exception>
        public List<PackageRelationship> Select(Package package)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }

            List<PackageRelationship> relationships = new List<PackageRelationship>(0);

            switch (SelectorType)
            {
                case PackageRelationshipSelectorType.Id:
                    if (SourceUri.Equals(PackUriHelper.PackageRootUri))
                    {
                        if (package.RelationshipExists(SelectionCriteria))
                            relationships.Add(package.GetRelationship(SelectionCriteria));
                    }
                    else
                    {
                        if (package.PartExists(SourceUri))
                        {
                            PackagePart part = package.GetPart(SourceUri);
                            if (part.RelationshipExists(SelectionCriteria))
                                relationships.Add(part.GetRelationship(SelectionCriteria));
                        }
                    }
                    break;

                case PackageRelationshipSelectorType.Type:
                    if (SourceUri.Equals(PackUriHelper.PackageRootUri))
                    {
                        foreach (PackageRelationship r in package.GetRelationshipsByType(SelectionCriteria))
                            relationships.Add(r);
                    }
                    else
                    {
                        if (package.PartExists(SourceUri))
                        {
                            foreach (PackageRelationship r in package.GetPart(SourceUri).GetRelationshipsByType(SelectionCriteria))
                                relationships.Add(r);
                        }
                    }
                    break;

                default:
                    //Debug.Assert is fine here since the parameters have already been validated. And all the properties are 
                    //readonly
                    Debug.Assert(false, "This option should never be called");
                    break;
            }

            return relationships;
        }
Exemple #17
0
 static void AddPart(Package zip, string root, string path) {
     Uri uri = PackUriHelper.CreatePartUri(new Uri(path, UriKind.Relative));
     if (zip.PartExists(uri)) {
         zip.DeletePart(uri);
     }
     PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
     using (FileStream fileStream = new FileStream(Path.Combine(root, path), FileMode.Open, FileAccess.Read)) {
         using (Stream dest = part.GetStream()) {
             CopyStream(fileStream, dest);
         }
     }
 }
Exemple #18
0
 private static void AddToArchive(Package zip, string fileToAdd, string root)
 {
     try
     {
         string uriFileName = fileToAdd.Replace(" ", "_");
         FileAttributes attr = System.IO.File.GetAttributes(fileToAdd);
         if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
         {
             root = root + "/" + Path.GetFileName(uriFileName);
             string[] subfolders = Directory.GetDirectories(fileToAdd);
             for (int i = 0; i < subfolders.Length; i++)
             {
                 AddToArchive(zip, subfolders[i], root);
             }
             string[] subfiles = Directory.GetFiles(fileToAdd);
             for (int i = 0; i < subfiles.Length; i++)
             {
                 AddToArchive(zip, subfiles[i], root);
             }
         }
         else
         {
             string zipUri = string.Concat(root + "/", Path.GetFileName(uriFileName));
             Uri partUri = new Uri(zipUri, UriKind.Relative);
             string contentType = System.Net.Mime.MediaTypeNames.Application.Zip;
             if (zip.PartExists(partUri)) zip.DeletePart(partUri);
             PackagePart pkgPart = zip.CreatePart(partUri, contentType, CompressionOption.Normal);
             Byte[] bytes = System.IO.File.ReadAllBytes(fileToAdd);
             pkgPart.GetStream().Write(bytes, 0, bytes.Length);
         }
     }
     catch (Exception ex)
     {
         TextWindow.WriteLine(fileToAdd);
         Utilities.OnError(Utilities.GetCurrentMethod(), ex);
     }
 }
Exemple #19
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();
            }
        }