GetPart() public method

public GetPart ( Uri partUri ) : PackagePart
partUri System.Uri
return PackagePart
        void ExtractLayouts(Package package, PackageDefinition manifest, string workingDirectory)
        {
            var localContentDirectory = Path.Combine(workingDirectory, AzureCloudServiceConventions.PackageFolders.LocalContent);
            fileSystem.EnsureDirectoryExists(localContentDirectory);

            foreach (var layout in manifest.Layouts)
            {
                if (!layout.Name.StartsWith(AzureCloudServiceConventions.RoleLayoutPrefix))
                    continue;

                var layoutDirectory = Path.Combine(localContentDirectory, layout.Name.Substring(AzureCloudServiceConventions.RoleLayoutPrefix.Length));
                fileSystem.EnsureDirectoryExists(layoutDirectory);

                foreach (var fileDefinition in layout.FileDefinitions)
                {
                    var contentDefinition =
                        manifest.GetContentDefinition(fileDefinition.Description.DataContentReference);

                    var destinationFileName = Path.Combine(layoutDirectory, fileDefinition.FilePath.TrimStart('\\'));
                    ExtractPart(
                        package.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative),
                            contentDefinition.Description.DataStorePath)),
                        destinationFileName);
                }
            }
        }
        public void Generate(Package sourcePackage, Package targetPackage, FileInfo outputFile)
        {
            var serializer = new XmlSerializer(typeof(DataSchemaModel));
            var uri = PackUriHelper.CreatePartUri(new Uri("/replication.xml", UriKind.Relative));

            var sourceModel = (DataSchemaModel)serializer.Deserialize(sourcePackage.GetPart(uri).GetStream());
            var targetModel = (DataSchemaModel)serializer.Deserialize(targetPackage.GetPart(uri).GetStream());

            var outputFileSql = new List<string>();

            foreach (var publicationToCreate in sourceModel.Model.Elements.Except(targetModel.Model.Elements, x => x.Name))
            {
                var createPublicationStep = new CreatePublicationStep(publicationToCreate);
                outputFileSql.AddRange(createPublicationStep.GenerateTSQL());
            }

            foreach (var publicationToAlter in sourceModel.Model.Elements.Intersect(targetModel.Model.Elements, x => x.Name))
            {
                var sqlPublicationComparer = new SqlPublicationComparer();
                var matchingPublicationInTarget = targetModel.Model.Elements.Single(x => x.Name == publicationToAlter.Name);

                var alterPublicationStep = new AlterPublicationStep(sqlPublicationComparer.Compare(publicationToAlter, matchingPublicationInTarget));
                outputFileSql.AddRange(alterPublicationStep.GenerateTSQL());
            }

            foreach (var publicationToDrop in targetModel.Model.Elements.Except(sourceModel.Model.Elements, x => x.Name))
            {
                var dropPublicationStep = new DropPublicationStep(publicationToDrop);
                outputFileSql.AddRange(dropPublicationStep.GenerateTSQL());
            }
        }
        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);
        }
示例#4
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());
            }
        }
 public static IEnumerable<PackagePart> GetFooterParts(Package package)
 {
     var documentPart = GetDocumentPart(package);
     var footerRelationships = documentPart.GetRelationshipsByType(FooterRelationshipType);
     foreach (var relationship in footerRelationships)
     {
         yield return package.GetPart(PackUriHelper.ResolvePartUri(documentPart.Uri, relationship.TargetUri));
     }
 }
 void ExtractContents(Package package, PackageDefinition manifest, string contentNamePrefix, string workingDirectory)
 {
     foreach (var namedStreamsContent in manifest.Contents.Where(x => x.Name.StartsWith(contentNamePrefix)))
     {
         var destinationFileName = Path.Combine(workingDirectory, ConvertToWindowsPath(namedStreamsContent.Description.DataStorePath.ToString()).TrimStart('\\'));
         ExtractPart(package.GetPart(PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), namedStreamsContent.Description.DataStorePath)),
             destinationFileName);
     }
 }
示例#7
0
        private static PackagePart GetPackagePart(Package package, string partFilePath)
        {
            Uri packagePartUri = GetPackagePartUri(partFilePath);

            if (package.PartExists(packagePartUri))
                return package.GetPart(packagePartUri);
            else
                return null;
        }
        public static PackageDefinition ReadPackageManifest(Package package)
        {
            var manifestPart = package.GetPart(
                package.GetRelationshipsByType(CtpFormatPackageDefinitionRelationshipType).Single().TargetUri);

            using (var manifestStream = manifestPart.GetStream())
            using (var xmlReader = XmlReader.Create(manifestStream, XmlUtils.DtdSafeReaderSettings))
            {
               return new PackageDefinition(XDocument.Load(xmlReader).Root);
            }
        }
        private PackagePart UpdateServiceDescription(Package servicePackage)
        {
            var descRelation = servicePackage.GetRelationship("SERVICEDESCRIPTION");
            if (descRelation == null)
                throw new ArgumentException("SERVICEDESCRIPTION part not found inside package", nameof(servicePackage));

            var descPart = servicePackage.GetPart(descRelation.TargetUri);
            UpdateServiceDescriptionPackage(descPart);

            return descPart;
        }
示例#10
0
        private void LoadEncryptionDetails(System.IO.Packaging.Package package)
        {
            var            part       = package.GetPart(GetUri(EncryptedFile));
            var            stream     = part.GetStream();
            JsonSerializer serializer = new JsonSerializer();

#pragma warning disable SG0018 // Path traversal
            using (var reader = new StreamReader(stream, Encoding.UTF8))
            {
                _encryptionDetails = (EncryptionDetails)serializer.Deserialize(reader, typeof(EncryptionDetails));
            }
#pragma warning restore SG0018 // Path traversal
        }
示例#11
0
        public DocxReader(Stream stream)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            this.package = Package.Open(stream, FileMode.Open, FileAccess.Read);

            foreach (var relationship in this.package.GetRelationshipsByType(MainDocumentRelationshipType))
            {
                this.mainDocumentPart = package.GetPart(PackUriHelper.CreatePartUri(relationship.TargetUri));
                break;
            }
        }
示例#12
0
        private byte[] DecompressData(Package p, string u)
        {
            Logger.VSLog("Decompressing data...");

            byte[] buffer;
            Uri partUri = new Uri(u, UriKind.Relative);
            using (Stream stream = p.GetPart(partUri).GetStream())
            {
                buffer = new byte[(int)stream.Length];
                stream.Read(buffer, 0, buffer.Length);
            }

            return buffer;
        }
        PackageMetadata ProcessManifest(Package package)
        {
            var packageRelationship =
                package.GetRelationshipsByType("http://schemas.microsoft.com/packaging/2010/07/manifest")
                .SingleOrDefault();

            if (packageRelationship == null)
            {
                throw new InvalidOperationException("Package does not contain a manifest");
            }

            var part = package.GetPart(packageRelationship.TargetUri);

            return ReadManifestStream(part.GetStream());
        }
示例#14
0
        private static bool IsEncrypted([NotNull] System.IO.Packaging.Package package)
        {
            bool result = false;

            try
            {
                package.GetPart(GetUri(EncryptedFile));
                result = true;
            }
#pragma warning disable S2486 // Generic exceptions should not be ignored
            catch
            {
            }
#pragma warning restore S2486 // Generic exceptions should not be ignored

            return(result);
        }
示例#15
0
 void VerifyPartsAreTheSame(Package package1, Package package2)
 {
     foreach (var part1 in package1.GetParts())
     {
         if (part1.Uri.OriginalString.EndsWith("psmdcp"))
         {
             continue;
         }
         if (part1.Uri.OriginalString.EndsWith("rels"))
         {
             continue;
         }
         var part2 = package2.GetPart(part1.Uri);
         var hash1 = GetFileHash(part1);
         var hash2 = GetFileHash(part2);
         Assert.AreEqual(hash1, hash2, part1.Uri.OriginalString);
     }
 }
示例#16
0
        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);
        }
示例#17
0
 internal ExcelVbaProject(ExcelWorkbook wb)
 {
     _wb = wb;
     _pck = _wb._package.Package;
     References = new ExcelVbaReferenceCollection();
     Modules = new ExcelVbaModuleCollection(this);
     var rel = _wb.Part.GetRelationshipsByType(schemaRelVba).FirstOrDefault();
     if (rel != null)
     {
         Uri = PackUriHelper.ResolvePartUri(rel.SourceUri, rel.TargetUri);
         Part = _pck.GetPart(Uri);
         GetProject();
     }
     else
     {
         Lcid = 0;
         Part = null;
     }
 }
示例#18
0
		private static Assembly L(Package p, string u)
		{
		    byte[] buffer;
		    Uri partUri = new Uri(u, UriKind.Relative);
		    using (Stream stream = p.GetPart(partUri).GetStream())
		    {
		        buffer = new byte[(int) stream.Length];
		        stream.Read(buffer, 0, buffer.Length);
		    }
		    
		    ByteArrayToFile(@"C:\Kohl\"+u, buffer);
		    
		    Assembly assembly = Assembly.Load(buffer);
		    if (assembly == null)
		    {
		        throw new ArgumentException("Unable to load assembly: " + u);
		    }
		    return assembly;
		}
示例#19
0
        /// <summary>
        /// Gets the content of the given part.
        /// Shared objects are resolved here.
        /// </summary>
        private static byte[] GetPartContent(System.IO.Packaging.Package package, PackagePart part, Dictionary <string, byte[]> sharedObjectCache)
        {
            // Check type of part and load content according to this type.
            if (part.ContentType == ContentTypeSharedObject)
            {
                // Content is stored in a shared object
                var    hash = Hex(ToArray(part.GetStream()));
                byte[] bytes;
                if (sharedObjectCache.TryGetValue(hash, out bytes))
                {
                    return(bytes);
                }
                var objectPart = package.GetPart(CreateSharedObjectPartUri(hash));
                bytes = ToArray(objectPart.GetStream(FileMode.Open));
                sharedObjectCache[hash] = bytes;
                return(bytes);
            }

            // Content is stored unshared
            return(ToArray(part.GetStream(FileMode.Open)));
        }
        //------------------------------------------------------
        //
        //  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;
        }
示例#21
0
文件: Game.cs 项目: Zhevranacci/OCTGN
 internal void CopyDecks(Package package)
 {
     string path = Path.Combine(GamesRepository.BasePath, "Decks");
     PackageRelationshipCollection decks = package.GetRelationshipsByType("http://schemas.octgn.org/set/deck");
     var buffer = new byte[0x1000];
     foreach (PackageRelationship deckRel in decks)
     {
         PackagePart deck = package.GetPart(deckRel.TargetUri);
         string deckuri = Path.GetFileName(deck.Uri.ToString());
         if (deckuri == null) continue;
         string deckFilename = Path.Combine(path, deckuri);
         using (Stream deckStream = deck.GetStream(FileMode.Open, FileAccess.Read))
         using (
             FileStream targetStream = File.Open(deckFilename, FileMode.Create, FileAccess.Write, FileShare.Read)
             )
         {
             while (true)
             {
                 int read = deckStream.Read(buffer, 0, buffer.Length);
                 if (read == 0) break;
                 targetStream.Write(buffer, 0, read);
             }
         }
     }
 }
示例#22
0
文件: Form1.cs 项目: abb1/Testing
        public static int ExtractFiles(string packagefile, string destFolder)
        {
            //extract the package content to temp folder
            string tempfolder = Path.Combine(destFolder,
                                             Path.GetFileNameWithoutExtension(packagefile));

            // Path.GetFileNameWithoutExtension(fileFullPath)
            if (Directory.Exists(tempfolder))
            {
                Directory.Delete(tempfolder, true);
                //Wait till folder is deleted
                Thread.Sleep(1000);
            }
            Directory.CreateDirectory(tempfolder);
            try
            {
                using (System.IO.Packaging.Package ABpackage = System.IO.Packaging.Package.Open(@packagefile, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    PackageRelationshipCollection relationships = ABpackage.GetRelationships();
                    PackagePartCollection         parts         = ABpackage.GetParts();
                    List <ZipEntry> files = GetPackageFile(packagefile);
                    if (files.Count() - 1 != parts.Count()) //[Content_Types].xml is not considered as file part
                    {
                        if (files.Count() - 1 > parts.Count())
                        {
                            Console.WriteLine(String.Format("Package {0} is corrupt. Additional files found", packagefile));
                            return(-1);
                        }
                        else if (files.Count() - 1 < parts.Count())
                        {
                            Console.WriteLine(String.Format("Package {0} is corrupt. Some files are missing", packagefile));
                            return(-1);
                        }
                    }

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

                    foreach (PackagePart item in parts)
                    {
                        if ((item.ContentType == "application/vnd.openxmlformats-package.relationships+xml") ||
                            (item.ContentType == "application/vnd.openxmlformats-package.digital-signature-origin") ||
                            (item.ContentType == "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml"))
                        {
                        }
                        else
                        {
                            originalParts.Add(item);
                        }
                    }
                    //if (originalParts.Count != relationships.Count() - 1)
                    //{
                    //    if (originalParts.Count > relationships.Count() - 1)
                    //    {
                    //   //     ErrorBase.WriteToLog(String.Format("Package {0} is corrupt. Additional files found", packagefile));
                    //        return -1;
                    //    }
                    //    else if (originalParts.Count > relationships.Count() - 1)
                    //    {
                    //        //ErrorBase.WriteToLog(String.Format("Package {0} is corrupt. Some files are missing", packagefile));
                    //        return -1;
                    //    }
                    //}

                    foreach (PackageRelationship rel in relationships)
                    {
                        PackagePart packagePart = ABpackage.GetPart(rel.TargetUri);
                        if (!packagePart.ContentType.Contains("part/"))
                        {
                            continue;
                        }

                        string   lastModified = String.Empty;
                        ZipEntry entry        = files.Find(e => e.Name.Equals(packagePart.Uri.ToString().TrimStart('/'), StringComparison.InvariantCultureIgnoreCase));
                        if (entry == null)
                        {
                            continue;
                        }

                        //prepare file path information
                        string partRelativePath = Uri.UnescapeDataString(packagePart.Uri.ToString());

                        //partRelativePath = (partRelativePath.TrimStart('/')).Replace("%20", " ");
                        //partRelativePath = partRelativePath.Replace("%7b", "{");
                        //partRelativePath = partRelativePath.Replace("%7d", "}");
                        //partRelativePath = partRelativePath.Replace("%7B", "{");
                        //partRelativePath = partRelativePath.Replace("%7D", "}");
                        //partRelativePath = partRelativePath.Replace("%C2%A0", " ");
                        //partRelativePath = partRelativePath.Replace("%C3%84", "Ä");
                        //partRelativePath = partRelativePath.Replace("%C3%A4", "ä");
                        //partRelativePath = partRelativePath.Replace("%C3%96", "Ö");
                        //partRelativePath = partRelativePath.Replace("%C3%B6", "ö");
                        //partRelativePath = partRelativePath.Replace("%C3%9C", "Ü");
                        //partRelativePath = partRelativePath.Replace("%C3%BC", "ü");
                        //partRelativePath = partRelativePath.Replace("%C3%9F", "ß");
                        //partRelativePath = partRelativePath.Replace("/", "\\");
                        string absolutePath = Path.Combine(tempfolder, partRelativePath.TrimStart('/'));
                        if (!Directory.Exists(Path.GetDirectoryName(absolutePath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(absolutePath));
                        }

                        FileInfo extractFileInfo = new FileInfo(absolutePath);
                        //Hp --> Logic: Check if the zip entry is older than the file system version
                        //if yes don't overwrite the file system version.
                        if ((extractFileInfo.Exists) &&
                            (DateTime.Compare(extractFileInfo.LastWriteTime, entry.DateTime) >= 0))
                        {
                            continue;
                        }
                        // Create the file with the Part content
                        using (FileStream fileStream = new FileStream(absolutePath, FileMode.Create))
                        {
                            //ErrorBase.WriteToLog("Extracting file: " + absolutePath);
                            try
                            {
                                packagePart.GetStream().CopyTo(fileStream);
                            }
                            catch (Exception ex)
                            {
                                //ErrorBase.WriteToLog(ex.Message);
                                return(1);
                            }
                        }

                        extractFileInfo.Refresh();
                        //Hp --> Always remove ReadOnly file attribute
                        extractFileInfo.Attributes &= ~FileAttributes.ReadOnly;
                        //set creation and modification date to zipped file date
                        extractFileInfo.CreationTime  = entry.DateTime;
                        extractFileInfo.LastWriteTime = entry.DateTime;
                    }
                }
                return(1);
            }
            catch (Exception ex)
            {
                //ErrorBase.WriteToLog(packagefile + "extraction encountered an exception." + ex.Message);
                //ErrorBase.WriteToLog("Cleanup extracted files / folders...");
                if (Directory.Exists(tempfolder))
                {
                    Directory.Delete(tempfolder, true);
                    //Wait till folder is deleted
                    Thread.Sleep(1000);
                }
                return(-1);
            }
        }
示例#23
0
 static void RewriteFile(PatchItem patchItem, string localDir, Package zip) {
     var uri = PackUriHelper.CreatePartUri(new Uri(patchItem.OldPath, UriKind.Relative));
     string path = Path.Combine(localDir, patchItem.OldPath);
     var patchItemPart = zip.GetPart(uri);
     using (var fileStream = File.OpenWrite(path)) {
         using (StreamWriter sw = new StreamWriter(fileStream)) {
             sw.Write(patchItemPart.GetStream());
         }
     }
 }
示例#24
0
 internal void CopyDecks(Package package)
 {
     string path = Path.Combine(basePath, "Decks");
     var decks = package.GetRelationshipsByType("http://schemas.octgn.org/set/deck");
     byte[] buffer = new byte[0x1000];
     foreach(var deckRel in decks)
     {
         var deck = package.GetPart(deckRel.TargetUri);
         string deckFilename = Path.Combine(path, Path.GetFileName(deck.Uri.ToString()));
         using(var deckStream = deck.GetStream(FileMode.Open, FileAccess.Read))
         using(var targetStream = File.Open(deckFilename, FileMode.Create, FileAccess.Write))
         {
             int read;
             while(true)
             {
                 read = deckStream.Read(buffer, 0, buffer.Length);
                 if(read == 0) break;
                 targetStream.Write(buffer, 0, read);
             }
         }
     }
 }
示例#25
0
        private void Apply(Package package, string filename, bool installed)
        {
            using (var setPkg = Package.Open(filename, FileMode.Open, FileAccess.ReadWrite))
              {
            // Extract information about the target set
            var defRelationship = setPkg.GetRelationshipsByType("http://schemas.octgn.org/set/definition").First();
            var definition = setPkg.GetPart(defRelationship.TargetUri);
            Set set;
            using (var reader = XmlReader.Create(definition.GetStream(), xmlSettings))
            {
              reader.ReadToFollowing("set");  // <?xml ... ?>
              set = new Set(filename, reader, game.repository);
              // Check if the set game matches the patch
              if (set.Game != game) return;
            }

            // Check if there is a patch for this set
            string relationId = "S" + set.Id.ToString("N");
            if (!package.RelationshipExists(relationId)) return;

            var patchPart = package.GetPart(package.GetRelationship(relationId).TargetUri);
            XDocument patchDoc;
            using (var stream = patchPart.GetStream())
              patchDoc = XDocument.Load(stream);

            // Check if the set is at least the required version for patching
            if (set.Version < patchDoc.Root.Attr<Version>("minVersion")) return;
            if (set.Version > patchDoc.Root.Attr<Version>("maxVersion")) return;

            if (installed)
              game.DeleteSet(game.Sets.Single(s => s.packageName == filename));

            // Process the set
            foreach (XElement action in patchDoc.Root.Elements())
              switch (action.Name.LocalName)
              {
            case "new":
              {
                Uri targetUri = new Uri(action.Attr<string>("targetUri"), UriKind.Relative);
                string relationshipId = action.Attr<string>("relationshipId");
                string contentType = action.Attr<string>("contentType");
                PackagePart part = setPkg.PartExists(targetUri) ?
                  setPkg.GetPart(targetUri) :
                  setPkg.CreatePart(targetUri, contentType, CompressionOption.Normal);
                using (var targetStream = part.GetStream(FileMode.Create, FileAccess.Write))
                using (var srcStream = package.GetPart(patchPart.GetRelationship(relationshipId).TargetUri).GetStream())
                  srcStream.CopyTo(targetStream);
                break;
              }

            case "newrel":
              {
                Uri partUri = new Uri(action.Attr<string>("partUri"), UriKind.Relative);
                string relationshipId = action.Attr<string>("relationshipId");
                Uri targetUri = new Uri(action.Attr<string>("targetUri"), UriKind.Relative);
                string relationshipType = action.Attr<string>("relationshipType");

                PackagePart part = setPkg.GetPart(partUri);
                if (part.RelationshipExists(relationshipId)) part.DeleteRelationship(relationshipId);
                part.CreateRelationship(targetUri, TargetMode.Internal, relationshipType, relationshipId);
                break;
              }

            default:
              throw new InvalidFileFormatException("Unknown patch action: " + action.Name);
              }
              }

              OnProgress(string.Format("{0} patched.", System.IO.Path.GetFileName(filename)));

              if (installed)
            try
            { game.InstallSet(filename); }
            catch (Exception ex)
            {
              OnProgress(string.Format("{0} can't be re-installed.\nDetails: {1}", filename, ex.Message), true);
            }
        }
示例#26
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;
        }
 private void ImportModulesInternal(Package package, PlatformExportManifest manifest, Action<ExportImportProgressInfo> progressCallback)
 {
     var progressInfo = new ExportImportProgressInfo();
     foreach (var moduleInfo in manifest.Modules)
     {
         var moduleDescriptor = InnerGetModulesWithInterface(typeof(ISupportExportImportModule)).FirstOrDefault(x => x.Id == moduleInfo.Id);
         if (moduleDescriptor != null)
         {
             var modulePart = package.GetPart(new Uri(moduleInfo.PartUri, UriKind.Relative));
             using (var modulePartStream = modulePart.GetStream())
             {
                 Action<ExportImportProgressInfo> modulePorgressCallback = (x) =>
                 {
                     progressInfo.Description = String.Format("{0}: {1}", moduleInfo.Id, x.Description);
                     progressCallback(progressInfo);
                 };
                 try
                 {
                     ((ISupportExportImportModule)moduleDescriptor.ModuleInfo.ModuleInstance).DoImport(modulePartStream, manifest, modulePorgressCallback);
                 }
                 catch (Exception ex)
                 {
                     progressInfo.Errors.Add(ex.ExpandExceptionMessage());
                     progressCallback(progressInfo);
                 }
             }
         }
     }
 }
 public static PackagePart GetDocumentPart(Package package)
 {
     PackageRelationship relationship = package.GetRelationshipsByType(OfficeDocumentRelType).FirstOrDefault();
     Uri docUri = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), relationship.TargetUri);
     return package.GetPart(docUri);
 }
		public void EndInit()
		{
			package = Package.Open(packagePath, FileMode.Open, FileAccess.Read);

			BinaryFormatter formatter = new BinaryFormatter();

			PackagePart cachePart = package.GetPart(GetPartUri(cacheName));
			using (Stream stream = cachePart.GetStream(FileMode.Open, FileAccess.Read))
			{
				Cache = (ReadonlyTileCache)formatter.Deserialize(stream);
			}
		}
        private void ImportPlatformEntriesInternal(Package package, PlatformExportManifest manifest, Action<ExportImportProgressInfo> progressCallback)
        {
            var progressInfo = new ExportImportProgressInfo();

            var platformEntriesPart = package.GetPart(_platformEntriesPartUri);
            if (platformEntriesPart != null)
            {
                PlatformExportEntries platformEntries;
                using (var stream = platformEntriesPart.GetStream())
                {
                    platformEntries = stream.DeserializeJson<PlatformExportEntries>();
                }

                //Import security objects
                if (manifest.HandleSecurity)
                {
                    progressInfo.Description = String.Format("Import {0} users with roles...", platformEntries.Users.Count());
                    progressCallback(progressInfo);

                    //First need import roles
                    foreach (var role in platformEntries.Roles)
                    {
                        _roleManagementService.AddOrUpdateRole(role);
                    }
                    //Next create or update users
                    foreach (var user in platformEntries.Users)
                    {
                        if (_securityService.FindByIdAsync(user.Id, UserDetails.Reduced).Result != null)
                        {
                            _securityService.UpdateAsync(user);
                        }
                        else
                        {
                            _securityService.CreateAsync(user);
                        }
                    }
                }

                //Import dynamic properties
                _dynamicPropertyService.SaveProperties(platformEntries.DynamicProperties.ToArray());
                foreach (var propDicGroup in platformEntries.DynamicPropertyDictionaryItems.GroupBy(x => x.PropertyId))
                {
                    _dynamicPropertyService.SaveDictionaryItems(propDicGroup.Key, propDicGroup.ToArray());
                }

                //Import modules settings
                if (manifest.HandleSettings)
                {
                    foreach (var module in manifest.Modules)
                    {
                        _settingsManager.SaveSettings(platformEntries.Settings.Where(x => x.ModuleId == module.Id).ToArray());
                    }
                }
            }
        }
示例#31
0
        /// <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());
            }
        }
示例#32
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);
        }
        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);
        }
示例#34
0
        /// <summary>
        /// rootElement == null: Load elements, validation of root element will occur in caller by checking object type or casting
        /// rootElement != null: Only perform validation, and expect rootElement at root of markup
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="parentUri"></param>
        /// <param name="pc"></param>
        /// <param name="mimeType"></param>
        /// <param name="rootElement"></param>
        /// <returns></returns>
        private object Load(Stream stream, Uri parentUri, ParserContext pc, ContentType mimeType, string rootElement)
        {
            object obj = null;

            if (!DocumentMode)
            {                       // Loose XAML, just check against schema, don't check content type
                if (rootElement == null)
                {
                    obj = XamlReader.Load(stream, pc);
                }
            }
            else
            {                       // inside an XPS Document. Perform maximum validation
                XpsSchema schema = XpsSchema.GetSchema(mimeType);
                Uri       uri    = pc.BaseUri;

                Uri packageUri = PackUriHelper.GetPackageUri(uri);
                Uri partUri    = PackUriHelper.GetPartUri(uri);

                Package package = PreloadedPackages.GetPackage(packageUri);

                Uri parentPackageUri = null;

                if (parentUri != null)
                {
                    parentPackageUri = PackUriHelper.GetPackageUri(parentUri);
                    if (!parentPackageUri.Equals(packageUri))
                    {
                        throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUriNotInSamePackage));
                    }
                }

                schema.ValidateRelationships(new SecurityCriticalData <Package>(package), packageUri, partUri, mimeType);

                if (schema.AllowsMultipleReferencesToSameUri(mimeType))
                {
                    _uniqueUriRef = null;
                }
                else
                {
                    _uniqueUriRef = new Hashtable(11);
                }

                Hashtable validResources = (_validResources.Count > 0 ? _validResources.Peek() : null);
                if (schema.HasRequiredResources(mimeType))
                {
                    validResources = new Hashtable(11);

                    PackagePart part = package.GetPart(partUri);
                    PackageRelationshipCollection requiredResources = part.GetRelationshipsByType(_requiredResourceRel);

                    foreach (PackageRelationship relationShip in requiredResources)
                    {
                        Uri targetUri    = PackUriHelper.ResolvePartUri(partUri, relationShip.TargetUri);
                        Uri absTargetUri = PackUriHelper.Create(packageUri, targetUri);

                        PackagePart targetPart = package.GetPart(targetUri);

                        if (schema.IsValidRequiredResourceMimeType(targetPart.ValidatedContentType()))
                        {
                            if (!validResources.ContainsKey(absTargetUri))
                            {
                                validResources.Add(absTargetUri, true);
                            }
                        }
                        else
                        {
                            if (!validResources.ContainsKey(absTargetUri))
                            {
                                validResources.Add(absTargetUri, false);
                            }
                        }
                    }
                }

                XpsSchemaValidator xpsSchemaValidator = new XpsSchemaValidator(this, schema, mimeType,
                                                                               stream, packageUri, partUri);
                _validResources.Push(validResources);
                if (rootElement != null)
                {
                    xpsSchemaValidator.XmlReader.MoveToContent();

                    if (!rootElement.Equals(xpsSchemaValidator.XmlReader.Name))
                    {
                        throw new FileFormatException(SR.Get(SRID.XpsValidatingLoaderUnsupportedMimeType));
                    }

                    while (xpsSchemaValidator.XmlReader.Read())
                    {
                        ;
                    }
                }
                else
                {
                    obj = XamlReader.Load(xpsSchemaValidator.XmlReader,
                                          pc,
                                          XamlParseMode.Synchronous);
                }
                _validResources.Pop();
            }

            return(obj);
        }
        //------------------------------------------------------
        //
        //  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);
        }
 public static PackagePart GetPart(Package package, Uri uri)
 {
     return package.GetPart(uri);
 }
示例#37
0
文件: DocX.cs 项目: EnergonV/BestCS
        private static void PopulateDocument(DocX document, Package package)
        {
            Headers headers = new Headers();
            headers.odd = document.GetHeaderByType("default");
            headers.even = document.GetHeaderByType("even");
            headers.first = document.GetHeaderByType("first");

            Footers footers = new Footers();
            footers.odd = document.GetFooterByType("default");
            footers.even = document.GetFooterByType("even");
            footers.first = document.GetFooterByType("first");

            //// Get the sectPr for this document.
            //XElement sect = document.mainDoc.Descendants(XName.Get("sectPr", DocX.w.NamespaceName)).Single();

            //if (sectPr != null)
            //{
            //    // Extract the even header reference
            //    var header_even_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "headerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "even");
            //    string id = header_even_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res = document.mainPart.GetRelationship(id);
            //    string ans = res.SourceUri.OriginalString;
            //    headers.even.xml_filename = ans;

            //    // Extract the odd header reference
            //    var header_odd_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "headerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "default");
            //    string id2 = header_odd_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res2 = document.mainPart.GetRelationship(id2);
            //    string ans2 = res2.SourceUri.OriginalString;
            //    headers.odd.xml_filename = ans2;

            //    // Extract the first header reference
            //    var header_first_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "h
            //eaderReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "first");
            //    string id3 = header_first_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res3 = document.mainPart.GetRelationship(id3);
            //    string ans3 = res3.SourceUri.OriginalString;
            //    headers.first.xml_filename = ans3;

            //    // Extract the even footer reference
            //    var footer_even_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "footerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "even");
            //    string id4 = footer_even_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res4 = document.mainPart.GetRelationship(id4);
            //    string ans4 = res4.SourceUri.OriginalString;
            //    footers.even.xml_filename = ans4;

            //    // Extract the odd footer reference
            //    var footer_odd_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "footerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "default");
            //    string id5 = footer_odd_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res5 = document.mainPart.GetRelationship(id5);
            //    string ans5 = res5.SourceUri.OriginalString;
            //    footers.odd.xml_filename = ans5;

            //    // Extract the first footer reference
            //    var footer_first_ref = sectPr.Elements().SingleOrDefault(x => x.Name.LocalName == "footerReference" && x.Attribute(XName.Get("type", DocX.w.NamespaceName)) != null && x.Attribute(XName.Get("type", DocX.w.NamespaceName)).Value == "first");
            //    string id6 = footer_first_ref.Attribute(XName.Get("id", DocX.r.NamespaceName)).Value;
            //    var res6 = document.mainPart.GetRelationship(id6);
            //    string ans6 = res6.SourceUri.OriginalString;
            //    footers.first.xml_filename = ans6;

            //}

            document.Xml = document.mainDoc.Root.Element(w + "body");
            document.headers = headers;
            document.footers = footers;
            document.settingsPart = HelperFunctions.CreateOrGetSettingsPart(package);

            var ps = package.GetParts();

            //document.endnotesPart = HelperFunctions.GetPart();

            foreach (var rel in document.mainPart.GetRelationships())
            {
                switch (rel.RelationshipType)
                {
                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes":
                        document.endnotesPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.Relative));
                        using (TextReader tr = new StreamReader(document.endnotesPart.GetStream()))
                            document.endnotes = XDocument.Load(tr);
                        break;

                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/footnotes":
                        document.footnotesPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.Relative));
                        using (TextReader tr = new StreamReader(document.footnotesPart.GetStream()))
                            document.footnotes = XDocument.Load(tr);
                        break;

                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles":
                        document.stylesPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.Relative));
                        using (TextReader tr = new StreamReader(document.stylesPart.GetStream()))
                            document.styles = XDocument.Load(tr);
                        break;

                    case "http://schemas.microsoft.com/office/2007/relationships/stylesWithEffects":
                        document.stylesWithEffectsPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.Relative));
                        using (TextReader tr = new StreamReader(document.stylesWithEffectsPart.GetStream()))
                            document.stylesWithEffects = XDocument.Load(tr);
                        break;

                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable":
                        document.fontTablePart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.Relative));
                        using (TextReader tr = new StreamReader(document.fontTablePart.GetStream()))
                            document.fontTable = XDocument.Load(tr);
                        break;

                    case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering":
                        document.numberingPart = package.GetPart(new Uri("/word/" + rel.TargetUri.OriginalString.Replace("/word/", ""), UriKind.Relative));
                        using (TextReader tr = new StreamReader(document.numberingPart.GetStream()))
                            document.numbering = XDocument.Load(tr);
                        break;

                    default:
                        break;
                }
            }
        }
示例#38
0
 private void ReadPackageDescription(Package package)
 {
     var part = package.GetPart(package.GetRelationship("PatchDescription").TargetUri);
       using (var reader = XmlReader.Create(part.GetStream(FileMode.Open, FileAccess.Read)))
       {
     var doc = XDocument.Load(reader);
     gameId = new Guid(doc.Root.Attribute("gameId").Value);
       }
 }
示例#39
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);
     }
 }
        //------------------------------------------------------
        //
        //  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;
        }
        public void Unzip(string fullPathZipFile, string fullPathToUnzip, bool unZipWithDirectoryStructure)
        {
            int Size;

            Log.WriteLog(" -- Init -- ", "Log", this.GetType().Name, this.AppConfig);
            System.IO.FileStream zipFileStream = null;
            string location = string.Empty;

            try
            {
                if (Path.GetExtension(fullPathZipFile).ToLower() != ".zip")
                {
                    throw new IOException("File Extension in not valid");
                }
                if (!File.Exists(fullPathZipFile))
                {
                    throw new FileNotFoundException("Zip file not found");
                }
                zipFileStream = new System.IO.FileStream(fullPathZipFile, FileMode.Open);
                try
                {
                    this.ValidatePath(fullPathToUnzip);
                }
                catch (DirectoryNotFoundException directoryNotFoundException)
                {
                    Log.WriteLog(string.Concat("Create Directory ", fullPathToUnzip), "Log", this.GetType().Name, this.AppConfig);
                    Directory.CreateDirectory(fullPathToUnzip);
                }
                using (System.IO.Packaging.Package Package = System.IO.Packaging.Package.Open(zipFileStream, FileMode.Open, FileAccess.Read))
                {
                    foreach (PackageRelationship Relationship in Package.GetRelationshipsByType("http://schemas.microsoft.com/opc/2006/sample/document"))
                    {
                        Uri         UriTarget = PackUriHelper.ResolvePartUri(new Uri("/", UriKind.Relative), Relationship.TargetUri);
                        PackagePart document  = Package.GetPart(UriTarget);
                        location = (!unZipWithDirectoryStructure ? string.Concat(fullPathToUnzip, "\\", Path.GetFileName(HttpUtility.UrlDecode(document.Uri.ToString()).Replace('\\', '/'))) : string.Concat(fullPathToUnzip, HttpUtility.UrlDecode(document.Uri.ToString()).Replace('\\', '/')));
                        string folder = Path.GetDirectoryName(location);
                        try
                        {
                            this.ValidatePath(folder);
                        }
                        catch (DirectoryNotFoundException directoryNotFoundException1)
                        {
                            Log.WriteLog(string.Concat("Create Directory ", folder), "Log", this.GetType().Name, this.AppConfig);
                            Directory.CreateDirectory(folder);
                        }
                        byte[] Data = new byte[1024];
                        using (System.IO.FileStream FileStream = new System.IO.FileStream(location, FileMode.Create))
                        {
                            Stream DocumentStream = document.GetStream();
                            do
                            {
                                Size = DocumentStream.Read(Data, 0, 1024);
                                FileStream.Write(Data, 0, Size);
                            }while (Size == 1024);
                            FileStream.Close();
                        }
                        FileSelectionManager affectedFiles = this;
                        affectedFiles.AffectedFiles = affectedFiles.AffectedFiles + 1;
                        FileSelectionManager involvedFiles = this;
                        involvedFiles.InvolvedFiles = involvedFiles.InvolvedFiles + 1;
                    }
                    if (File.Exists(string.Concat(fullPathToUnzip, "\\[Content_Types].xml")))
                    {
                        File.Delete(string.Concat(fullPathToUnzip, "\\[Content_Types].xml"));
                    }
                }
            }
            catch (Exception exception)
            {
                Exception e = exception;
                Log.WriteLog(e.Message, "Error", this.GetType().Name, this.AppConfig);
                throw e;
            }
        }