Пример #1
0
        private void btn_7unz_Click(object sender, EventArgs e)
        {
            if (SELECTED_FILES == null)
            {
                return;
            }

            var app = new SevenZip(prog.CDCRUSH.TOOLS_PATH);

            app.onComplete = (s) => {
                LOG.log("--7zip Complete :: {0}", s);
            };
            app.onProgress = (p) => {
                LOG.log("--7zip Got Progress :: {0}", p);
            };
            string destFolder   = Path.GetDirectoryName(SELECTED_FILES[0]);
            string destFilename = Path.GetFileNameWithoutExtension(SELECTED_FILES[0]);
            string finalpath    = Path.Combine(destFolder, destFilename + "_test_");

            if (!string.IsNullOrEmpty(txt_files_2.Text))
            {
                finalpath = txt_files_2.Text;
            }

            app.extract(SELECTED_FILES[0], finalpath);
        }
Пример #2
0
        public void Test_compress_to_extract_roundtrip()
        {
            const string originalContent = "Hello world!";
            var          originalPath    = _tempDirectoryPath.Join("original.txt");

            originalPath.WriteAllText(originalContent);

            var sevenZip = new SevenZip(silent: false);
            var zipPath  = _tempDirectoryPath.Join("compressed.7z");

            sevenZip.Compress(originalPath, zipPath);
            zipPath.IsFile().Should().BeTrue();

            var extractedDirectoryPath = _tempDirectoryPath.Join("extracted");

            extractedDirectoryPath.CreateDirectory();
            sevenZip.Extract(zipPath, extractedDirectoryPath);

            var extractedPath = extractedDirectoryPath.Join("original.txt");

            extractedDirectoryPath.IsDirectory().Should().BeTrue();
            extractedPath.IsFile().Should().BeTrue();

            var extractedContent = extractedPath.ReadAllText();

            extractedContent.Should().Be(originalContent);
        }
Пример #3
0
        public List <OCMessage> GetOCMessage(Contact contract, DateTime dtStart, DateTime dtEnd)
        {
            List <OCMessage> list = new List <OCMessage>();

            lock (locker)
            {
                using (var repository = StorageEngine.FromFile(DATABASE_NAME))
                {
                    var table = repository.Scheme.CreateOrOpenXTable <long, OCMessage>(
                        new Locator(contract.ContactName));
                    repository.Scheme.Commit();

                    var ocMessages = table.Where(w => w.Record.MessageTime >= dtStart &&
                                                 w.Record.MessageTime < dtEnd)
                                     .Select(s => s.Record);

                    if (ocMessages != null)
                    {
                        foreach (var v in ocMessages)
                        {
                            var msg = new OCMessage()
                            {
                                ContactId   = v.ContactId,
                                MessageText = v.IsCompressed ? SevenZip.Decompress(v.MessageText) : v.MessageText,
                                MessageTime = v.MessageTime
                            };
                            list.Add(msg);
                        }
                    }
                }
            }

            return(list);
        }
Пример #4
0
        public void Test_extract_excluding_path()
        {
            const string originalContent = "Hello world!";
            var          originalDirPath = _tempDirectoryPath.Join("original");

            originalDirPath.CreateDirectory();
            var originalPath1 = originalDirPath.Join("to_be_extracted.txt");
            var originalPath2 = originalDirPath.Join("to_be_excluded.txt");

            originalPath1.WriteAllText(originalContent);
            originalPath2.WriteAllText(originalContent);

            var sevenZip = new SevenZip(silent: false);
            var zipPath  = _tempDirectoryPath.Join("compressed.7z");

            sevenZip.Compress(originalDirPath, zipPath);
            zipPath.IsFile().Should().BeTrue();

            var extractedDirectoryPath = _tempDirectoryPath.Join("extracted");
            var extractedDirPath       = extractedDirectoryPath.Join("original");

            extractedDirectoryPath.CreateDirectory();
            sevenZip.Extract(zipPath, extractedDirectoryPath,
                             excludedFiles: new[] { extractedDirPath.Join("to_be_excluded.txt") });

            extractedDirectoryPath.IsDirectory().Should().BeTrue();
            extractedDirPath.IsDirectory().Should().BeTrue();
            extractedDirPath.Join("to_be_extracted.txt").IsFile().Should().BeTrue();
            extractedDirPath.Join("to_be_excluded.txt").IsFile().Should().BeFalse();
        }
Пример #5
0
        public void SaveMessage(DateTime beginTime, string messageBody, string[] contracts)
        {
            messageBody = MessageFormatter.FormatSendTimeStamp(messageBody);

            string compress = SevenZip.Compress(messageBody);

            bool isCompressed = compress.Length < messageBody.Length;

            foreach (var c in contracts)
            {
                Contact contract = SaveContract(c, beginTime);
                SaveContractCoversationDailyDate(contract, beginTime);
                SaveMessage(contract, isCompressed ? compress : messageBody, beginTime, isCompressed);
            }
        }
Пример #6
0
Файл: SQL.cs Проект: iwteih/OCH
        public List<OCMessage> GetOCMessage(Contact contract, DateTime dtStart, DateTime dtEnd)
        {
            List<OCMessage> list = new List<OCMessage>();

            using (SqlConnection connection =
                    new SqlConnection(connectionString))
            {
                using (SqlCommand command = new SqlCommand("GetOCMessage", connection))
                {
                    connection.Open();

                    command.CommandType = System.Data.CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@ContactId", contract.Id);
                    command.Parameters.AddWithValue("@dtStart", dtStart == DateTime.MinValue ? 
                        new DateTime(1753, 1, 1) : dtStart);

                    command.Parameters.AddWithValue("@dtEnd", dtEnd);

                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            OCMessage message = new OCMessage();
                            message.ContactId = int.Parse(reader["ContactId"].ToString());
                            message.MessageText = reader["MessageText"].ToString();
                            message.MessageTime = DateTime.Parse(reader["MessageTime"].ToString());
                            message.IsCompressed = bool.Parse(reader["IsCompressed"].ToString());
                            
                            if (message.IsCompressed)
                            {
                                message.MessageText = SevenZip.Decompress(message.MessageText);
                            }

                            list.Add(message);
                        }
                    }
                }
            }

            return list;
        }
Пример #7
0
        public void FileSignatures_TestSevenZipFile()
        {
            SevenZip testFile = new SevenZip(Path.Combine(resourceDir, "FileSignature_Compression_SevenZipFile.7z"));

            Assert.AreEqual(true, testFile.EntireFileIsValid);
        }
Пример #8
0
 public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
 {
     if (symbol < Base.kNumLowLenSymbols)
     {
         _choice.Encode(rangeEncoder, 0);
         _lowCoder[posState].Encode(rangeEncoder, symbol);
     }
     else
     {
         symbol -= Base.kNumLowLenSymbols;
         _choice.Encode(rangeEncoder, 1);
         if (symbol < Base.kNumMidLenSymbols)
         {
             _choice2.Encode(rangeEncoder, 0);
             _midCoder[posState].Encode(rangeEncoder, symbol);
         }
         else
         {
             _choice2.Encode(rangeEncoder, 1);
             _highCoder.Encode(rangeEncoder, symbol - Base.kNumMidLenSymbols);
         }
     }
 }
Пример #9
0
 public byte DecodeNormal(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte)
 {
     return m_Coders[GetState(pos, prevByte)].DecodeNormal(rangeDecoder);
 }
Пример #10
0
 public uint Decode(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, uint posState)
 {
     if (m_Choice.Decode(rangeDecoder) == 0)
         return m_LowCoder[posState].Decode(rangeDecoder);
     else
     {
         uint symbol = Base.kNumLowLenSymbols;
         if (m_Choice2.Decode(rangeDecoder) == 0)
             symbol += m_MidCoder[posState].Decode(rangeDecoder);
         else
         {
             symbol += Base.kNumMidLenSymbols;
             symbol += m_HighCoder.Decode(rangeDecoder);
         }
         return symbol;
     }
 }
        public static void TestFlyweightDesign(string charArray)
        {
            SevenZip sevenZip = new SevenZip();

            sevenZip.ZipDocument(charArray);
        }
Пример #12
0
 public byte DecodeWithMatchByte(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, uint pos, byte prevByte, byte matchByte)
 {
     return m_Coders[GetState(pos, prevByte)].DecodeWithMatchByte(rangeDecoder, matchByte);
 }
Пример #13
0
        /// <summary>
        /// Extracts files from the archive one-by-one.
        /// </summary>
        private void ExtractIndividual(SevenZip.SevenZipExtractor extractor)
        {
            _unitsByte = true;
            UnitsTotal = extractor.UnpackedSize;

            foreach (var entry in extractor.ArchiveFileData)
            {
                string relativePath = GetRelativePath(entry.FileName.Replace('\\', '/'));
                if (relativePath == null) continue;

                if (entry.IsDirectory) CreateDirectory(relativePath, entry.LastWriteTime);
                else
                {
                    using (var stream = OpenFileWriteStream(relativePath))
                        extractor.ExtractFile(entry.Index, stream);
                    File.SetLastWriteTimeUtc(CombinePath(relativePath), DateTime.SpecifyKind(entry.LastWriteTime, DateTimeKind.Utc));

                    UnitsProcessed += (long)entry.Size;
                }
            }
            Finish();
        }
Пример #14
0
 public void EncodeMatched(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, byte matchByte, byte symbol)
 {
     uint context = 1;
     bool same = true;
     for (int i = 7; i >= 0; i--)
     {
         uint bit = (uint)((symbol >> i) & 1);
         uint state = context;
         if (same)
         {
             uint matchBit = (uint)((matchByte >> i) & 1);
             state += ((1 + matchBit) << 8);
             same = (matchBit == bit);
         }
         m_Encoders[state].Encode(rangeEncoder, bit);
         context = (context << 1) | bit;
     }
 }
Пример #15
0
 public new void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, UInt32 symbol, UInt32 posState)
 {
     base.Encode(rangeEncoder, symbol, posState);
     if (--_counters[posState] == 0)
         UpdateTable(posState);
 }
Пример #16
0
 public byte DecodeNormal(SevenZip.Compression.RangeCoder.Decoder rangeDecoder)
 {
     uint symbol = 1;
     do
         symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder);
     while (symbol < 0x100);
     return (byte)symbol;
 }
Пример #17
0
 public byte DecodeWithMatchByte(SevenZip.Compression.RangeCoder.Decoder rangeDecoder, byte matchByte)
 {
     uint symbol = 1;
     do
     {
         uint matchBit = (uint)(matchByte >> 7) & 1;
         matchByte <<= 1;
         uint bit = m_Decoders[((1 + matchBit) << 8) + symbol].Decode(rangeDecoder);
         symbol = (symbol << 1) | bit;
         if (matchBit != bit)
         {
             while (symbol < 0x100)
                 symbol = (symbol << 1) | m_Decoders[symbol].Decode(rangeDecoder);
             break;
         }
     }
     while (symbol < 0x100);
     return (byte)symbol;
 }
Пример #18
0
 public void Encode(SevenZip.Compression.RangeCoder.Encoder rangeEncoder, byte symbol)
 {
     uint context = 1;
     for (int i = 7; i >= 0; i--)
     {
         uint bit = (uint)((symbol >> i) & 1);
         m_Encoders[context].Encode(rangeEncoder, bit);
         context = (context << 1) | bit;
     }
 }
Пример #19
0
 private void extractor_Extracting(object sender, SevenZip.ProgressEventArgs e)
 {
     Invoke((MethodInvoker)delegate
     {
         pbProgress.Value = e.PercentDone;
         lblStatus.Text = "Status: Extracting...";
     });
 }
Пример #20
0
        /// <summary>
        /// Extracts all files from the archive in one go.
        /// </summary>
        private void ExtractComplete(SevenZip.SevenZipExtractor extractor)
        {
            _unitsByte = false;
            UnitsTotal = 100;
            extractor.Extracting += (sender, e) => { UnitsProcessed = e.PercentDone; };

            CancellationToken.ThrowIfCancellationRequested();
            if (string.IsNullOrEmpty(SubDir)) extractor.ExtractArchive(EffectiveTargetDir);
            else
            {
                // Use an intermediate temp directory (on the same filesystem)
                string tempDir = Path.Combine(TargetDir, Path.GetRandomFileName());
                extractor.ExtractArchive(tempDir);

                // Get only a specific subdir even though we extracted everything
                string subDir = FileUtils.UnifySlashes(SubDir);
                string tempSubDir = Path.Combine(tempDir, subDir);
                if (!FileUtils.IsBreakoutPath(subDir) && Directory.Exists(tempSubDir))
                    new MoveDirectory(tempSubDir, EffectiveTargetDir, overwrite: true).Run(CancellationToken);
                Directory.Delete(tempDir, recursive: true);
            }
            CancellationToken.ThrowIfCancellationRequested();
        }
Пример #21
0
        public List <OCHEntity.OCMessage> GetOCMessage(Contact contract, DateTime dtStart, DateTime dtEnd)
        {
            List <OCMessage> list = new List <OCMessage>();

            try
            {
                lock (locker)
                {
                    using (var connection =
                               new SqliteConnection(DATABASE_NAME))
                    {
                        using (var command = connection.CreateCommand())
                        {
                            connection.Open();

                            command.CommandText = string.Format(@"SELECT *
	  from Message
	 where ContactId = '{0}'
	   and MessageTime >= '{1}'
	   and MessageTime < '{2}'
     order by strftime('%s',MessageTime)",
                                                                contract.Id,
                                                                DateTime2String(dtStart == DateTime.MinValue ?
                                                                                new DateTime(1970, 1, 1) : dtStart),
                                                                DateTime2String(dtEnd));

                            using (var reader = command.ExecuteReader())
                            {
                                if (reader.HasRows)
                                {
                                    while (reader.Read())
                                    {
                                        OCMessage message = new OCMessage();
                                        message.ContactId    = int.Parse(reader["ContactId"].ToString());
                                        message.MessageText  = reader["MessageText"].ToString();
                                        message.MessageTime  = DateTime.Parse(reader["MessageTime"].ToString());
                                        message.IsCompressed = bool.Parse(reader["IsCompressed"].ToString());

                                        if (message.IsCompressed)
                                        {
                                            message.MessageText = SevenZip.Decompress(message.MessageText);
                                        }

                                        list.Add(message);
                                    }
                                }

                                reader.Close();
                                reader.Dispose();
                            }

                            command.Dispose();
                        }

                        connection.Close();
                        connection.Dispose();
                    }
                }
            }
            catch (SqliteException exp)
            {
                logger.Error(exp);
            }

            return(list);
        }
Пример #22
0
        /// <summary>
        /// Get the content-detectable protections associated with a single path
        /// </summary>
        /// <param name="file">Path to the file to scan</param>
        /// <returns>Dictionary of list of strings representing the found protections</returns>
        private Dictionary <string, List <string> > GetInternalProtections(string file)
        {
            // Quick sanity check before continuing
            if (!File.Exists(file))
            {
                return(null);
            }

            // Initialze the protections found
            var protections = new Dictionary <string, List <string> >();

            // Get the extension for certain checks
            string extension = Path.GetExtension(file).ToLower().TrimStart('.');

            // Open the file and begin scanning
            using (FileStream fs = File.OpenRead(file))
            {
                // Get the first 16 bytes for matching
                byte[] magic = new byte[16];
                try
                {
                    fs.Read(magic, 0, 16);
                    fs.Seek(-16, SeekOrigin.Current);
                }
                catch
                {
                    // We don't care what the issue was, we can't read or seek the file
                    return(null);
                }

                #region Non-Archive File Types

                // Executable
                if (ScanAllFiles || new Executable().ShouldScan(magic))
                {
                    var subProtections = new Executable().Scan(this, fs, file);
                    Utilities.AppendToDictionary(protections, subProtections);
                }

                // Text-based files
                if (ScanAllFiles || new Textfile().ShouldScan(magic, extension))
                {
                    var subProtections = new Textfile().Scan(this, fs, file);
                    Utilities.AppendToDictionary(protections, subProtections);
                }

                #endregion

                #region Archive File Types

                // If we're scanning archives, we have a few to try out
                if (ScanArchives)
                {
                    // 7-Zip archive
                    if (new SevenZip().ShouldScan(magic))
                    {
                        var subProtections = new SevenZip().Scan(this, fs, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }

                    // BFPK archive
                    if (new BFPK().ShouldScan(magic))
                    {
                        var subProtections = new BFPK().Scan(this, fs, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }

                    // BZip2
                    if (new BZip2().ShouldScan(magic))
                    {
                        var subProtections = new BZip2().Scan(this, fs, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }

                    // GZIP
                    if (new GZIP().ShouldScan(magic))
                    {
                        var subProtections = new GZIP().Scan(this, fs, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }

                    // InstallShield Cabinet
                    if (file != null && new InstallShieldCAB().ShouldScan(magic))
                    {
                        var subProtections = new InstallShieldCAB().Scan(this, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }

                    // Microsoft Cabinet
                    if (file != null && new MicrosoftCAB().ShouldScan(magic))
                    {
                        var subProtections = new MicrosoftCAB().Scan(this, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }

                    // MSI
                    if (file != null && new MSI().ShouldScan(magic))
                    {
                        var subProtections = new MSI().Scan(this, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }

                    // MPQ archive
                    if (file != null && new MPQ().ShouldScan(magic))
                    {
                        var subProtections = new MPQ().Scan(this, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }

                    // PKZIP archive (and derivatives)
                    if (new PKZIP().ShouldScan(magic))
                    {
                        var subProtections = new PKZIP().Scan(this, fs, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }

                    // RAR archive
                    if (new RAR().ShouldScan(magic))
                    {
                        var subProtections = new RAR().Scan(this, fs, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }

                    // Tape Archive
                    if (new TapeArchive().ShouldScan(magic))
                    {
                        var subProtections = new TapeArchive().Scan(this, fs, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }

                    // Valve archive formats
                    if (file != null && new Valve().ShouldScan(magic))
                    {
                        var subProtections = new Valve().Scan(this, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }

                    // XZ
                    if (new XZ().ShouldScan(magic))
                    {
                        var subProtections = new XZ().Scan(this, fs, file);
                        Utilities.PrependToKeys(subProtections, file);
                        Utilities.AppendToDictionary(protections, subProtections);
                    }
                }

                #endregion
            }

            // Clear out any empty keys
            Utilities.ClearEmptyKeys(protections);

            return(protections);
        }
Пример #23
0
        public void Test_implementsSearchForNewer()
        {
            var seven = new SevenZip(false);

            Assert.IsTrue(seven.implementsSearchForNewer());
        }