public static Stream GetTestPackageWithContentXmlFile() { var stream = new MemoryStream(); using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) { zip.AddEntry("lib/a.dll", ZeroContent); zip.AddEntry("[Content_Types].xml", ZeroContent); zip.AddEntry("content/[Content_Types].xml", ZeroContent); zip.AddEntry("packageA.nuspec", @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata> <id>packageA</id> <version>2.0.3</version> <authors>Author1, author2</authors> <description>Sample description</description> <language>en-US</language> <projectUrl>http://www.nuget.org/</projectUrl> <licenseUrl>http://www.nuget.org/license</licenseUrl> </metadata> </package>", Encoding.UTF8); } return(stream); }
public void PackageFolderReader_NuspecCountNested() { // Arrange using (var workingDir = TestDirectory.Create()) using (var stream = new MemoryStream()) { using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) { zip.AddEntry("lib/net45/a.dll", new byte[0]); zip.AddEntry("package.nuspec", new byte[5]); zip.AddEntry("content/package.nuspec", new byte[0]); } stream.Seek(0, SeekOrigin.Begin); var zipFile = new ZipArchive(stream, ZipArchiveMode.Read); zipFile.ExtractAll(workingDir); var folderReader = new PackageFolderReader(workingDir); // Act using (var nuspec = folderReader.GetNuspec()) { // Assert Assert.NotNull(nuspec); Assert.Equal(5, nuspec.Length); } } }
/// <summary> /// Generates a test .nupkg with icon information /// </summary> /// <param name="iconByteSize">if it is less than zero, it will not include the zip file</param> /// <returns></returns> public static TempFile GetTestPackageIcon(int iconByteSize) { var stream = new TempFile(); using (var zip = new ZipArchive(File.Create(stream), ZipArchiveMode.Create)) { if (iconByteSize >= 0) { zip.AddEntry("content/big.jpg", new byte[iconByteSize]); } zip.AddEntry("packageA.nuspec", @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata> <id>iconPackage</id> <version>5.2.0</version> <authors>Author1, author2</authors> <description>Sample icon description</description> <icon>content/big.jpg</icon> </metadata> </package>", Encoding.UTF8); } return(stream); }
public static TempFile GetPackageCoreReaderLongPathTestPackage() { var file = new TempFile(); using (var zip = new ZipArchive(File.Create(file), ZipArchiveMode.Create)) { zip.AddEntry("lib/net45/a.dll", ZeroContent); zip.AddEntry("content/2.5.6/core/store/x64/netcoreapp2.0/microsoft.extensions.configuration.environmentvariables/2.0.0/lib/netstandard2.0/Microsoft.Extensions.Configuration.EnvironmentVariables.dll ", ZeroContent); zip.AddEntry("Aa.nuspec", @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata minClientVersion=""1.2.3""> <id>microsoft.dadsdasfihfhofhoashfosfho.dsahodfhasfhasof</id> <version>2.5.6</version> <authors>author</authors> <description>description</description> <packageTypes> <packageType name=""Bb"" /> <packageType name=""Cc"" version=""7.8.9"" /> </packageTypes> </metadata> </package>", Encoding.UTF8); } return(file); }
public static TempFile GetLegacyContentPackageMixed() { var file = new TempFile(); using (var zip = new ZipArchive(File.Create(file), ZipArchiveMode.Create)) { zip.AddEntry("content/Scripts/test.js", ZeroContent); zip.AddEntry("content/net40/Scripts/test2.js", ZeroContent); zip.AddEntry("content/net40/Scripts/testb.js", ZeroContent); zip.AddEntry("content/net45/Scripts/test3.js", ZeroContent); zip.AddEntry("packageA.nuspec", @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata> <id>contentPackage</id> <version>2.0.3</version> <authors>Author1, author2</authors> <description>Sample description</description> <language>en-US</language> <projectUrl>http://www.nuget.org/</projectUrl> <licenseUrl>http://www.nuget.org/license</licenseUrl> </metadata> </package>", Encoding.UTF8); } return(file); }
public static TempFile GetPackageWithPackageTypes() { var file = new TempFile(); using (var zip = new ZipArchive(File.Create(file), ZipArchiveMode.Create)) { zip.AddEntry("lib/net40/test40.dll", ZeroContent); zip.AddEntry("packageA.nuspec", @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata> <id>packageA</id> <version>2.0.3</version> <authors>Author1, author2</authors> <description>Sample description</description> <packageTypes> <packageType name=""foo"" /> <packageType name=""bar"" version=""2.0.0"" /> </packageTypes> </metadata> </package>", Encoding.UTF8); } return(file); }
public void GetNuspec_SupportsEscapingInFileName() { // Arrange using (var workingDir = TestDirectory.Create()) using (var stream = new MemoryStream()) { using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) { zip.AddEntry("lib/net45/a.dll", new byte[0]); zip.AddEntry("package%20.nuspec", new byte[5]); } ExtractAll(stream, workingDir); using (var reader = new PackageFolderReader(workingDir)) { // Act using (var nuspec = reader.GetNuspec()) { // Assert Assert.NotNull(nuspec); Assert.Equal(5, nuspec.Length); } } } }
public static TempFile GetPackageCoreReaderTestPackage() { var file = new TempFile(); using (var zip = new ZipArchive(File.Create(file), ZipArchiveMode.Create)) { zip.AddEntry("lib/net45/a.dll", ZeroContent); zip.AddEntry("lib/net45/b.dll", ZeroContent); zip.AddEntry("Aa.nuspec", @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata minClientVersion=""1.2.3""> <id>Aa</id> <version>4.5.6</version> <authors>author</authors> <description>description</description> <packageTypes> <packageType name=""Bb"" /> <packageType name=""Cc"" version=""7.8.9"" /> </packageTypes> </metadata> </package>", Encoding.UTF8); } return(file); }
public void GetNuspec_ThrowsForMultipleRootNuspecs() { // Arrange using (var workingDir = TestDirectory.Create()) using (var stream = new MemoryStream()) { using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) { zip.AddEntry("lib" + Path.DirectorySeparatorChar + "net45" + Path.DirectorySeparatorChar + "a.dll", new byte[0]); zip.AddEntry("package.NUSPEC", new byte[0]); zip.AddEntry("package2.nuspec", new byte[0]); } ExtractAll(stream, workingDir); using (var reader = new PackageFolderReader(workingDir)) { // Act var exception = Assert.Throws <PackagingException>(() => reader.GetNuspec()); // Assert Assert.Equal("Package contains multiple nuspec files.", exception.Message); } } }
public void GetNuspec_ThrowsForNoRootNuspec() { // Arrange using (var workingDir = TestDirectory.Create()) using (var stream = new MemoryStream()) { using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) { zip.AddEntry("lib/net45/a.dll", new byte[0]); zip.AddEntry("content/package.nuspec", new byte[0]); } ExtractAll(stream, workingDir); using (var reader = new PackageFolderReader(workingDir)) { // Act var exception = Assert.Throws <PackagingException>(() => reader.GetNuspec()); // Assert var log = exception.AsLogMessage(); Assert.Equal(NuGetLogCode.NU5037, log.Code); Assert.Contains("The package is missing the required nuspec file.", log.Message); } } }
public static FileInfo GetLegacyContentPackage() { var file = Path.GetTempFileName() + ".nupkg"; var result = new FileInfo(file); using (var zip = new ZipArchive(File.Create(result.FullName), ZipArchiveMode.Create)) { zip.AddEntry("content/Scripts/test.js", new byte[] { 0 }); zip.AddEntry("content/Scripts/test2.js", new byte[] { 0 }); zip.AddEntry("content/Scripts/test3.js", new byte[] { 0 }); zip.AddEntry("packageA.nuspec", @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata> <id>contentPackage</id> <version>2.0.3</version> <authors>Author1, author2</authors> <description>Sample description</description> <language>en-US</language> <projectUrl>http://www.nuget.org/</projectUrl> <licenseUrl>http://www.nuget.org/license</licenseUrl> </metadata> </package>", Encoding.UTF8); } return(result); }
public static TempFile GetLegacyTestPackageWithInvalidPortableFrameworkFolderName() { var file = new TempFile(); using (var zip = new ZipArchive(File.Create(file), ZipArchiveMode.Create)) { zip.AddEntry("lib/test.dll", ZeroContent); zip.AddEntry("lib/net45/test45.dll", ZeroContent); zip.AddEntry("lib/portable-net+win+wpa+wp+sl+net-cf+netmf+MonoAndroid+MonoTouch+Xamarin.iOS/test.dll", ZeroContent); zip.AddEntry("packageA.nuspec", @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata> <id>packageA</id> <version>2.0.3</version> <authors>Author1, author2</authors> <description>Sample description</description> <language>en-US</language> <projectUrl>http://www.nuget.org/</projectUrl> <licenseUrl>http://www.nuget.org/license</licenseUrl> </metadata> </package>", Encoding.UTF8); } return(file); }
private void ProcessEntry(IArchiveEntry entry, IList <Stream> imageStreams, ZipArchive output, SimpleEncoder encoder) { using (var stream = entry.OpenEntryStream()) { var ms = new MemoryStream(); imageStreams.Add(ms); if (entry.Key.StartsWith("__MACOSX")) { return; } if (!entry.Key.EndsWith(".jpg") && !entry.Key.EndsWith(".png")) { stream.CopyTo(ms); output.AddEntry(entry.Key, ms); return; } Bitmap bits; try { bits = new Bitmap(stream); } catch (Exception e) { Logger.LogError("Error parsing bitmap: " + entry.Key); Logger.LogDebug(e, LogLevel.Error); return; } if (bits.PixelFormat != System.Drawing.Imaging.PixelFormat.Format24bppRgb) { var newBits = ChangePixelFormat(bits); bits.Dispose(); bits = newBits; } try { encoder.Encode(bits, ms, Quality); output.AddEntry(entry.Key + ".webp", ms); } catch (Exception e) { Logger.LogError("Error encoding entry: " + entry.Key); Logger.LogDebug(e, LogLevel.Error); } finally { bits.Dispose(); } } }
private void ProcessEntry(Stream stream, string entryKey, ZipArchive output, SimpleEncoder encoder) { if (entryKey.StartsWith("__MACOSX")) { return; } if (!entryKey.EndsWith(".jpg") && !entryKey.EndsWith(".png")) { output.AddEntry(entryKey, stream); return; } Bitmap bits; try { bits = new Bitmap(stream); } catch (Exception e) { Logger.LogError("Error parsing bitmap: " + entryKey); Logger.LogDebug(e, LogLevel.Error); return; } if (bits.PixelFormat != System.Drawing.Imaging.PixelFormat.Format24bppRgb) { var newBits = ChangePixelFormat(bits); bits.Dispose(); bits = newBits; } try { using (var ms = new MemoryStream()) { encoder.Encode(bits, ms, Quality); stream.Dispose(); stream = new MemoryStream(); ms.WriteTo(stream); output.AddEntry(Path.ChangeExtension(entryKey, "webp"), stream); } } catch (Exception e) { Logger.LogError("Error encoding entry: " + entryKey); Logger.LogDebug(e, LogLevel.Error); } finally { bits.Dispose(); } }
public void EnumerateSkipDeletedEntries(bool deleteFromExistingFile) { var ms = new MemoryStream(Encoding.UTF8.GetBytes(TEXT)); File.WriteAllText("file1.txt", "1111"); string filePath = Path.GetFullPath("file1.txt"); if (File.Exists("test-archive-write.zip")) { File.Delete("test-archive-write.zip"); } ZipArchive zip = null; try { zip = ZipArchive.Open("test-archive-write.zip", FileMode.CreateNew); ZipEntry e; e = zip.AddFile(filePath, "/path/ZipTestCopy1.exe"); e = zip.AddFile(filePath, "/path/ZipTestCopy2.exe"); var text = "Hello World"; e = zip.AddEntry("/data/foo1.txt", text, Encoding.UTF8, CompressionMethod.Store); e = zip.AddEntry("/data/foo2.txt", File.OpenRead(filePath), CompressionMethod.Store); if (deleteFromExistingFile) { zip.Close(); zip = ZipArchive.Open("test-archive-write.zip", FileMode.Open); } ValidateEnumeratedEntries(zip, "path/ZipTestCopy1.exe", "path/ZipTestCopy2.exe", "data/foo1.txt", "data/foo2.txt"); // Delete first zip.DeleteEntry("path/ZipTestCopy1.exe"); ValidateEnumeratedEntries(zip, "path/ZipTestCopy2.exe", "data/foo1.txt", "data/foo2.txt"); // Delete last zip.DeleteEntry("data/foo2.txt"); ValidateEnumeratedEntries(zip, "path/ZipTestCopy2.exe", "data/foo1.txt"); // Delete middle zip.DeleteEntry("path/ZipTestCopy2.exe"); ValidateEnumeratedEntries(zip, "data/foo1.txt"); // Delete all zip.DeleteEntry("data/foo1.txt"); ValidateEnumeratedEntries(zip); } finally { zip?.Dispose(); } }
public static FileInfo GetLegacyTestPackageWithReferenceGroups() { string file = Path.GetTempFileName() + ".nupkg"; FileInfo result = new FileInfo(file); using (var zip = new ZipArchive(File.Create(result.FullName), ZipArchiveMode.Create)) { zip.AddEntry("lib/test.dll", new byte[] { 0 }); zip.AddEntry("lib/net40/test40.dll", new byte[] { 0 }); zip.AddEntry("lib/net40/test40b.dll", new byte[] { 0 }); zip.AddEntry("lib/net45/test45.dll", new byte[] { 0 }); zip.AddEntry("packageA.nuspec", @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata> <id>packageA</id> <version>2.0.3</version> <authors>Author1, author2</authors> <description>Sample description</description> <language>en-US</language> <projectUrl>http://www.nuget.org/</projectUrl> <licenseUrl>http://www.nuget.org/license</licenseUrl> <dependencies> <group> <dependency id=""RouteMagic"" version=""1.1.0"" /> </group> <group targetFramework=""net40""> <dependency id=""jQuery"" /> <dependency id=""WebActivator"" /> </group> <group targetFramework=""sl30""> </group> </dependencies> <references> <group targetFramework=""net45""> <reference file=""test45.dll"" /> </group> <group> <reference file=""test.dll"" /> </group> </references> <frameworkAssemblies> <frameworkAssembly assemblyName=""wp80Assem"" targetFramework=""wp80"" /> <frameworkAssembly assemblyName=""anyAssem"" /> </frameworkAssemblies> </metadata> </package>", Encoding.UTF8); } return(result); }
/// <summary> /// Creates a signed CDA package zip file. /// </summary> /// <param name="package">The CDAPackageBase instance used to generate the zip file content.</param> /// <param name="signingCert">The certificate used to sign the CDA root document.</param> /// <returns>A byte array of the zip file content.</returns> public static byte[] Create(CDAPackage package, X509Certificate2 signingCert) { // Validation on package Validation.ValidateArgumentRequired("package", package); // Validate CDAPackage CDAPackageValidation.ValidateCDAPackage(package, signingCert != null); var ms = new MemoryStream(); // Generate signature if package operation is ADD or REPLACE byte[] signatureContent = null; if (signingCert != null) { signatureContent = CreateSignature(package, signingCert); package.CDASignature = new CDAPackageFile(); package.CDASignature.CDAPackageFileType = CDAPackageFile.FileType.Signature; package.CDASignature.FileContent = signatureContent; package.CDASignature.FileName = "CDA_SIGN.XML"; } using (var zip = new ZipArchive(ms, ZipArchiveMode.Create)) { zip.CreateEntry("IHE_XDM/"); zip.CreateEntry("IHE_XDM/SUBSET01/"); zip.AddEntry("IHE_XDM/SUBSET01/" + package.CDADocumentRoot.FileName, package.CDADocumentRoot.FileContent); // Add signature if present if (signatureContent != null) { zip.AddEntry("IHE_XDM/SUBSET01/" + package.CDASignature.FileName, signatureContent); } if (package.CDADocumentAttachments != null) { foreach (var file in package.CDADocumentAttachments) { zip.AddEntry("IHE_XDM/SUBSET01/" + file.FileName, file.FileContent); } } } var zipContent = ms.ToArray(); ms.Close(); return(zipContent); }
public void HttpStreamValidation_ValidateNupkg_RejectsPartialNupkg() { // Arrange using (var zipStream = new MemoryStream()) using (var stream = new MemoryStream()) { using (var zip = new ZipArchive(zipStream, ZipArchiveMode.Create, leaveOpen: true)) { zip.AddEntry("package.nuspec", new byte[0]); } zipStream.Seek(0, SeekOrigin.Begin); var partialLength = (int)zipStream.Length - 1; stream.Write(zipStream.ToArray(), 0, partialLength); stream.Seek(0, SeekOrigin.Begin); // Act & Assert var actual = Assert.Throws <InvalidDataException>(() => { HttpStreamValidation.ValidateNupkg( Uri, stream); }); Assert.IsType <InvalidDataException>(actual.InnerException); } }
public void HttpStreamValidation_ValidateNupkg_RejectsNupkgWithBadPrefix() { // Arrange using (var zipStream = new MemoryStream()) using (var stream = new MemoryStream()) { using (var zip = new ZipArchive(zipStream, ZipArchiveMode.Create, leaveOpen: true)) { zip.AddEntry("package.nuspec", new byte[0]); } zipStream.Seek(0, SeekOrigin.Begin); var badPrefix = Encoding.ASCII.GetBytes("bad!!!"); stream.Write(badPrefix, 0, badPrefix.Length); zipStream.CopyTo(stream); stream.Seek(0, SeekOrigin.Begin); // Act & Assert var actual = Assert.Throws <InvalidDataException>(() => { HttpStreamValidation.ValidateNupkg( Uri, stream); }); Assert.IsType <InvalidDataException>(actual.InnerException); } }
private void ArchiveMulti(ZipArchive archive, string root, string from, string toFile, string notDirName) { DirectoryInfo di = new DirectoryInfo(from); var dris = di.GetDirectories(); foreach (var fi in di.GetFiles()) { //var fileInfo = new FileInfo(from); //archive.AddEntry(fi.FullName.Substring(from.Length), fileInfo.OpenRead(), true, fileInfo.Length, // fileInfo.LastWriteTime); archive.AddEntry(fi.FullName.Substring(root.Length), fi.OpenRead(), true, fi.Length, fi.LastWriteTime); //archive.AddEntry(fi.Name, fi.OpenRead(), true); } foreach (var dir in dris) { if (dir.Name == notDirName)//vs 编译配置文件,不添加 { continue; } ArchiveMulti(archive, root, dir.FullName, toFile, notDirName); } }
public void Test() { string file0 = "1.txt"; string file1 = "2.txt"; using (var memoryStream = new MemoryStream()) { using (ZipArchive zipArchive = ZipArchive.Create()) { zipArchive.AddEntry(file0, new MemoryStream(Encoding.UTF8.GetBytes("test1"))); zipArchive.SaveTo(memoryStream); } using (ZipArchive zipArchive = ZipArchive.Open(memoryStream)) { var zipEntry = GetEntry(zipArchive, file0); Assert.NotNull(zipEntry); zipArchive.AddEntry(file1, new MemoryStream(Encoding.UTF8.GetBytes("test2"))); zipEntry = GetEntry(zipArchive, file1); Assert.NotNull(zipEntry); } using (ZipArchive zipArchive = ZipArchive.Open(memoryStream)) { var zipEntry = GetEntry(zipArchive, file0); Assert.NotNull(zipEntry); zipEntry = GetEntry(zipArchive, file1); Assert.IsNull(zipEntry); } } }
private static FileInfo GeneratePackage( string path, string packageId, string packageVersion, string[] zipEntries, string[] zipContents, bool frameworkAssemblies, SemanticVersion minClientVersion, bool dependencies) { if (zipEntries == null || zipContents == null || zipEntries.Length != zipContents.Length) { throw new InvalidOperationException("TEST Exception: zipEntries and zipContents should be non-null and" + "zipEntries.Length should be equal to zipContents.Length"); } var fileInfo = GetFileInfo(path, packageId, packageVersion); using (var zip = new ZipArchive(File.Create(fileInfo.FullName), ZipArchiveMode.Create)) { for (int i = 0; i < zipEntries.Length; i++) { zip.AddEntry(zipEntries[i], zipContents[i], Encoding.UTF8); } SetSimpleNuspec(zip, packageId, packageVersion, frameworkAssemblies, minClientVersion, dependencies); } return(fileInfo); }
private void AddGdbservers(ZipArchive apk, ArchiveFileList files, string supportedAbis, AndroidDebugServer debugServer) { if (string.IsNullOrEmpty(AndroidNdkDirectory)) { return; } foreach (var sabi in supportedAbis.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)) { var arch = GdbPaths.GetArchFromAbi(sabi); var abi = GdbPaths.GetAbiFromArch(arch); if (abi == null) { continue; } var debugServerFile = GdbPaths.GetDebugServerFileName(debugServer); if (files.Any(f => string.Equals(Path.GetFileName(f.Item1), debugServerFile, StringComparison.Ordinal) && string.Equals(f.Item2, "lib/" + sabi, StringComparison.Ordinal))) { continue; } var entryName = string.Format("lib/{0}/{1}", sabi, debugServerFile); var debugServerPath = GdbPaths.GetDebugServerPath(debugServer, arch, AndroidNdkDirectory, SdkBinDirectory); if (!File.Exists(debugServerPath)) { continue; } Log.LogDebugMessage("Adding {0} debug server '{1}' to the APK as '{2}'", sabi, debugServerPath, entryName); apk.AddEntry(entryName, File.OpenRead(debugServerPath)); } }
public static ZipArchiveEntry CreateEntryFromFile(this ZipArchive archive, string file, string path) { using (Stream stream = File.OpenRead(file)) { return(archive.AddEntry(path, stream)); } }
public static ZipArchiveEntry CreateEntry(this ZipArchive archive, string path) { using (Stream stream = new MemoryStream()) { return(archive.AddEntry(path, stream)); } }
public void PackageFolderReader_NuspecCountNone() { // Arrange using (var workingDir = TestFileSystemUtility.CreateRandomTestFolder()) using (var stream = new MemoryStream()) { using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true)) { zip.AddEntry("lib/net45/a.dll", new byte[0]); } stream.Seek(0, SeekOrigin.Begin); var zipFile = new ZipArchive(stream, ZipArchiveMode.Read); zipFile.ExtractAll(workingDir); var reader = new PackageFolderReader(workingDir); var threwPackagingException = false; // Act try { var nuspec = reader.GetNuspec(); } catch (PackagingException) { threwPackagingException = true; } // Assert Assert.True(threwPackagingException); } }
private static void CreateRuntimesPackage(string repositoryDir, string packageId, string runtimeJson) { var file = Path.Combine(repositoryDir, packageId + ".1.0.0.nupkg"); using (var zip = new ZipArchive(File.Create(file), ZipArchiveMode.Create)) { zip.AddEntry("runtime.json", runtimeJson, Encoding.UTF8); zip.AddEntry(packageId + ".nuspec", @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2013/01/nuspec.xsd""> <metadata> <id>" + packageId + @"</id> <version>1.0.0</version> <title /> </metadata> </package>", Encoding.UTF8); } }
public static FileInfo GetLegacyTestPackageMinClient(string minClientVersion) { var file = Path.GetTempFileName() + ".nupkg"; var result = new FileInfo(file); using (var zip = new ZipArchive(File.Create(result.FullName), ZipArchiveMode.Create)) { zip.AddEntry("lib/test.dll", new byte[] { 0 }); zip.AddEntry("lib/net40/test40.dll", new byte[] { 0 }); zip.AddEntry("lib/net40/test40b.dll", new byte[] { 0 }); zip.AddEntry("lib/net45/test45.dll", new byte[] { 0 }); var nuspec = string.Format( CultureInfo.InvariantCulture, @"<?xml version=""1.0"" encoding=""utf-8""?> <package xmlns=""http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd""> <metadata minClientVersion=""{0}""> <id>packageA</id> <version>2.0.3</version> <authors>Author1, author2</authors> <description>Sample description</description> <language>en-US</language> <projectUrl>http://www.nuget.org/</projectUrl> <licenseUrl>http://www.nuget.org/license</licenseUrl> <dependencies> <group> <dependency id=""RouteMagic"" version=""1.1.0"" /> </group> <group targetFramework=""net40""> <dependency id=""jQuery"" /> <dependency id=""WebActivator"" /> </group> <group targetFramework=""sl30""> </group> </dependencies> </metadata> </package>", minClientVersion); zip.AddEntry("packageA.nuspec", nuspec, Encoding.UTF8); return(result); } }
public async Task RevertFileAsync_RevertsFile() { var projectFileContent = string.Format( CultureInfo.InvariantCulture, "<a>{0} <x>{0} <b>d</b>{0} <y>{0} <z>d</z>{0} </y>{0} </x>{0}</a>", Environment.NewLine); using (var test = new XdtTransformerTest("<a xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\"><x><y xdt:Transform=\"Remove\"><z>$c$</z></y></x></a>")) { var zipArchiveFilePath = Path.Combine(test.TestDirectory.Path, "archive.zip"); var zipFileInfo = new InternalZipFileInfo(zipArchiveFilePath, "install.xdt"); using (var zipFileStream = File.OpenWrite(zipArchiveFilePath)) using (var zipArchive = new ZipArchive(zipFileStream, ZipArchiveMode.Create)) { var content = Encoding.UTF8.GetBytes("<a xmlns:xdt=\"http://schemas.microsoft.com/XML-Document-Transform\"><x><b xdt:Transform=\"Insert\">$c$</b></x></a>"); zipArchive.AddEntry(zipFileInfo.ZipArchiveEntryFullName, content); } File.WriteAllText(test.TargetFile.FullName, projectFileContent); test.ProjectSystem.SetupGet(x => x.ProjectFullPath) .Returns(test.TargetFile.DirectoryName); test.ProjectSystem.SetupGet(x => x.ProjectName) .Returns("ProjectName"); test.ProjectSystem.Setup(x => x.GetPropertyValue(It.IsNotNull <string>())) .Returns("d"); test.ProjectSystem.Setup(x => x.AddFile(It.IsNotNull <string>(), It.IsNotNull <Stream>())) .Callback <string, Stream>( (targetFilePath, stream) => { Assert.Equal(test.TargetFile.Name, targetFilePath); stream.Seek(offset: 0, origin: SeekOrigin.Begin); using (var reader = new StreamReader(stream)) { var actualResult = reader.ReadToEnd(); var expectedResult = string.Format( CultureInfo.InvariantCulture, "<a>{0} <x>{0} <b>d</b>{0} </x>{0}</a>", Environment.NewLine); Assert.Equal(expectedResult, actualResult); } }); await test.Transformer.RevertFileAsync( test.StreamTaskFactory, test.TargetFile.Name, new[] { zipFileInfo }, test.ProjectSystem.Object, CancellationToken.None); } }
void UpdateEntry(ZipArchive archive, string file, string content) { var existing = archive.FirstOrDefault(e => e.FullName == file); if (existing != null) { archive.DeleteEntry(existing); } archive.AddEntry(file, content, Encoding.UTF8); }
private static void WriteFilesRecursiveToZip(ZipArchive archive, IStorage storage, string basePath) { string searchPattern = basePath; string[] fileNames = storage.GetFileNames(searchPattern); foreach (string fileName in fileNames) { Stream fileStream = storage.OpenFile(basePath + "/" + fileName, StorageFileMode.Open, StorageFileAccess.Read); archive.AddEntry(fileName, fileStream); } string[] directrryNames = storage.GetDirectoryNames(searchPattern); foreach (string directoryName in directrryNames) { WriteFilesRecursiveToZip(archive, storage, basePath + "/" + directoryName); } }
/// <summary> /// Creates a ZipEntry of the passed node and its childs to the passed zip file. /// </summary> /// <param name="zip">The zip file to add the new zip entry to.</param> /// <param name="node">The node to create a zip entry for.</param> /// <param name="processedNodeCount">Count of the processed nodes (for recursive calls only).</param> /// <returns>Count of the processed nodes.</returns> private static int CreateZipEntry(ZipArchive zip, ModNode node, int processedNodeCount = 0) { string absPath = KSPPathHelper.GetAbsolutePath(node.Destination); string gameDataPath = KSPPathHelper.GetPath(KSPPaths.GameData); string path = absPath.Replace(gameDataPath + Path.DirectorySeparatorChar, string.Empty); if (node.IsFile && node.IsInstalled) zip.AddEntry(path, absPath); foreach (ModNode child in node.Nodes) processedNodeCount = CreateZipEntry(zip, child, processedNodeCount); return processedNodeCount; }
/// <summary> /// Adds the sub directory to the Archive. /// </summary> /// <param name="parentDir">Parent directory to scan for sub directories and files.</param> /// <param name="archive">The Archive to add the directories and files to.</param> private static void AddSubDirs(string parentDir, ZipArchive archive) { foreach (string subDir in Directory.GetDirectories(parentDir)) { foreach (string file in Directory.GetFiles(subDir)) { string directoryName = Path.GetDirectoryName(file); if (directoryName != null) { string temp = Path.Combine(directoryName.Replace(KSPPathHelper.GetPath(KSPPaths.KSPRoot) + Path.DirectorySeparatorChar, string.Empty), Path.GetFileName(file)); archive.AddEntry(temp, file); } } AddSubDirs(subDir, archive); } }