public void Should_Throw_If_File_Paths_Are_Null() { // Given var fileSystem = Substitute.For <IFileSystem>(); var environment = Substitute.For <ICakeEnvironment>(); var log = Substitute.For <ICakeLog>(); var zipper = new Zipper(fileSystem, environment, log); // When var result = Record.Exception(() => zipper.Zip("/Root", "/file.txt", null)); // Then Assert.IsArgumentNullException(result, "filePaths"); }
public void ZipUnzipToFromFile() { ZipContent original = new ZipContent(); original.A = "A"; original.B = 6; string pathToZip = AppDomain.CurrentDomain.BaseDirectory + "ZipUnzipToFromFile.zip"; Zipper.Zip(original, pathToZip); ZipContent unziped = Zipper.Unzip <ZipContent>(pathToZip); Assert.AreEqual(original, unziped); }
public void Should_Throw_If_Root_Path_Is_Null() { // Given var fileSystem = Substitute.For <IFileSystem>(); var environment = Substitute.For <ICakeEnvironment>(); var log = Substitute.For <ICakeLog>(); var zipper = new Zipper(fileSystem, environment, log); // When var result = Record.Exception(() => zipper.Zip(null, "/file.zip", new FilePath[] { "/Root/file.txt" })); // Then Assert.IsArgumentNullException(result, "rootPath"); }
public void Should_Throw_If_Output_Path_Is_Null() { // Given var fileSystem = Substitute.For <IFileSystem>(); var environment = Substitute.For <ICakeEnvironment>(); var log = Substitute.For <ICakeLog>(); var zipper = new Zipper(fileSystem, environment, log); // When var result = Record.Exception(() => zipper.Zip("/Root", null, new FilePath[] { "/Root/file.txt" })); // Then Assert.IsType <ArgumentNullException>(result); Assert.Equal("outputPath", ((ArgumentNullException)result).ParamName); }
public void ZippedCanBeUnzipedTest() { string testValue = ""; for (int i = 0; i < 100; i++) { testValue += DateTime.Now.Ticks.ToString(); } var zipped = Zipper.Zip(testValue); var unzipped = Zipper.Unzip(zipped); Assert.IsTrue(testValue == unzipped); }
public void Should_Zip_Provided_Files() { // Given var environment = FakeEnvironment.CreateUnixEnvironment(); var fileSystem = new FakeFileSystem(environment); fileSystem.CreateFile("/Root/file.txt").SetContent("HelloWorld"); var log = Substitute.For <ICakeLog>(); var zipper = new Zipper(fileSystem, environment, log); // When zipper.Zip("/Root", "/file.zip", new FilePath[] { "/Root/file.txt" }); // Then Assert.True(fileSystem.GetFile("/file.zip").Exists); }
public List <Tuple <int, int> > Call <Name>(Named <List <int>, Name> named) { var len1 = Zipper.Len(this.xs); var len2 = Zipper.Len(named); var proof1 = Zipper.LengthIsTwo(len1); var proof2 = Zipper.LengthIsTwo(len2); if (proof1 != null && proof2 != null) { return(Zipper.Zip( new SuchThat <Named <List <int>, Xs>, Equals <Length <Xs>, Succ <Succ <Zero> > > >(this.xs, proof1), new SuchThat <Named <List <int>, Name>, Equals <Length <Name>, Succ <Succ <Zero> > > >(named, proof2))); } throw new Exception("Lists were not of length 2."); }
public void Should_Throw_If_File_Is_Not_Relative_To_Root() { // Given var environment = FakeEnvironment.CreateUnixEnvironment(); var fileSystem = new FakeFileSystem(environment); fileSystem.CreateFile("/NotRoot/file.txt"); var log = Substitute.For <ICakeLog>(); var zipper = new Zipper(fileSystem, environment, log); // When var result = Record.Exception(() => zipper.Zip("/Root", "/file.zip", new FilePath[] { "/NotRoot/file.txt" })); // Then Assert.IsType <CakeException>(result); Assert.Equal("File '/NotRoot/file.txt' is not relative to root path '/Root'.", result.Message); }
private Stream GetZipStream() { List <ZipItem> zipItems = new List <ZipItem>(); try{ var fileInfo = this.HostEnvironment.ContentRootFileProvider.GetFileInfo("resources/files_to_zip/ImageProcessing.exe"); zipItems.Add(new ZipItem("ImageProcessing.exe", System.IO.File.OpenRead(fileInfo.PhysicalPath))); fileInfo = this.HostEnvironment.ContentRootFileProvider.GetFileInfo("resources/files_to_zip/ImageProcessing.exe.config"); zipItems.Add(new ZipItem("ImageProcessing.exe", System.IO.File.OpenRead(fileInfo.PhysicalPath))); System.Console.WriteLine("salut"); return(Zipper.Zip(zipItems)); } catch (System.Exception ex) { System.Console.WriteLine(ex.Message); } return(Zipper.Zip(zipItems)); }
public void ZipTest() { using (CreateContext()) { var signed = CreateSignedLedger(); byte[] bytes; using (var stream = new ByteStream()) { stream.Write(signed); bytes = stream.GetBytes(); } var unzipped = Zipper.Unzip(Zipper.Zip(bytes)); Debug.Assert(bytes.IsEqual(unzipped)); } }
public void GivenADirectory_AndWeExplicityWantToCreateUnixArchive_ThenAllPathsWithinZipAreUnix() { var directoryToZip = TestHelper.GetZipModuleSourceDirectory(); using (var zipFile = new TempFile($"test-{Guid.NewGuid()}.zip")) { Zipper.Zip( new CrossPlatformZipSettings { ZipFile = zipFile, Artifacts = directoryToZip, CompressionLevel = 9, TargetPlatform = ZipPlatform.Unix }); this.GetAllEntries(zipFile).Any(e => e.Contains("\\")).Should().BeFalse(); } }
public void GivenADirectory_ThenAllFilesAndDirectoriesWithinAreAddedToZip() { var directoryToZip = TestHelper.GetZipModuleSourceDirectory(); var expectedEntryCount = Directory.EnumerateFileSystemEntries(directoryToZip, "*", SearchOption.AllDirectories).Count(); using (var zipFile = new TempFile($"test-{Guid.NewGuid()}.zip")) { Zipper.Zip( new CrossPlatformZipSettings { ZipFile = zipFile, Artifacts = directoryToZip, CompressionLevel = 9, }); this.GetEntryCount(zipFile).Should().Be(expectedEntryCount); } }
public void Zipped_File_Should_Contain_Correct_Content() { // Given var environment = FakeEnvironment.CreateUnixEnvironment(); var fileSystem = new FakeFileSystem(environment); fileSystem.CreateFile("/Root/Stuff/file.txt").SetContent("HelloWorld"); var log = Substitute.For <ICakeLog>(); var zipper = new Zipper(fileSystem, environment, log); zipper.Zip("/Root", "/file.zip", new FilePath[] { "/Root/Stuff/file.txt" }); // When var archive = new ZipArchive(fileSystem.GetFile("/file.zip").Open(FileMode.Open, FileAccess.Read, FileShare.Read)); var entry = archive.GetEntry("Stuff/file.txt"); // Then Assert.NotNull(entry); Assert.True(entry.Length == 10); }
public static string CompressFile(string BackupPath) { string zipPath = BackupPath.Remove(BackupPath.Length - 4) + ".zip"; try { Zipper zipLib = new Zipper { ZipFile = zipPath }; zipLib.ItemList.Add(BackupPath); zipLib.Zip(); } catch (Exception Ex) { LogEvent.Error(String.Format("Failed to Compress the Database:\r\n {0} \r\nContinuing With the Backup", Ex)); zipPath = BackupPath; } return(zipPath); }
public void Zip_files_are_at_destination() { var randomDir = CreateRandomPath(); var fileNames = CreateTestFiles(randomDir.FullName); var destination = CreateRandomPath(); var config = new Zipper.ZipConfiguration() { Source = randomDir, Destination = new FileInfo(Path.Combine(destination.FullName, "zipfile.zip")), Extension = ".pdf", }; var zipFile = Zipper.Zip(config); Assert.True(zipFile.File.Exists); Assert.Single(zipFile.ZipItems); DeleteTestDir(config.Source); DeleteTestDir(config.Destination.Directory); }
public void Zip_invalid_configuration() { var config = new Zipper.ZipConfiguration(); Exception ex = Assert.Throws <ArgumentNullException>(() => Zipper.Zip(config)); Assert.StartsWith("Extension was not specified", ex.Message); config.Extension = ".txt"; ex = Assert.Throws <ArgumentNullException>(() => Zipper.Zip(config)); Assert.StartsWith("Source was not specified", ex.Message); config.Source = new DirectoryInfo("/"); ex = Assert.Throws <ArgumentNullException>(() => Zipper.Zip(config)); Assert.StartsWith("Destination was not specified", ex.Message); config.Destination = new FileInfo("/"); config.SkipAmount = -9000; ex = Assert.Throws <ArgumentOutOfRangeException>(() => Zipper.Zip(config)); Assert.StartsWith("SkipAmount must be 0 or greater", ex.Message); }
public void GivenASingleFile_AndUsingZipMethod_ThenItIsAddedAtTheRootOfTheCentralDirectory() { var fileToZip = TestHelper.GetZipModuleSourceFile(); var expectedEntry = Path.GetFileName(fileToZip); using (var zipFile = new TempFile($"test-{Guid.NewGuid()}.zip")) { Zipper.Zip( new CrossPlatformZipSettings { ZipFile = zipFile, Artifacts = fileToZip, CompressionLevel = 9, TargetPlatform = ZipPlatform.Unix }); this.GetEntryCount(zipFile).Should().Be(1); this.GetFirstEntryPath(zipFile).Should().Be(expectedEntry); } }
public void Zip_skip_all_zipfile_should_be_empty() { var randomDir = CreateRandomPath(); var fileNames = CreateTestFiles(randomDir.FullName); var destination = CreateRandomPath(); var config = new Zipper.ZipConfiguration() { Source = randomDir, Destination = new FileInfo(Path.Combine(destination.FullName, "zipfile.zip")), Extension = ".txt", SkipAmount = 3 }; var zipFile = Zipper.Zip(config); Assert.True(zipFile.File.Exists); Assert.Empty(zipFile.ZipItems); DeleteTestDir(config.Source); DeleteTestDir(config.Destination.Directory); }
static string TamperSomehow(string token) { var zipper = new Zipper(); var zippedBytes = Convert.FromBase64String(token); var str = Encoding.ASCII.GetString(zipper.Unzip(zippedBytes)); Console.WriteLine("Unzipped contents:"); Console.WriteLine(str); Console.WriteLine(); var parts = str.Split(new [] { "|" }, StringSplitOptions.RemoveEmptyEntries); var jsonText = Encoding.UTF8.GetString(Convert.FromBase64String(parts[0])); Console.WriteLine("First part as JSON:"); Console.WriteLine(jsonText); Console.WriteLine(); var tamperedJsonText = jsonText.Replace(@"""joe""", @"""moe"""); Console.WriteLine("Tampered JSON:"); Console.WriteLine(tamperedJsonText); Console.WriteLine(); var newStr = Convert.ToBase64String(Encoding.UTF8.GetBytes(tamperedJsonText)) + "|" + parts[1]; Console.WriteLine("New unzipped contents:"); Console.WriteLine(newStr); Console.WriteLine(); var tamperedZippedBytes = zipper.Zip(Encoding.ASCII.GetBytes(newStr)); return(Convert.ToBase64String(tamperedZippedBytes)); }
/// <summary> /// Package a directory to a zip. /// </summary> /// <param name="artifact">Path to artifact directory.</param> /// <param name="workingDirectory">The working directory.</param> /// <param name="s3">Interface to S3</param> /// <param name="logger">Interface to logger.</param> /// <returns>A <see cref="ResourceUploadSettings"/></returns> public static async Task <ResourceUploadSettings> PackageDirectory( DirectoryInfo artifact, string workingDirectory, IPSS3Util s3, ILogger logger) { // Property value points to a directory, which must always be zipped. var fileToUpload = Path.Combine(workingDirectory, $"{artifact.Name}.zip"); // Compute hash before zipping as zip hashes not idempotent due to temporally changing attributes in central directory var resourceToUpload = new ResourceUploadSettings { File = new FileInfo(fileToUpload), Hash = artifact.MD5(), HashMatch = true, KeyPrefix = s3.KeyPrefix }; if (await s3.ObjectChangedAsync(resourceToUpload)) { logger.LogVerbose($"Zipping directory '{artifact.FullName}' to {Path.GetFileName(fileToUpload)}"); Zipper.Zip( new CrossPlatformZipSettings { Artifacts = artifact.FullName, CompressionLevel = 9, LogMessage = m => logger.LogVerbose(m), LogError = e => logger.LogError(e), ZipFile = fileToUpload, TargetPlatform = ZipPlatform.Unix }); resourceToUpload.HashMatch = false; } return(resourceToUpload); }
/// <summary> /// Very simple interface to create a new zip file. /// </summary> /// <param name="zipFile">Path to zip file to create</param> /// <param name="platform">Target platform (default Unix if running on Windows, else Windows).</param> /// <param name="level">Compression level (0-9, 0 = store, 9 = best, default 5)</param> /// <param name="argument">Path to file or folder to zip</param> /// <returns>Exit status</returns> public static int Main(string zipFile, ZipPlatform?platform, int?level, FileSystemInfo argument) { try { var compession = level ?? 5; var defaultPlatform = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? ZipPlatform.Unix : ZipPlatform.Windows; Zipper.Zip( new CrossPlatformZipSettings { CompressionLevel = compession, Artifacts = argument.FullName, ZipFile = zipFile, TargetPlatform = platform ?? defaultPlatform }); } catch (Exception e) { Console.WriteLine(e); return(1); } return(0); }
public void Should_Zip_Provided_Directory() { // Given var environment = FakeEnvironment.CreateUnixEnvironment(); var fileSystem = new FakeFileSystem(environment); var globber = new Globber(fileSystem, environment); var context = new CakeContextFixture { Environment = environment, FileSystem = fileSystem, Globber = globber }.CreateContext(); fileSystem.CreateDirectory("/Dir0"); // empty directory fileSystem.CreateFile("/File1.txt").SetContent("1"); fileSystem.CreateFile("/Dir1/File2.txt").SetContent("22"); fileSystem.CreateFile("/Dir2/File3.txt").SetContent("333"); fileSystem.CreateFile("/Dir2/Dir3/File4.txt").SetContent("4444"); fileSystem.CreateFile("/Dir2/Dir3/File5.txt").SetContent("55555"); var log = Substitute.For <ICakeLog>(); var zipper = new Zipper(fileSystem, environment, log); // When zipper.Zip("/", "/Root.zip", context.GetPaths("/**/*")); // Then var archive = new ZipArchive(fileSystem.GetFile("/Root.zip").Open(FileMode.Open, FileAccess.Read, FileShare.Read)); Assert.True(archive.Entries.Count == 9); Assert.True(archive.GetEntry("Dir0/")?.Length == 0); // directory entries; includes empty directories Assert.True(archive.GetEntry("Dir1/")?.Length == 0); Assert.True(archive.GetEntry("Dir2/")?.Length == 0); Assert.True(archive.GetEntry("Dir2/Dir3/")?.Length == 0); Assert.True(archive.GetEntry("File1.txt")?.Length == 1); // file entries Assert.True(archive.GetEntry("Dir1/File2.txt")?.Length == 2); Assert.True(archive.GetEntry("Dir2/File3.txt")?.Length == 3); Assert.True(archive.GetEntry("Dir2/Dir3/File4.txt")?.Length == 4); Assert.True(archive.GetEntry("Dir2/Dir3/File5.txt")?.Length == 5); }
private void RectangleReport_MouseDown(object sender, MouseButtonEventArgs e) { IndexALL indexALL = JobDB.FindIndex(((Rectangle)sender).Tag.ToString()); if (indexALL.JobIndex != -1) { switch (indexALL.Type) { case EnumType.HashTag: { var job = db.job.HashTag[indexALL.JobIndex]; if (job.HashTag.Count == 0) { MessageBOX.Show("Нету данных, попробуйте позже.."); } else { Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog(); sfd.Title = "Укажите путь, куда сохранить архив"; sfd.FileName = "archive"; sfd.DefaultExt = ".zip"; sfd.Filter = "archive|*.zip"; //Сохраняем архив if ((bool)sfd.ShowDialog() == true) { MessageBOX.Show("Данные успешно сохранены"); Directory.CreateDirectory("tmp"); //Сохраняем теги File.WriteAllLines(@"tmp\tag.txt", job.HashTag.ToArray()); //Сохраняем список групп foreach (var g in job.Group.ToArray()) { File.AppendAllText(@"tmp\group.txt", ("https://vk.com/public" + g.gid.ToString().Replace("-", "") + Environment.NewLine)); } //Пакуем в архив Zipper zip = new Zipper(); zip.ZipFile = sfd.FileName; zip.ItemList.Add(@"tmp\" + "*.*"); zip.Recurse = true; zip.Comment = "VKHashTag - feedron.ru"; zip.Zip(); //Удаляем темп Directory.Delete("tmp", true); zip = null; } sfd = null; } job = null; break; } } } sender = null; e = null; indexALL = null; }
private ZipperItem <T>[] InitialiseResults() { var actualItems = Zipper.Zip(GetASegments, GetBSegments).ToArray(); return(actualItems); }
public static void SaveModel(CalculationModel model) { DataTable dt = new DataTable("CalPrice"); dt.Columns.Add(new DataColumn("PriceID", typeof(long))); dt.Columns.Add(new DataColumn("JsonData1", typeof(string))); dt.Columns.Add(new DataColumn("JsonData2", typeof(string))); dt.Columns.Add(new DataColumn("JsonData3", typeof(string))); dt.Columns.Add(new DataColumn("JsonData4", typeof(string))); dt.Columns.Add(new DataColumn("JsonData5", typeof(string))); dt.Columns.Add(new DataColumn("JsonData6", typeof(string))); dt.Columns.Add(new DataColumn("JsonData7", typeof(string))); dt.Columns.Add(new DataColumn("JsonData8", typeof(string))); dt.Columns.Add(new DataColumn("JsonData9", typeof(string))); dt.Columns.Add(new DataColumn("JsonData10", typeof(string))); dt.Columns.Add(new DataColumn("CreatedDate", typeof(DateTime))); dt.Columns.Add(new DataColumn("ModifiedDate", typeof(DateTime))); //create new calculation row DataRow dr = dt.NewRow(); dt.Rows.Add(dr); //set insert columns List <DataColumn> oIgnoreSave = new List <DataColumn>(); oIgnoreSave.Add(dt.Columns["PriceID"]); if (model.ID == 0) { //model.ID = CalPriceGetLatestID() + 1; dr["CreatedDate"] = DateTime.Now; oIgnoreSave.Add(dt.Columns["ModifiedDate"]); //insert new row first to get id model.ID = InsertRowReturnIdentity(dt.Rows[0], dt.Columns["PriceID"], oIgnoreSave.ToArray()); } else { dr["ModifiedDate"] = DateTime.Now; oIgnoreSave.Add(dt.Columns["CreatedDate"]); } dr["PriceID"] = model.ID; string sJson = Utility.ObjectToJson(model); string sCompress = Zipper.Zip(sJson); //extract encode json to JsonData1 to JsonData10 int i = 1; while (!String.IsNullOrWhiteSpace(sCompress)) { if (sCompress.Length >= 3000) { dr[String.Concat("JsonData", i)] = sCompress.Substring(0, 4000); sCompress = sCompress.Remove(0, 3000); } else { dr[String.Concat("JsonData", i)] = sCompress.Substring(0); sCompress = sCompress.Remove(0, sCompress.Length); } i += 1; } //update jsondata by particular row SaveTable(dt, dt.Columns["PriceID"], oIgnoreSave.ToArray()); //save proffix if needed SaveProffix(model); }