public static ToffeeInternalPacketReadResult Read(ToffeeParticipant receiver, byte[] packet) { try { // Iterate through the packet ToffeePacketIterator iterator = new ToffeePacketIterator(receiver, packet); // Get the header, data, and CRC InternalPacketHeader header = iterator.ReadStruct <InternalPacketHeader>(); byte[] packetData = iterator.ReadBytes(header.Length); uint sentCrc = iterator.ReadUInt32(); // Is the CRC correct? uint calculatedCrc = CRC.CalculateCRC32(packetData); if (sentCrc != calculatedCrc) { return(new ToffeeInternalPacketReadResult(false, new InternalPacketHeader(), null)); } // Is this packet compressed? if (header.Compressed) { packetData = CompressionService.Decompress(packetData); } // Return the read result return(new ToffeeInternalPacketReadResult(true, header, packetData)); } catch { return(new ToffeeInternalPacketReadResult(false, new InternalPacketHeader(), null)); } }
static void Main(string[] args) { DecompressFileApp app = new DecompressFileApp(); Logger logger = app.Logger; ExitCode exitCode = ExitCode.None; try { logger.Info("Application started."); CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); Options options = new Options(); Parser.Default.ParseArgumentsStrict(args, options, CommandLineOptions.ArgumentParsingFailed); using (ICompressionService zipFileService = new CompressionService()) { zipFileService.Decompress(options.InputFileName, options.OutputPath); exitCode = ExitCode.Success; } } catch (Exception ex) { exitCode = new ExceptionHandlingService(ex).GetExitCode(); } finally { logger.Info(CultureInfo.InvariantCulture, "Application exited with code: {0}", (int)exitCode); Environment.Exit((int)exitCode); } }
public void CompressAndDecompressToSameResultTest(byte[] data) { var compressionService = new CompressionService(); var compressedData = compressionService.Compress(data); var decompressedData = compressionService.Decompress(compressedData); Assert.True(data.SequenceEqual(decompressedData)); }
/// <summary> /// Build a final compressed, encrypted, and encoded packet. /// </summary> /// <returns>The packet data.</returns> public byte[] BuildPacket() { // Get the packet data byte[] data = Data.ToArray(); // Compression bool compressed = false; if (DataLength > 100) { byte[] compressedData = CompressionService.Compress(data); if (compressedData.Length < data.Length) { data = compressedData; compressed = true; } } ushort dataLength = (ushort)data.Length; // Create the packet header ClientPacketHeader header = new ClientPacketHeader { OpCode = OpCode, Compressed = compressed, Length = dataLength, Timestamp = TimeUtil.GetUnixTimestamp() }; LastHeader = header; // Append the header and CRC to the compressed data ToffeePacket packet = new ToffeePacket(Sender); packet.Write(header); packet.Write(data, true); packet.Write(CRC.CalculateCRC32(data)); data = packet.GetBytes(); // Encryption bool encrypted = ((Encrypted && Sender.UseEncryption) || (Sender.ForceEncryption)); if ((encrypted) && (!Sender.UseEncryption)) { Sender.Disconnect(); return(new byte[0]); } if (encrypted) { data = Sender.Encryption.Encrypt(data); } // Create the final packet packet = new ToffeePacket(Sender); packet.Write(encrypted); packet.Write(data, true); return(packet.GetBytes()); }
public void Complex_Test() { var zipFileName = Path.GetTempFileName(); var filesData = new Dictionary <string, string>() { { "file1.txt", "Lorem ipsum dolor sit amet" }, { "file2.txt", "Sed accumsan sodales nulla, a mattis nunc euismod sit amet. Proin varius nunc lectus, quis maximus ante mattis id" } }; var filesToCompress = new Dictionary <string, string>(); foreach (var fd in filesData) { var path = Path.GetTempFileName(); File.WriteAllText(path, fd.Value); filesToCompress.Add(fd.Key, path); CompressionService.IsZipFile(path).ShouldBe(false, $"{nameof(CompressionService.IsZipFile)} works wrong - recognized text file as a zip"); } using (var zipStream = new FileStream(zipFileName, FileMode.Create)) { CompressionService.CompressFilesToStream(filesToCompress, zipStream); } File.Exists(zipFileName).ShouldBe(true, "Failed to create zip file"); CompressionService.IsZipFile(zipFileName).ShouldBe(true, "Created archive is not recognized as zip"); foreach (var fileToCompress in filesToCompress) { File.Delete(fileToCompress.Value); } var extractPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); var decompressedFiles = CompressionService.GetDecompressedFiles(zipFileName, extractPath); decompressedFiles.Count.ShouldBe(filesData.Count, "Wrong number of decompressed files"); foreach (var fd in filesData) { var decompressedFile = decompressedFiles.FirstOrDefault(f => Path.GetFileName(f) == fd.Key); decompressedFile.ShouldNotBeNull($"File '{fd.Key}' not found"); var text = File.ReadAllText(decompressedFile); text.ShouldBe(fd.Value, "Decompressed value doesn't match the initial one"); } foreach (var file in decompressedFiles) { File.Delete(file); } File.Delete(zipFileName); Directory.Delete(extractPath); }
public void CompressedDataSmallerThenOriginalTest(byte[] data) { var compressionService = new CompressionService(); var compressedData = compressionService.Compress(data); var originalDataSize = data.Length * sizeof(byte); var compressedDataSize = compressedData.Length * sizeof(byte); Assert.LessOrEqual(compressedDataSize, compressedDataSize, "Compressed data size ({0}) is greater then original ({1}).", compressedDataSize, originalDataSize); }
public async Task <FileStreamResult> DownloadZipAsync([FromQuery] DownloadZipInput input) { var files = input.AllCategories ? await _fileService.GetAttachmentsAsync(input.OwnerId, input.OwnerType) : await _fileService.GetAttachmentsOfCategoryAsync(input.OwnerId, input.OwnerType, input.FilesCategory); // todo: move zip support to the FileService, current implementation doesn't support Azure var list = _fileService.MakeUniqueFileNames(files); var compressedStream = await CompressionService.CompressFiles(list); // note: compressedStream will be disposed automatically in the FileStreamResult return(File(compressedStream, "multipart/x-zip", "files.zip")); }
public static ToffeeClientPacketReadResult Read(ToffeeParticipant receiver, byte[] packet) { try { // Is this packet encrypted? bool encrypted = packet[0] == 0x01; if (encrypted) { // Is this client setup to use encryption? if (receiver.UseEncryption) { packet = receiver.Encryption.Decrypt(packet.Skip(1).ToArray()); } } else { packet = packet.Skip(1).ToArray(); } // Iterate through the packet ToffeePacketIterator iterator = new ToffeePacketIterator(receiver, packet); // Get the header, data, and CRC ClientPacketHeader header = iterator.ReadStruct <ClientPacketHeader>(); byte[] packetData = iterator.ReadBytes(header.Length); uint sentCrc = iterator.ReadUInt32(); // Is the CRC correct? uint calculatedCrc = CRC.CalculateCRC32(packetData); if (sentCrc != calculatedCrc) { return(new ToffeeClientPacketReadResult(false, encrypted, new ClientPacketHeader(), null)); } // Is this packet compressed? if (header.Compressed) { packetData = CompressionService.Decompress(packetData); } // Return the read result return(new ToffeeClientPacketReadResult(true, encrypted, header, packetData)); } catch { return(new ToffeeClientPacketReadResult(false, false, new ClientPacketHeader(), null)); } }
public RomService(ErrorService errorService, GraphicsService graphicsService, PalettesService palettesService, TileService tileService, LevelService levelService, WorldService worldService, TextService textService) { _errorService = errorService; _levelIndexTable = new Dictionary <Guid, byte>(); _worldIndexTable = new Dictionary <Guid, byte>(); _paletteIndexTable = new Dictionary <Guid, byte>(); _levelAddressTable = new Dictionary <byte, int>(); _levelTypeTable = new Dictionary <byte, int>(); _graphicsService = graphicsService; _palettesService = palettesService; _tileService = tileService; _worldService = worldService; _textService = textService; _levelService = levelService; _compressionService = new CompressionService(); }
public void CompressionService_Compression_CompressValidSourceDirectory() { // arrange DateTime currentTime = DateTime.Now; string sourceDirectory = @"C:\_LogFiles\TF1"; string targetDirectory = @"C:\_ArchiveFiles\" + currentTime.ToString("ddMMyy"); // Create the directory if it doesn't exist if (!Directory.Exists(sourceDirectory)) { Directory.CreateDirectory(sourceDirectory); } string sevenZipPath = @"C:\Program Files\7-Zip\7z.exe"; // act bool result = CompressionService.Compress(sevenZipPath, sourceDirectory, targetDirectory); // assert Assert.IsTrue(result); }
public void CompressionService_Compress_CompressInvalidSourceDirectory() { // arrange DateTime currentTime = DateTime.Now; string sourceDirectory = @"C:\_LogFiles\adfadfasdf"; string targetDirectory = @"C:\_ArchiveFiles\" + currentTime.ToString("ddMMyy"); string sevenZipPath = @"C:\Program Files\7-Zip\7z.exe"; bool result; // act try { result = CompressionService.Compress(sevenZipPath, sourceDirectory, targetDirectory); } catch { result = false; } // assert Assert.IsFalse(result); }
/// <summary> /// Build a final compressed, encrypted, and encoded packet. /// </summary> /// <returns>The packet data.</returns> public byte[] BuildPacket() { // Get the packet data byte[] data = Data.ToArray(); // Compression bool compressed = false; if (DataLength > 100) { byte[] compressedData = CompressionService.Compress(data); if (compressedData.Length < data.Length) { data = compressedData; compressed = true; } } ushort dataLength = (ushort)data.Length; // Create the packet header InternalPacketHeader header = new InternalPacketHeader { OpCode = OpCode, Compressed = compressed, Length = dataLength }; LastHeader = header; // Append the header and CRC to the compressed data ToffeePacket packet = new ToffeePacket(Sender); packet.Write(header); packet.Write(data, true); packet.Write(CRC.CalculateCRC32(data)); return(packet.GetBytes()); }
public DbFileRepository(string connectionString) { _connection = new SQLiteConnection(connectionString); _compressionService = Locator.Current.GetService <CompressionService>(); }
public static async Task Main(string[] args) { // Make sure only days, source Directory, and targetDirectory are entered into program if (args.Length != 4) { await SystemUtilityService.NotifySystemAdminAsync(Constants.InvalidArgs, Constants.SystemAdminEmailAddress).ConfigureAwait(false); return; } DateTime currentTime = DateTime.Now; int days; string targetDirectory = ""; try { days = Convert.ToInt32(args[1]); } catch { await SystemUtilityService.NotifySystemAdminAsync(Constants.FirstArgumentNotInt, Constants.SystemAdminEmailAddress).ConfigureAwait(false); return; } string sourceDir; if (Directory.Exists(args[2])) { sourceDir = args[2]; } else { await SystemUtilityService.NotifySystemAdminAsync(Constants.SourceDirectoryDNE, Constants.SystemAdminEmailAddress).ConfigureAwait(false); return; } if (Directory.Exists(args[3])) { targetDirectory = args[3]; } targetDirectory += currentTime.ToString(Constants.NamingFormatString); bool result = false; // FetchLogs will return true if files of the proper age are found in the source directory. if (FileFetchingService.FetchLogs(sourceDir, targetDirectory, days)) { if (CompressionService.Compress(Constants.SevenZipPath, sourceDir, targetDirectory)) { result = await FTPService.SendAsync(Constants.FTPUrl, "", targetDirectory, Constants.FTPUsername, Constants.FTPpassword).ConfigureAwait(false); } } // Notify system admin if Archiving fails to run successfully. if (result == false) { await SystemUtilityService.NotifySystemAdminAsync("Archiving failed on" + currentTime, Constants.SystemAdminEmailAddress).ConfigureAwait(false); } }