Exemple #1
0
        public void Compressor_CanCompressIonic()
        {
            ICompressor compressor = new GZipCompressor();
            string      archive    = compressor.Compress(TestFilePath);

            Assert.IsTrue(File.Exists(archive));
        }
Exemple #2
0
        public void TestBuildInput_NoIdentifier_Compression()
        {
            ICompressor compressor = new GZipCompressor();
            Image       img        = _createTestImage();
            JobInput    i          = new JobInput(img);

            i.Compressor = compressor;
            JobBuilderProcess p       = new JobBuilderProcess();
            XElement          element = p.BuildInput(i);

            Assert.AreEqual("input", element.Name);
            Assert.IsNull(element.Attribute("identifier"));

            Assert.IsNotNull(element.Attribute("compressor"));
            Assert.AreEqual("gzip", element.Attribute("compressor").Value.ToLower());

            XNode child = element.FirstNode;

            Assert.IsTrue(child.NodeType == System.Xml.XmlNodeType.CDATA);

            XCData data          = (XCData)child;
            string providedImage = data.Value;
            string expectedImage = System.Text.Encoding.Default.GetString(CompressionAssistant.Compress(img, compressor));

            Assert.AreEqual(expectedImage, providedImage);
        }
        public void TestResolveIdentifier_ValidCompressor()
        {
            ICompressor compressor = new GZipCompressor();
            string      id         = CompressorFactory.ResolveIdentifier(compressor);

            Assert.AreEqual("gzip", id.ToLower());
        }
Exemple #4
0
        /// <summary>
        /// Convert the current record to a GZipped Base64 string
        /// </summary>
        /// <returns></returns>
        public string ToRawForm()
        {
            var rawDoc = Serializers.PxzRecordToXml(this);
            var rawXml = rawDoc.OuterXml;

            return(GZipCompressor.CompressString(rawXml));
        }
        private void InitializeConfiguration()
        {
            var certificateStore    = new CertificateStore(ModuleLogger(nameof(CertificateStore)));
            var compressor          = new GZipCompressor(ModuleLogger(nameof(GZipCompressor)));
            var passwordEncryption  = new PasswordEncryption(ModuleLogger(nameof(PasswordEncryption)));
            var publicKeyEncryption = new PublicKeyEncryption(certificateStore, ModuleLogger(nameof(PublicKeyEncryption)));
            var symmetricEncryption = new PublicKeySymmetricEncryption(certificateStore, ModuleLogger(nameof(PublicKeySymmetricEncryption)), passwordEncryption);
            var repositoryLogger    = ModuleLogger(nameof(ConfigurationRepository));
            var xmlParser           = new XmlParser(compressor, ModuleLogger(nameof(XmlParser)));
            var xmlSerializer       = new XmlSerializer(ModuleLogger(nameof(XmlSerializer)));

            configuration = new ConfigurationRepository(certificateStore, new HashAlgorithm(), repositoryLogger);
            appConfig     = configuration.InitializeAppConfig();

            configuration.Register(new BinaryParser(
                                       compressor,
                                       new HashAlgorithm(),
                                       ModuleLogger(nameof(BinaryParser)),
                                       passwordEncryption,
                                       publicKeyEncryption,
                                       symmetricEncryption, xmlParser));
            configuration.Register(new BinarySerializer(
                                       compressor,
                                       ModuleLogger(nameof(BinarySerializer)),
                                       passwordEncryption,
                                       publicKeyEncryption,
                                       symmetricEncryption,
                                       xmlSerializer));
            configuration.Register(new XmlParser(compressor, ModuleLogger(nameof(XmlParser))));
            configuration.Register(new XmlSerializer(ModuleLogger(nameof(XmlSerializer))));
            configuration.Register(new FileResourceLoader(ModuleLogger(nameof(FileResourceLoader))));
            configuration.Register(new FileResourceSaver(ModuleLogger(nameof(FileResourceSaver))));
            configuration.Register(new NetworkResourceLoader(appConfig, new ModuleLogger(logger, nameof(NetworkResourceLoader))));
        }
Exemple #6
0
        public void Compress()
        {
            var    TestObject = new GZipCompressor();
            string Data       = "This is a bit of data that I want to compress";

            Assert.Equal("H4sIAAAAAAAACwrJyCxWAKJEhaTMEoX8NIWUxJJEhZKMxBIFT4XyxLwShZJ8heT83IKi1OJiAAAAAP//", Convert.ToBase64String(TestObject.Compress(Data.ToByteArray())));
        }
Exemple #7
0
        public void Decompress()
        {
            var    TestObject = new GZipCompressor();
            string Data       = "This is a bit of data that I want to compress";

            Assert.Equal("This is a bit of data that I want to compress", TestObject.Decompress(TestObject.Compress(Data.ToByteArray())).ToString(null));
        }
Exemple #8
0
        public void CompressionAsyncTest()
        {
            AutoResetEvent          waitHandle = new AutoResetEvent(false);
            CustomCancellationToken token      = CustomCancellationTokenSource.GetToken();

            compressor = new GZipCompressor(waitHandle);
            string decompressedFileName = @"Decompressed_" + startFileName;

            GZipCompressionDelegate del = compressor.Compress;

            del.BeginInvoke(startFileName, endFileName, token, OnCompressionComplete, del);
            waitHandle.WaitOne();
            string startFileHash        = "";
            string decompressedFileHash = "";

            MD5 md5hash = MD5.Create();

            del = compressor.Decompress;
            del.BeginInvoke(endFileName, decompressedFileName, token, OnCompressionComplete, del);
            waitHandle.WaitOne();

            using (Stream startFileStream = File.OpenRead(startFileName))
                using (Stream decompressedFIleStream = File.OpenRead(decompressedFileName))
                {
                    startFileHash        = Encoding.Default.GetString(md5hash.ComputeHash(startFileStream));
                    decompressedFileHash = Encoding.Default.GetString(md5hash.ComputeHash(decompressedFIleStream));
                }
            Assert.AreEqual(startFileHash, decompressedFileHash);
        }
Exemple #9
0
        public void CompressionTest()
        {
            AutoResetEvent waitHandle = new AutoResetEvent(false);

            compressor = new GZipCompressor(waitHandle);
            //startFileName = @"video.avi";
            string decompressedFileName = @"Decompressed_" + startFileName;

            compressor.OnCompressionComplete += compressor_OnCompressionComplete;
            compressor.Compress(startFileName, endFileName);
            waitHandle.WaitOne();
            string startFileHash        = "";
            string decompressedFileHash = "";

            MD5 md5hash = MD5.Create();

            compressor.Decompress(endFileName, decompressedFileName);
            waitHandle.WaitOne();

            using (Stream startFileStream = File.OpenRead(startFileName))
                using (Stream decompressedFIleStream = File.OpenRead(decompressedFileName))
                {
                    startFileHash        = Encoding.Default.GetString(md5hash.ComputeHash(startFileStream));
                    decompressedFileHash = Encoding.Default.GetString(md5hash.ComputeHash(decompressedFIleStream));
                }
            Assert.AreEqual(startFileHash, decompressedFileHash);
        }
Exemple #10
0
 public void GZipStream_Decompressor_2()
 {
     byte[] input       = new byte[] { 0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x73, 0x74, 0x72, 0x76, 0x71, 0x75, 0x03, 0x00, 0x69, 0xFE, 0x76, 0xBB, 0x06, 0x00, 0x00, 0x00 };
     byte[] plaintext   = Encoding.UTF8.GetBytes("ABCDEF");
     byte[] decompBytes = GZipCompressor.Decompress(input);
     Assert.IsTrue(decompBytes.SequenceEqual(plaintext));
 }
        public void Compressor_CanCompressIonic()
        {
            ICompressor compressor = new GZipCompressor();
            string archive = compressor.Compress(TestFilePath);

            Assert.IsTrue(File.Exists(archive));
        }
Exemple #12
0
        /// <summary>
        /// Gets the compression mechanism using the service context and the depending on the request and response.
        /// </summary>
        /// <param name="serviceContext">The service context object.</param>
        /// <param name="isRequest">Specifies whether to return compression mechanism for reqeust or response.</param>
        /// <returns>The Compression mechanism.</returns>
        public static ICompressor GetCompressor(ServiceContext serviceContext, bool isRequest)
        {
            ICompressor compressor = null;

            if (isRequest)
            {
                switch (serviceContext.IppConfiguration.Message.Request.CompressionFormat)
                {
                case Configuration.CompressionFormat.GZip:
                    compressor = new GZipCompressor();
                    break;

                case Configuration.CompressionFormat.Deflate:
                    compressor = new DeflateCompressor();
                    break;
                }
            }
            else
            {
                switch (serviceContext.IppConfiguration.Message.Response.CompressionFormat)
                {
                case Configuration.CompressionFormat.GZip:
                    compressor = new GZipCompressor();
                    break;

                case Configuration.CompressionFormat.Deflate:
                    compressor = new DeflateCompressor();
                    break;
                }
            }

            return(compressor);
        }
Exemple #13
0
        public void TestDecompress_NullBytes()
        {
            GZipCompressor c = new GZipCompressor();

            byte[] decompressed = c.Decompress(null);
            Assert.IsNotNull(decompressed);
            Assert.AreEqual(0, decompressed.Length);
        }
Exemple #14
0
        public void Compressor_CanDecompressIonic()
        {
            ICompressor compressor = new GZipCompressor();
            string      file       = compressor.Decompress(compressor.Compress(TestFilePath));

            Assert.IsTrue(File.Exists(file));
            Assert.AreEqual(TestFilePath, file);
        }
Exemple #15
0
 public virtual void Compress(string srcPath, string destPath)
 {
     using (ICompressor cmpr = new GZipCompressor(srcPath, destPath))
     {
         cmpr.OnCompleted += CompressionCompleted;
         cmpr.Compress();
     }
 }
 public override void SetParameterValues(IDictionary <string, string> parameters)
 {
     base.SetParameterValues(parameters);
     if (Compression == null)
     {
         Compression = new GZipCompressor();
     }
 }
        public void Compressor_CanDecompressIonic()
        {
            ICompressor compressor = new GZipCompressor();
            string file = compressor.Decompress(compressor.Compress(TestFilePath));

            Assert.IsTrue(File.Exists(file));
            Assert.AreEqual(TestFilePath, file);
        }
Exemple #18
0
        /// <summary>
        /// Save this PXZ file to disk
        /// </summary>
        /// <param name="path">The file to save to/create</param>
        public void Save(string path)
        {
            //delete the existing file (if it exists)
            if (System.IO.File.Exists(path))
            {
                System.IO.File.Delete(path);
            }

            //new index attributes (don't override records though)
            FileIndex.Author = PxzAuthor.FromCurrent();

            var idxDoc = FileIndex.ToXml();

            //deflate the content to save room (poster isn't compressed via Zlib)
            var idxByte = GZipCompressor.CompressString(idxDoc.OuterXml);

            //names of root format items
            const string idxName = @"index";
            const string recName = @"records";

            //create a new temporary Zip file (in memory, not on disk)
            using var archive = new ZipFile(path, Encoding.Default);

            //add the indexing information to the PXZ
            archive.AddEntry(idxName, idxByte);

            //add records folder
            archive.AddDirectoryByName(recName);

            //traverse the records list
            foreach (var r in Records)
            {
                //null records are skipped
                if (r == null)
                {
                    continue;
                }

                //convert to record string
                var raw = r.ToRawForm();

                //record name
                var fileName = $"{recName}/{r.Header.Naming.StoredName}";

                //add the ZIP entry of the file
                if (!archive.Any(entry => entry.FileName.EndsWith(fileName)))
                {
                    archive.AddEntry(fileName, raw);
                }
            }

            //finalise ZIP file
            archive.Save(path);

            //cull the residual archive from memory
            archive.Dispose();
        }
Exemple #19
0
        public void TestCompressDecompressSomeByteArray()
        {
            ICompressor compressor = new GZipCompressor();

            var originalBytes     = Encoding.UTF8.GetBytes("Hello, World!");
            var compressedBytes   = compressor.Compress(originalBytes);
            var decompressedBytes = compressor.Decompress(compressedBytes);

            CollectionAssert.AreEqual(originalBytes, decompressedBytes);
        }
Exemple #20
0
        public void TestCompressDecompressEmptyByteArray()
        {
            ICompressor compressor = new GZipCompressor();

            var originalBytes     = new byte[0];
            var compressedBytes   = compressor.Compress(originalBytes);
            var decompressedBytes = compressor.Decompress(compressedBytes);

            CollectionAssert.AreEqual(originalBytes, decompressedBytes);
        }
        public void CompressTest()
        {
            GZipCompressor target   = new GZipCompressor(); // TODO: Initialize to an appropriate value
            UTF8Encoding   encoding = new UTF8Encoding();

            byte[] content       = encoding.GetBytes("abc@123"); // TODO: Initialize to an appropriate value
            Stream requestStream = new MemoryStream();           // TODO: Initialize to an appropriate value

            target.Compress(content, requestStream);
            Assert.IsNotNull(requestStream);
        }
        public void GZipCompressorBytesExtesionWorks()
        {
            var compressor = new GZipCompressor();
            var compressed = compressor.Compress(Encoding.UTF8.GetBytes("test"));

            Assert.IsNotNull(compressed);
            var decompressor = new GZipDecompressor();
            var decompressed = decompressor.Decompress(compressed);

            Assert.IsNotNull(decompressed);
            Assert.AreEqual("test", Encoding.UTF8.GetString(decompressed));
        }
Exemple #23
0
        public void TestDecompress_CompressedBytes()
        {
            GZipCompressor c   = new GZipCompressor();
            string         str = "Hello";

            byte[] strBytes        = System.Text.Encoding.UTF8.GetBytes(str);
            byte[] compressed      = c.Compress(strBytes);
            byte[] decompressed    = c.Decompress(compressed);
            string strDecompressed = System.Text.Encoding.Default.GetString(decompressed);

            Assert.AreEqual(str, strDecompressed);
        }
        private static byte[] GetCompressedData(byte[] dataToCompress)
        {
            var gZipCompressor = new GZipCompressor(new InMemoryFileService());

            var outputStream = new MemoryStream();

            gZipCompressor.Execute(new MemoryStream(dataToCompress), outputStream, true);

            var compressedResult = outputStream.ToArray();

            return(compressedResult);
        }
        public void GZipCompressorStringExtesionWorks()
        {
            var compressor = new GZipCompressor();
            var compressed = compressor.Compress("test");

            compressed.Should().NotBeNull();
            var decompressor = new GZipDecompressor();
            var decompressed = decompressor.Decompress(compressed);

            decompressed.Should().NotBeNull();
            Encoding.UTF8.GetString(decompressed).Should().Be("test");
        }
        /// <summary>
        /// rawData should NOT contain encrypted bytes; this is done here if applicable.
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="protectedData"></param>
        private void GenericConstructor(byte[] rawData, bool protectedData = false)
        {
            Encrypted = protectedData;

            //we'll need to encrypt everything if it's true
            if (protectedData)
            {
                var provider = new ProtectedBytes(rawData, ProtectionMode.Encrypt);
                rawData = provider.ProcessedValue;
            }

            RawRecord = GZipCompressor.CompressString(rawData);
        }
Exemple #27
0
        /// <summary>
        /// Compress the byte array value of a message.
        /// </summary>
        /// <param name="value">A byte array to compress.</param>
        /// <param name="encoding">
        /// The encoding used to convert the string to a byte array.
        /// </param>
        /// <returns>The compressed byte array.</returns>
        public byte[] Compress(byte[] value, Encoding encoding)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            var compressor = new GZipCompressor();

            return(encoding.GetBytes(Convert.ToBase64String(compressor.Compress(value))));
        }
Exemple #28
0
        public void CompressionWithCancellationTest()
        {
            AutoResetEvent          waitHandle = new AutoResetEvent(false);
            CustomCancellationToken token      = CustomCancellationTokenSource.GetToken();

            compressor = new GZipCompressor(waitHandle);
            //startFileName = @"video.avi";
            GZipCompressionDelegate del = compressor.Decompress;

            compressor.OnCompressionComplete += compressor_OnCompressionCompleteWithCancellation;
            del.BeginInvoke(startFileName, endFileName, token, null, del);
            Thread.Sleep(6000);
            token.IsCancelled = true;
            waitHandle.WaitOne();
        }
Exemple #29
0
        private void InitializeConfiguration()
        {
            var executable       = Assembly.GetExecutingAssembly();
            var programBuild     = FileVersionInfo.GetVersionInfo(executable.Location).FileVersion;
            var programCopyright = executable.GetCustomAttribute <AssemblyCopyrightAttribute>().Copyright;
            var programTitle     = executable.GetCustomAttribute <AssemblyTitleAttribute>().Title;
            var programVersion   = executable.GetCustomAttribute <AssemblyInformationalVersionAttribute>().InformationalVersion;

            var certificateStore    = new CertificateStore(ModuleLogger(nameof(CertificateStore)));
            var compressor          = new GZipCompressor(ModuleLogger(nameof(GZipCompressor)));
            var passwordEncryption  = new PasswordEncryption(ModuleLogger(nameof(PasswordEncryption)));
            var publicKeyEncryption = new PublicKeyEncryption(certificateStore, ModuleLogger(nameof(PublicKeyEncryption)));
            var symmetricEncryption = new PublicKeySymmetricEncryption(certificateStore, ModuleLogger(nameof(PublicKeySymmetricEncryption)), passwordEncryption);
            var repositoryLogger    = ModuleLogger(nameof(ConfigurationRepository));
            var xmlParser           = new XmlParser(ModuleLogger(nameof(XmlParser)));
            var xmlSerializer       = new XmlSerializer(ModuleLogger(nameof(XmlSerializer)));

            configuration = new ConfigurationRepository(
                certificateStore,
                new HashAlgorithm(),
                repositoryLogger,
                executable.Location,
                programBuild,
                programCopyright,
                programTitle,
                programVersion);
            appConfig = configuration.InitializeAppConfig();

            configuration.Register(new BinaryParser(
                                       compressor,
                                       new HashAlgorithm(),
                                       ModuleLogger(nameof(BinaryParser)),
                                       passwordEncryption,
                                       publicKeyEncryption,
                                       symmetricEncryption, xmlParser));
            configuration.Register(new BinarySerializer(
                                       compressor,
                                       ModuleLogger(nameof(BinarySerializer)),
                                       passwordEncryption,
                                       publicKeyEncryption,
                                       symmetricEncryption,
                                       xmlSerializer));
            configuration.Register(new XmlParser(ModuleLogger(nameof(XmlParser))));
            configuration.Register(new XmlSerializer(ModuleLogger(nameof(XmlSerializer))));
            configuration.Register(new FileResourceLoader(ModuleLogger(nameof(FileResourceLoader))));
            configuration.Register(new FileResourceSaver(ModuleLogger(nameof(FileResourceSaver))));
            configuration.Register(new NetworkResourceLoader(appConfig, new ModuleLogger(logger, nameof(NetworkResourceLoader))));
        }
Exemple #30
0
        public void GZipStream_Compressor_2()
        {
            byte[] input = Encoding.UTF8.GetBytes("ABCDEF");

            // Compress first,
            // 1F-8B-08-00-00-00-00-00-00-0A-73-74-72-76-71-75-03-00-69-FE-76-BB-06-00-00-00
            byte[] compBytes = GZipCompressor.Compress(input);

            // then Decompress
            byte[] decompBytes = GZipCompressor.Decompress(compBytes);

            // Comprare SHA256 Digest
            byte[] inputDigest  = TestSetup.SHA256Digest(input);
            byte[] decompDigest = TestSetup.SHA256Digest(decompBytes);
            Assert.IsTrue(decompDigest.SequenceEqual(inputDigest));
        }
        public void CompressDecompressTest()
        {
            GZipCompressor target     = new GZipCompressor();
            string         strContent = "Hello World";

            byte[] content = Encoding.ASCII.GetBytes(strContent);
            using (Stream requestStream = new MemoryStream())
            {
                var compressedStream = new GZipStream(requestStream, CompressionMode.Compress);
                compressedStream.Write(content, 0, content.Length);
                Stream actual = target.Decompress(requestStream);
                Assert.IsNotNull(actual);
                actual.Read(content, 0, content.Length);
                string dString = Encoding.ASCII.GetString(content);
                Assert.IsTrue(string.Compare(strContent, dString, false) == 0);
            }
        }
Exemple #32
0
        public void TestDecompileInput_GZipCompressor_NoIdentifier()
        {
            Image       rawImg     = Image.FromFile("compression_test.bmp");
            ICompressor compressor = new GZipCompressor();

            byte[]           img         = CompressionAssistant.Compress(rawImg, compressor);
            string           imgAsString = System.Text.Encoding.Default.GetString(img);
            XCData           data        = new XCData(imgAsString);
            XAttribute       c           = new XAttribute("compressor", "gzip");
            XElement         element     = new XElement("test", c, data);
            JobXmlDecompiler d           = new JobXmlDecompiler();
            JobInput         i           = d.DecompileInput(element);

            Assert.IsNotNull(i.Input);
            Assert.IsNotNull(i.Identifier);
            Assert.AreEqual(string.Empty, i.Identifier);
        }