public bool SignPackage(string packagePath, string outputPath, string keyPath, string keyPassword, string signedPackageId) { if (!File.Exists(packagePath)) { throw new FileNotFoundException(string.Format("File {0} does not exist.", packagePath)); } string package = Path.GetFullPath(packagePath); if (!string.IsNullOrEmpty(outputPath) && packagePath != outputPath) { File.Copy(packagePath, outputPath, true); package = Path.GetFullPath(outputPath); } try { using (Stream stream = new FileStream(package, FileMode.Open, FileAccess.ReadWrite)) { using (ZipPackage zipPackage = Package.Open(stream, FileMode.Open, FileAccess.ReadWrite) as ZipPackage) { return(SignPackage(zipPackage, keyPath, keyPassword, signedPackageId)); } } } catch (Exception) { if (!string.IsNullOrEmpty(outputPath)) { File.Delete(outputPath); } throw; } }
public CompressedPackage(string filename) { s = FileSystem.Open(filename); pkg = (ZipPackage)ZipPackage.Open(s, FileMode.Open); hashes = pkg.GetParts() .Select(p => PackageEntry.HashFilename(p.Uri.LocalPath)).ToArray(); }
//------------------------------------------------------ // // Public Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Constructors // //------------------------------------------------------ #region Internal Constructors /// <summary> /// Constructs a ZipPackagePart for an atomic (i.e. non-interleaved) part. /// This is called from the ZipPackage class as a result of GetPartCore, /// GetPartsCore or CreatePartCore methods /// </summary> /// <param name="zipPackage"></param> /// <param name="zipArchive"></param> /// <param name="zipArchiveEntry"></param> /// <param name="zipStreamManager"></param> /// <param name="partUri"></param> /// <param name="compressionOption"></param> /// <param name="contentType"></param> internal ZipPackagePart(ZipPackage zipPackage, ZipArchive zipArchive, ZipArchiveEntry zipArchiveEntry, ZipStreamManager zipStreamManager, PackUriHelper.ValidatedPartUri partUri, string contentType, CompressionOption compressionOption) : base(zipPackage, partUri, contentType, compressionOption) { _zipPackage = zipPackage; _zipArchive = zipArchive; _zipStreamManager = zipStreamManager; _zipArchiveEntry = zipArchiveEntry; }
/// <summary> /// Constructs a ZipPackagePart for an atomic (i.e. non-interleaved) part. /// This is called from the ZipPackage class as a result of GetPartCore, /// GetPartsCore or CreatePartCore methods /// </summary> /// <param name="zipPackage"></param> /// <param name="zipArchive"></param> /// <param name="zipArchiveEntry"></param> /// <param name="zipStreamManager"></param> /// <param name="partUri"></param> /// <param name="compressionOption"></param> /// <param name="contentType"></param> internal ZipPackagePart(ZipPackage zipPackage, ZipArchive zipArchive, ZipArchiveEntry zipArchiveEntry, ZipStreamManager zipStreamManager, PackUriHelper.ValidatedPartUri partUri, string contentType, CompressionOption compressionOption) : base(zipPackage, partUri, contentType, compressionOption) { _zipPackage = zipPackage; _zipArchive = zipArchive; _zipStreamManager = zipStreamManager; _zipArchiveEntry = zipArchiveEntry; }
// Replaces ZipPackage.LoadParts, which is naive and very, very slow, and used every time a package is opened. private static bool New_System_IO_Packaging_ZipPackage_LoadParts(System.IO.Packaging.ZipPackage __instance, ref Dictionary <Uri, ZipPackagePart> ___parts) { ___parts = new Dictionary <Uri, ZipPackagePart>(); var packageStream = __instance.GetFieldOrPropertyValue <Stream>("PackageStream"); using (var zipArchive = new ZipArchive(packageStream, ZipArchiveMode.Read, true)) { foreach (var zipArchiveEntry in zipArchive.Entries) { // We don't care what Packaging thinks the content type is System_IO_Packaging_ZipPackage_CreatePartCore(__instance, new Uri("/" + zipArchiveEntry.FullName, UriKind.Relative), "application/octet", CompressionOption.Maximum); } } return(false); }
/// <summary> /// A helper method that decompresses the the Ribbon data returned /// </summary> /// <param name="data">The compressed ribbon data</param> /// <returns></returns> private byte[] unzipRibbon(byte[] data) { System.IO.Packaging.ZipPackage package = null; MemoryStream memStream = null; memStream = new MemoryStream(); memStream.Write(data, 0, data.Length); package = (ZipPackage)ZipPackage.Open(memStream, FileMode.Open); ZipPackagePart part = (ZipPackagePart)package.GetPart(new Uri("/RibbonXml.xml", UriKind.Relative)); using (Stream strm = part.GetStream()) { long len = strm.Length; byte[] buff = new byte[len]; strm.Read(buff, 0, (int)len); return(buff); } }
public bool SignPackage(ZipPackage package, string keyPath, string keyPassword, string signedPackageId) { bool signedPackage = false; foreach (var packagePart in package.GetParts()) { if (TrySignPackagePart(packagePart, keyPath, keyPassword, signedPackage)) { signedPackage = true; } } if (!string.IsNullOrEmpty(signedPackageId)) { TryUpdatePackageId(package, signedPackageId); } return signedPackage; }
public bool SignPackage(ZipPackage package, string keyPath, string keyPassword, string signedPackageId) { bool signedPackage = false; foreach (var packagePart in package.GetParts()) { if (TrySignPackagePart(packagePart, keyPath, keyPassword, signedPackage)) { signedPackage = true; } } if (!string.IsNullOrEmpty(signedPackageId)) { TryUpdatePackageId(package, signedPackageId); } return(signedPackage); }
/// <summary> Attempts to get the NuGet package metadata from the given package. </summary> /// <param name="package"> The package.</param> /// <param name="metadata"> The package metadata.</param> /// <returns> true if it succeeds, false if it fails. </returns> private static bool TryGetPackageMetadata(ZipPackage package, out ManifestMetadata metadata) { var packageRelationship = package.GetRelationshipsByType("http://schemas.microsoft.com/packaging/2010/07/manifest") .SingleOrDefault( ); if (packageRelationship == null) { metadata = null; return(false); } var manifestPart = package.GetPart(packageRelationship.TargetUri); using (var partStream = manifestPart.GetStream( )) { var manifest = Manifest.ReadFrom(partStream, NullPropertyProvider.Instance, validateSchema: false); metadata = manifest.Metadata; return(true); } }
private static void TryUpdatePackageId(ZipPackage package, string signedPackageId) { // Update package id var manifestRelationType = package.GetRelationshipsByType("http://schemas.microsoft.com/packaging/2010/07/manifest").SingleOrDefault(); if (manifestRelationType != null) { var manifestPart = package.GetPart(manifestRelationType.TargetUri); var manifest = Manifest.ReadFrom(manifestPart.GetStream(), NullPropertyProvider.Instance, false); manifest.Metadata.Id = signedPackageId; package.DeleteRelationship(manifestRelationType.Id); package.DeletePart(manifestPart.Uri); Uri uri = PackUriHelper.CreatePartUri(new Uri(string.Format("/{0}.nuspec", signedPackageId), UriKind.Relative)); var newManifestPart = package.CreatePart(uri, "application/octet", CompressionOption.Maximum); manifest.Save(newManifestPart.GetStream(FileMode.Create)); package.CreateRelationship(uri, TargetMode.Internal, "http://schemas.microsoft.com/packaging/2010/07/manifest"); } }
public void PackageBuilderWorksWithFileNamesContainingSpecialCharacters() { // Arrange var fileNames = new[] { @"lib\regular.file.dll", @"lib\name with spaces.dll", @"lib\C#\test.dll", @"content\images\logo123?#78.png", @"content\images\bread&butter.jpg", }; // Act var builder = new PackageBuilder { Id = "test", Version = new SemanticVersion("1.0"), Description = "test" }; builder.Authors.Add("test"); foreach (var name in fileNames) { builder.Files.Add(CreatePackageFile(name)); } // Assert using (MemoryStream stream = new MemoryStream()) { builder.Save(stream); var zipPackage = new ZipPackage(() => new MemoryStream(stream.ToArray()), enableCaching: false); Assert.Equal(@"content\images\bread&butter.jpg", zipPackage.GetFiles().ElementAt(0).Path); Assert.Equal(@"content\images\logo123?#78.png", zipPackage.GetFiles().ElementAt(1).Path); Assert.Equal(@"lib\C#\test.dll", zipPackage.GetFiles().ElementAt(2).Path); Assert.Equal(@"lib\name with spaces.dll", zipPackage.GetFiles().ElementAt(3).Path); Assert.Equal(@"lib\regular.file.dll", zipPackage.GetFiles().ElementAt(4).Path); } }
/// <summary> /// Gets an XML reader for the specified part, or null, if the part not exists. /// </summary> static XmlTextReader GetPartAsXmlReader(ZipPackage package, Uri uri) { ZipPackagePart part = package.GetPart(uri) as ZipPackagePart; string xml = String.Empty; using (Stream stream = part.GetStream()) { using (StreamReader sr = new StreamReader(stream)) { xml = sr.ReadToEnd(); } } XmlTextReader reader = new XmlTextReader(new StringReader(xml)); return reader; }
/// <summary> /// Gets the specified part as string. Returns an empty string if the part not exists. /// </summary> static string GetPartAsString(ZipPackage package, Uri uri) { ZipPackagePart part = package.GetPart(uri) as ZipPackagePart; string xml = String.Empty; using (Stream stream = part.GetStream()) { using (StreamReader sr = new StreamReader(stream)) { xml = sr.ReadToEnd(); #if true_ string xmlPath = IOPath.Combine(IOPath.GetDirectoryName(xpsFilename), IOPath.GetFileNameWithoutExtension(xpsFilename)) + ".xml"; using (StreamWriter sw = new StreamWriter(xmlPath)) { sw.Write(xml); } #endif //XpsElement el = PdfSharp.Xps.Parsing.XpsParser.Parse(xml); //PdfRenderer renderer = new PdfRenderer(); //renderer.RenderPage(page, el as PdfSharp.Xps.XpsModel.FixedPage); } } return xml; }
internal static XmlTextReader GetPartAsXmlReader(ZipPackage package, string uriString) { // HACK: just make it work... if (!uriString.StartsWith("/")) uriString = "/" + uriString; // Documents with relative uri exists. if (uriString.StartsWith("/..")) uriString = uriString.Substring(3); ZipPackagePart part = package.GetPart(new Uri(uriString, UriKind.Relative)) as ZipPackagePart; string xml = String.Empty; using (Stream stream = part.GetStream()) { using (StreamReader sr = new StreamReader(stream)) { xml = sr.ReadToEnd(); } } XmlTextReader reader = new XmlTextReader(new StringReader(xml)); return reader; }
private static void ReadPartOfPackage(ZipPackage package, string partName, Action<XmlReader> partsReader) { Uri partUri = new Uri(partName, UriKind.Relative); if (!package.PartExists(partUri)) { return; } var part = (ZipPackagePart)package.GetPart(partUri); var stream = part.GetStream(); if (stream.Length == 0) { return; } using (var reader = new XmlTextReader(stream)) { partsReader(reader); } }
/// <summary> /// </summary> /// <param name="path">Path to the package.</param> /// <param name="packageMode">FileMode in which the package should be opened.</param> /// <param name="packageAccess">FileAccess with which the package should be opened.</param> /// <param name="packageShare">FileShare with which the package is opened.</param> /// <returns>Package</returns> /// <exception cref="ArgumentNullException">If path parameter is null</exception> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration [packageAccess] does not have one of the valid values</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [packageMode] does not have one of the valid values</exception> public static Package Open( string path, FileMode packageMode, FileAccess packageAccess, FileShare packageShare) { Package package = null; if (path == null) throw new ArgumentNullException(nameof(path)); ThrowIfFileModeInvalid(packageMode); ThrowIfFileAccessInvalid(packageAccess); if (packageMode == FileMode.OpenOrCreate && packageAccess != FileAccess.ReadWrite) throw new ArgumentException(SR.UnsupportedCombinationOfModeAccess); if (packageMode == FileMode.Create && packageAccess != FileAccess.ReadWrite) throw new ArgumentException(SR.UnsupportedCombinationOfModeAccess); if (packageMode == FileMode.CreateNew && packageAccess != FileAccess.ReadWrite) throw new ArgumentException(SR.UnsupportedCombinationOfModeAccess); if (packageMode == FileMode.Open && packageAccess == FileAccess.Write) throw new ArgumentException(SR.UnsupportedCombinationOfModeAccess); if (packageMode == FileMode.Truncate && packageAccess == FileAccess.Read) throw new ArgumentException(SR.UnsupportedCombinationOfModeAccess); if (packageMode == FileMode.Truncate) throw new NotSupportedException(SR.UnsupportedCombinationOfModeAccess); //Note: FileShare enum is not being verified at this stage, as we do not interpret the flag in this //code at all and just pass it on to the next layer, where the necessary validation can be //performed. Also, there is no meaningful way to check this parameter at this layer, as the //FileShare enumeration is a set of flags and flags/Bit-fields can be combined using a //bitwise OR operation to create different values, and validity of these values is specific to //the actual physical implementation. //Verify if this is valid for filenames FileInfo packageFileInfo = new FileInfo(path); try { package = new ZipPackage(packageFileInfo.FullName, packageMode, packageAccess, packageShare); package._openFileMode = packageMode; //We need to get all the parts if any exists from the underlying file //so that we have the names in the Normalized form in our in-memory //data structures. //Note: If ever this call is removed, each individual call to GetPartCore, //may result in undefined behavior as the underlying ZipArchive, maintains the //files list as being case-sensitive. if (package.FileOpenAccess == FileAccess.ReadWrite || package.FileOpenAccess == FileAccess.Read) package.GetParts(); } catch { if (package != null) { package.Close(); } throw; } return package; }
internal static Package Open(Stream stream, FileMode packageMode, FileAccess packageAccess, bool streaming) { EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXOpenPackageBegin); Package package = null; try { if (stream == null) throw new ArgumentNullException("stream"); ValidateStreamingAccess(packageMode, packageAccess, null /* no FileShare info */, streaming); //FileMode and FileAccess Enums are validated in the following call Stream ensuredStream = ValidateModeAndAccess(stream, packageMode, packageAccess); // Today the Open(Stream) method is purely used for streams of Zip file format as // that is the default underlying file format mapper implemented. package = new ZipPackage(ensuredStream, packageMode, packageAccess, streaming); if (!package._inStreamingCreation) // No read operation in streaming production. { //We need to get all the parts if any exists from the underlying file //so that we have the names in the Normalized form in our in-memory //data structures. //Note: If ever this call is removed, each individual call to GetPartCore, //may result in undefined behavior as the underlying ZipArchive, maintains the //files list as being case-sensitive. if (package.FileOpenAccess == FileAccess.ReadWrite || package.FileOpenAccess == FileAccess.Read) package.GetParts(); } } finally { EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXOpenPackageEnd); } return package; }
/// <summary> /// Constructs a ZipPackagePart for an interleaved part. This is called outside of streaming /// production when an interleaved part is encountered in the package. /// </summary> /// <param name="container"></param> /// <param name="zipArchive"></param> /// <param name="pieces"></param> /// <param name="partUri"></param> /// <param name="compressionOption"></param> /// <param name="contentType"></param> internal ZipPackagePart(ZipPackage container, ZipArchive zipArchive, List<PieceInfo> pieces, PackUriHelper.ValidatedPartUri partUri, string contentType, CompressionOption compressionOption) :base(container, partUri, contentType, compressionOption) { _zipArchive = zipArchive; _pieces = pieces; }
//------------------------------------------------------ // // Public Events // //------------------------------------------------------ // None //------------------------------------------------------ // // Internal Constructors // //------------------------------------------------------ #region Internal Constructors /// <summary> /// Constructs a ZipPackagePart for an atomic (i.e. non-interleaved) part. /// This is called from the ZipPackage class as a result of GetPartCore, /// GetPartsCore or CreatePartCore methods /// </summary> /// <param name="container"></param> /// <param name="zipFileInfo"></param> /// <param name="partUri"></param> /// <param name="compressionOption"></param> /// <param name="contentType"></param> internal ZipPackagePart(ZipPackage container, ZipFileInfo zipFileInfo, PackUriHelper.ValidatedPartUri partUri, string contentType, CompressionOption compressionOption) :base(container, partUri, contentType, compressionOption) { _zipArchive = zipFileInfo.ZipArchive; _zipFileInfo = zipFileInfo; }
internal static byte[] GetPartAsBytes(ZipPackage package, string uriString) { Uri target = new Uri(uriString, UriKind.Relative); #if true if (!uriString.StartsWith("/")) { //target = PackUriHelper.ResolvePartUri(package.t.GetRelationship Uri("/documents2/3/Pages", UriKind.RelativeOrAbsolute), target); //PackagePartCollection coll = package.GetParts(); // HACK: introduce a "CurrentPart" target = PackUriHelper.ResolvePartUri(new Uri("/documents/1/Pages/1.page", UriKind.RelativeOrAbsolute), target); } #else // HACK: just make it go... if (!uriString.StartsWith("/")) uriString = "/" + uriString; // Documents with relative uri exists. if (uriString.StartsWith("/..")) uriString = uriString.Substring(3); #endif ZipPackagePart part = package.GetPart(target) as ZipPackagePart; byte[] bytes = null; using (Stream stream = part.GetStream()) { int length = (int)stream.Length; bytes = new byte[length]; stream.Read(bytes, 0, length); } return bytes; }
/// <summary> /// This method gives the possibility of opening a package in streaming mode. /// When 'streaming' is true, the only allowed file modes are Create and CreateNew, /// the only allowed file access is Write and the only allowed FileShare values are /// Null and Read. /// </summary> /// <param name="path">Path to the package.</param> /// <param name="packageMode">FileMode in which the package should be opened.</param> /// <param name="packageAccess">FileAccess with which the package should be opened.</param> /// <param name="packageShare">FileShare with which the package is opened.</param> /// <param name="streaming">Whether to allow the creation of part pieces while enforcing write-once access.</param> /// <returns>Package</returns> /// <exception cref="ArgumentNullException">If path parameter is null</exception> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration [packageAccess] does not have one of the valid values</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [packageMode] does not have one of the valid values</exception> internal static Package Open( string path, FileMode packageMode, FileAccess packageAccess, FileShare packageShare, bool streaming) { EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXOpenPackageBegin); Package package = null; try { if (path == null) throw new ArgumentNullException("path"); ThrowIfFileModeInvalid(packageMode); ThrowIfFileAccessInvalid(packageAccess); ValidateStreamingAccess(packageMode, packageAccess, packageShare, streaming); //Note: FileShare enum is not being verfied at this stage, as we do not interpret the flag in this //code at all and just pass it on to the next layer, where the necessary validation can be //performed. Also, there is no meaningful way to check this parameter at this layer, as the //FileShare enumeration is a set of flags and flags/Bit-fields can be combined using a //bitwise OR operation to create different values, and validity of these values is specific to //the actual physical implementation. //Verify if this is valid for filenames FileInfo packageFileInfo = new FileInfo(path); package = new ZipPackage(packageFileInfo.FullName, packageMode, packageAccess, packageShare, streaming); if (!package._inStreamingCreation) // No read operation in streaming production. { //We need to get all the parts if any exists from the underlying file //so that we have the names in the Normalized form in our in-memory //data structures. //Note: If ever this call is removed, each individual call to GetPartCore, //may result in undefined behavior as the underlying ZipArchive, maintains the //files list as being case-sensitive. if (package.FileOpenAccess == FileAccess.ReadWrite || package.FileOpenAccess == FileAccess.Read) package.GetParts(); } } finally { EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXPS, EventTrace.Event.WClientDRXOpenPackageEnd); } return package; }
public ZipPartStream(ZipPackage package, MemoryStream stream, FileAccess access) { BaseStream = stream; Package = package; Writeable = access != FileAccess.Read; }
/// <summary> /// </summary> /// <param name="stream">Stream on which the package is created</param> /// <param name="packageMode">FileMode in which the package is to be opened</param> /// <param name="packageAccess">FileAccess on the package that is opened</param> /// <returns>Package</returns> /// <exception cref="ArgumentNullException">If stream parameter is null</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [packageMode] does not have one of the valid values</exception> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration [packageAccess] does not have one of the valid values</exception> /// <exception cref="IOException">If package to be created should have readwrite/read access and underlying stream is write only</exception> /// <exception cref="IOException">If package to be created should have readwrite/write access and underlying stream is read only</exception> public static Package Open(Stream stream, FileMode packageMode, FileAccess packageAccess) { Package package = null; if (stream == null) throw new ArgumentNullException(nameof(stream)); try { // Today the Open(Stream) method is purely used for streams of Zip file format as // that is the default underlying file format mapper implemented. package = new ZipPackage(stream, packageMode, packageAccess); //We need to get all the parts if any exists from the underlying file //so that we have the names in the Normalized form in our in-memory //data structures. //Note: If ever this call is removed, each individual call to GetPartCore, //may result in undefined behavior as the underlying ZipArchive, maintains the //files list as being case-sensitive. if (package.FileOpenAccess == FileAccess.ReadWrite || package.FileOpenAccess == FileAccess.Read) package.GetParts(); } catch { if (package != null) { package.Close(); } throw; } return package; }
public ZipPartStream (ZipPackage package, MemoryStream stream, FileAccess access) { BaseStream = stream; Package = package; Writeable = access != FileAccess.Read; }