Example #1
0
        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int idx = combo_compressType.SelectedIndex;

            switch (idx)
            {
            case 0: currType = CompressType.Retro_Curved; break;

            case 1: currType = CompressType.Radially_Tipped; break;
            }
        }
Example #2
0
        public static string GetAssetBundleDirectory(CompressType type)
        {
            var builder =
                new StringBuilder()
                .Append(Application.streamingAssetsPath)
                .Append("/")
                .Append(type.ToString())
                .Append("/");

            return(builder.ToString());
        }
Example #3
0
 /// <summary>
 /// 压缩指定文件夹下的文件
 /// </summary>
 /// <param name="sourceFilePath">文件夹目录</param>
 /// <param name="zipDirectory">压缩包保存目录,默认与源文件在同一目录</param>
 /// <param name="zipName">压缩包保存目录</param>
 /// <param name="searchPattern">要与 path 中的文件名匹配的搜索字符串。此参数可以包含有效文本路径和通配符(* 和 ?)的组合(请参见“备注”),但不支持正则表达式。</param>
 /// <param name="searchOption">默认当前文件夹下 TopDirectoryOnly,若查询包含所有子目录为AllDirectories</param>
 /// <param name="overWrite">是否覆盖</param>
 /// <param name="isEncrypt">是否加密</param>
 /// <param name="password">密码</param>
 /// <param name="compressionLevel">压缩等级(0 无 - 9 最高,默认 5)</param>
 /// <param name="zipMaxFile">压缩包内最多文件数量(-1不限)</param>
 /// <param name="blockSize">缓存大小(每次写入文件大小,默认 2048)</param>
 /// <param name="compressType">压缩方式(默认zip)</param>
 /// <returns></returns>
 public string[] CompressCatalogAndFiltrate(string sourceFilePath, string zipDirectory, string zipName,
                                            string searchPattern      = "*.*",
                                            SearchOption searchOption = SearchOption.AllDirectories, bool overWrite = true, bool isEncrypt = false,
                                            string password           = "", int compressionLevel = 5, int zipMaxFile = -1, int blockSize = 2048,
                                            CompressType compressType = null)
 {
     return(CompressFactory.GetProvider(compressType ?? CompressType.Zip).CompressCatalogAndFiltrate(
                sourceFilePath, zipDirectory,
                zipName, searchPattern, searchOption, overWrite, isEncrypt, password, compressionLevel, zipMaxFile,
                blockSize));
 }
 /// <summary>
 /// 压缩文件
 /// </summary>
 /// <param name="sourceFilePath">文件指定路径</param>
 /// <param name="zipDirectory">压缩包保存目录,默认与源文件在同一目录</param>
 /// <param name="zipName">压缩文件名称,默认与源文件名称一致</param>
 /// <param name="overWrite">是否覆盖</param>
 /// <param name="isEncrypt">是否加密</param>
 /// <param name="password">密码</param>
 /// <param name="compressionLevel">压缩等级(0 无 - 9 最高,默认 5)</param>
 /// <param name="blockSize">缓存大小(每次写入文件大小,默认 2048)</param>
 /// <param name="compressType">压缩方式(默认zip)</param>
 /// <returns></returns>
 public string CompressSingle(string sourceFilePath, string zipDirectory = "", string zipName = "",
                              bool overWrite            = true,
                              bool isEncrypt            = false,
                              string password           = "", int compressionLevel = 5, int blockSize = 2048,
                              CompressType compressType = null)
 {
     return(CompressFactory.GetProvider(compressType ?? CompressType.Zip).CompressSingle(sourceFilePath,
                                                                                         zipDirectory, zipName,
                                                                                         overWrite,
                                                                                         isEncrypt, password, compressionLevel, blockSize));
 }
Example #5
0
        static void EncryptAssetBundleInternal(CompressType type)
        {
            // 非暗号化AssetBundleをbyte[]化 → 暗号化を掛けていく
            var path  = SamplePathUtility.GetAssetBundlePath(type, false);
            var bytes = File.ReadAllBytes(path);

            var exportDir      = SamplePathUtility.GetAssetBundleDirectory(type);
            var exportFileName = SamplePathUtility.EncryptedPrefix + SamplePathUtility.SampleAssetBundleName;

            EncryptHelper.ExportEncryptBinary(bytes, exportDir + exportFileName);
            AssetDatabase.Refresh();
            Debug.Log($"Complete EncryptAssetBundleInternal({type})");
        }
Example #6
0
        public ServiceDecodeSetter(IServiceProvider container) : base(container)
        {
            var ssloption = container.GetRequiredService <IOptions <SslOption> >().Value;

            if (ssloption.IsUse && ssloption.Certificate != null)
            {
                Certificate = ssloption.Certificate;
                is_use_ssl  = true;
            }

            var compresstion = container.GetRequiredService <IOptions <CompressOption> >().Value;

            decodeType = compresstion.Mode;
        }
Example #7
0
 /// <summary>
 /// 压缩指定文件夹(压缩为单个压缩包)
 /// </summary>
 /// <param name="sourceFilePath">文件夹目录</param>
 /// <param name="zipDirectory">压缩包保存目录,默认与源文件在同一目录</param>
 /// <param name="zipName">压缩文件名称</param>
 /// <param name="isRecursive">是否递归(默认递归)</param>
 /// <param name="overWrite">是否覆盖</param>
 /// <param name="password">密码</param>
 /// <param name="compressionLevel">压缩等级(0 无 - 9 最高,默认 5)</param>
 /// <param name="compressType">压缩方式(默认zip)</param>
 /// <returns></returns>
 public string CompressCatalog(
     string sourceFilePath,
     string zipDirectory,
     string zipName,
     bool isRecursive          = true,
     bool overWrite            = true,
     string password           = "",
     int compressionLevel      = 5,
     CompressType compressType = null)
 {
     return(CompressFactory.GetProvider(compressType ?? CompressType.Zip).CompressCatalog(sourceFilePath,
                                                                                          zipDirectory, zipName,
                                                                                          isRecursive, overWrite, password, compressionLevel));
 }
Example #8
0
        public List <PValue> GetIntervalValuesFixInterval(string tagname, DateTime startdate, DateTime enddate, int count)
        {
            List <PValue>      pvalues = new List <PValue>();
            List <SignalValue> values  = new List <SignalValue>();

            if (!this._pgimDb.IsLogon)
            {
                return(pvalues);
            }

            //由时间间隔和指定的读取量,计算取数时间间隔
            TimeSpan ts       = enddate - startdate;
            double   interval = Math.Floor(ts.TotalSeconds / count);

            //关于ReadAggregates接口定义,请直接到定义中查找
            CompressType compress   = CompressType.Value;   //关于CompressType请到定义中去查找。这里可选选择去实际值、最小值、最大值、均值、积分、求和等等
            string       resolution = interval.ToString() + " sec";

            try
            {
                values = this._pgimDb.ReadAggregates(tagname, startdate, enddate, compress, resolution, count);
            }
            catch (PgimNet.Exceptions.PgimDataException ex)
            {
                //将pgim的异常PgimDataException记录在_exception中,并以PgimDataException的名称继续抛出异常
                this._exception = ex.Message.ToString();
                throw ex;     //将pgim的异常继续向外传递。
            }
            catch (PgimNet.Exceptions.PgimException ex)
            {
                //将pgim的异常PgimDataException记录在_exception中,并以PgimDataException的名称继续抛出异常
                this._exception = ex.Message.ToString();
                throw ex;     //将pgim的异常继续向外传递。
            }
            catch (Exception ex)
            {
                //将pgim的异常PgimDataException记录在_exception中,并以PgimDataException的名称继续抛出异常
                this._exception = "PgimNet其他未知错误。通常是服务器故障、标签中对应的服务器名称不正确导致!";
                throw ex;     //将pgim的异常继续向外传递。
            }

            //根据取整的时间间隔,重新计算结束时间
            enddate = startdate.AddSeconds(interval * count);
            pvalues = Signals2PValuesHistForInterval(values, startdate, enddate);
            //下面是记录读取指令的log
            //LogHelper.Write(LogType.Debug, string.Format("PGIM: {0},{1},{2},{3}", tag, starttime, endtime, values.Count));

            return(pvalues);
        }
Example #9
0
 /// <summary>
 /// 压缩多个文件
 /// </summary>
 /// <param name="sourceFileList">多文件指定路径</param>
 /// <param name="zipDirectory">压缩包保存目录</param>
 /// <param name="zipName">压缩文件名称(不能为空)</param>
 /// <param name="overWrite">是否覆盖</param>
 /// <param name="password">密码</param>
 /// <param name="compressionLevel">压缩等级(0 无 - 9 最高,默认 5)</param>
 /// <param name="zipMaxFile">压缩包内最多文件数量(-1不限)</param>
 /// <param name="blockSize">缓存大小(每次写入文件大小,默认 2048)</param>
 /// <param name="compressType">压缩方式(默认zip)</param>
 /// <returns></returns>
 public string[] CompressMulti(
     string[] sourceFileList,
     string zipDirectory,
     string zipName,
     bool overWrite            = true,
     string password           = "",
     int compressionLevel      = 5,
     int zipMaxFile            = -1,
     int blockSize             = 2048,
     CompressType compressType = null)
 {
     return(CompressFactory.GetProvider(compressType ?? CompressType.Zip)
            .CompressMulti(sourceFileList, zipDirectory, zipName, overWrite, password, compressionLevel, zipMaxFile,
                           blockSize));
 }
Example #10
0
    /// <summary>
    /// 标记一个文件夹一个资源包
    /// </summary>
    /// <param name="path">路径</param>
    /// <param name="prefix">AB包路径前缀</param>
    public static void MarkOneFloderOneBundle(string path, CompressType type = CompressType.LZMA)
    {
        string fullPath = EditorUtil.FixedWindowsPath(Application.dataPath + "/" + path);

        if (Directory.Exists(fullPath))
        {
            path = GetAssetBundleName(path, type);
            string        assetPath = EditorUtil.GetAssetsPath(fullPath);
            AssetImporter ai        = AssetImporter.GetAtPath(assetPath);
            ai.SetAssetBundleNameAndVariant(path, AssetBundleDef.ABSuffix);
        }
        else
        {
            Debug.LogError("标记文件夹出错,不存在的文件路径:" + fullPath);
        }
    }
Example #11
0
        /// <summary>
        /// Gzip/Deflate解压缩
        /// </summary>
        /// <param name="data">输入字节数组</param>
        /// <param name="model">压缩模式,默认Gzip</param>
        /// <returns>byte[] 解压缩后的字节数组</returns>
        public static byte[] decompress(byte[] data, CompressType model = CompressType.GZIP)
        {
            using (var ms = new MemoryStream(data))
            {
                var buffer = new MemoryStream();
                var block  = new byte[1024];
                switch (model)
                {
                case CompressType.GZIP:
                    using (var stream = new GZipStream(ms, CompressionMode.Decompress))
                    {
                        while (true)
                        {
                            var read = stream.Read(block, 0, block.Length);
                            if (read <= 0)
                            {
                                break;
                            }
                            buffer.Write(block, 0, read);
                        }
                    }
                    break;

                case CompressType.DEFLATE:
                    using (var stream = new DeflateStream(ms, CompressionMode.Decompress))
                    {
                        while (true)
                        {
                            var read = stream.Read(block, 0, block.Length);
                            if (read <= 0)
                            {
                                break;
                            }
                            buffer.Write(block, 0, read);
                        }
                    }
                    break;

                case CompressType.NONE:
                    return(data);

                default:
                    return(data);
                }
                return(buffer.ToArray());
            }
        }
Example #12
0
        /// <summary>
        /// 将result数据使用Json.NET序列化,并按指定的压缩模式压缩为一个字节数组
        /// </summary>
        /// <param name="result">响应结果数据</param>
        /// <param name="model">压缩模式</param>
        /// <returns>byte[] 压缩后的字节数组</returns>
        public static byte[] jsonWrite(object result, CompressType model)
        {
            using (var stream = new MemoryStream())
            {
                using (var streamWriter = new StreamWriter(stream, Encoding.UTF8))
                {
                    var writer = new JsonTextWriter(streamWriter)
                    {
                        Formatting = Formatting.Indented
                    };
                    new JsonSerializer().Serialize(writer, result);
                    streamWriter.Flush();

                    return(compress(stream.ToArray(), model));
                }
            }
        }
Example #13
0
        public NetxDecodeSetter(IServiceProvider container)
            : base(container)
        {
            var ssloption = container.GetRequiredService <IOptions <SslOption> >().Value;

            if (ssloption.IsUse)
            {
                Certificate   = ssloption.Certificate;
                domain        = ssloption.DoMain;
                SslStreamInit = ssloption.SslStreamInit;
                is_use_ssl    = true;
            }

            var compresstion = container.GetRequiredService <IOptions <CompressOption> >().Value;

            decodeType = compresstion.Mode;
        }
Example #14
0
    /// <summary>
    /// 标记指定路径下的所有子文件夹
    /// </summary>
    /// <param name="path">指定路径</param>
    /// <param name="prefix">AB包路径前缀</param>
    public static void MarkSubFloderOneBundle(string path, CompressType type = CompressType.LZMA)
    {
        string fullPath = EditorUtil.FixedWindowsPath(Application.dataPath + "/" + path);

        if (Directory.Exists(fullPath))
        {
            string[] paths = Directory.GetDirectories(fullPath);
            for (int i = 0; i < paths.Length; i++)
            {
                string tmpPath = EditorUtil.FixedWindowsPath(paths[i]).Replace(Application.dataPath + "/", string.Empty);
                MarkOneFloderOneBundle(tmpPath, type);
            }
        }
        else
        {
            Debug.LogError("标记子文件夹出错,不存在的文件路径:" + fullPath);
        }
    }
Example #15
0
        private static DataRecord GetData(byte[] input, string filename, CompressType compress)
        {
            if (compress == CompressType.Nothing)
            {
                return(new DataRecord()
                {
                    Data = input
                });
            }
            if (compress == CompressType.ByExtension && _noCompressExt.Contains(System.IO.Path.GetExtension(filename)))
            {
                return(new DataRecord()
                {
                    Data = input
                });
            }

            var cdata = new System.IO.MemoryStream();

            //Lzs.Encode(new System.IO.MemoryStream(input), cdata);
            byte[] lprops;
            using (var lzma = new SharpCompress.Compressors.LZMA.LzmaStream(new SharpCompress.Compressors.LZMA.LzmaEncoderProperties(), false, cdata)) {
                lzma.Write(input, 0, input.Length);
                lprops = lzma.Properties;
            }
            if (/*compress == CompressType.ByContent &&*/ (cdata.Length + lprops.Length + 8) > (input.Length * 10 / 8))
            {
                return(new DataRecord()
                {
                    Data = input
                });
            }

            byte[] data = new byte[cdata.Length + lprops.Length + 8];
            Array.Copy(BitConverter.GetBytes(input.Length), data, 4);
            Array.Copy(BitConverter.GetBytes(lprops.Length), 0, data, 4, 4);
            Array.Copy(lprops, 0, data, 8, lprops.Length);
            cdata.Position = 0;
            cdata.Read(data, lprops.Length + 8, (int)cdata.Length);
            return(new DataRecord()
            {
                Data = data, Compressed = true
            });
        }
Example #16
0
        //public static bool IsEncodingAccepted( HttpContext context )
        //{
        //    return IsEncodingAccepted ( context, GZIP );
        //}

        //private static bool IsEncodingAccepted( HttpContext context, string encoding )
        //{
        //    NameValueCollection headers = context.Request.Headers;
        //    return headers ["Accept-encoding"] != null && headers ["Accept-encoding"].Contains ( encoding );
        //}

        //private static void SetResponseCompressEncoding( HttpContext context, string encoding )
        //{
        //    context.Response.AppendHeader ( "Content-encoding", encoding );
        //}

        //public static void SetResponseCompressEncoding( HttpContext context )
        //{
        //    SetResponseCompressEncoding ( context, GZIP );
        //}

        public static void CompressBytes(ref byte[] compressBytes, CompressType compressType)
        {
            switch (compressType)
            {
            case CompressType.None:
                break;

            case CompressType.Deflate:
                compressBytes = StreamHelper.DeflateCompress(compressBytes);
                break;

            case CompressType.Gzip:
                compressBytes = StreamHelper.Compress(compressBytes);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Example #17
0
        //public static bool SupportGipCompress()
        //{
        //    string ua = HttpContext.Current.Request.UserAgent;
        //    if ( !string.IsNullOrEmpty ( ua ) )
        //    {
        //        ua = ua.ToLower ();
        //        if ( ua.IndexOf ( "msie 7" ) >= 0 )
        //        {
        //            return true;
        //        }
        //        if ( ua.IndexOf ( "msie" ) >= 0 )
        //        {
        //            return false;
        //        }
        //    }
        //    return true;
        //}

        public static void SetResponseCompressEncodingType(HttpContext context, CompressType compressType)
        {
            switch (compressType)
            {
            case CompressType.None:
                break;

            case CompressType.Deflate:
                context.Response.AppendHeader("Content-encoding", DEFLATE);
                break;

            case CompressType.Gzip:
                context.Response.AppendHeader("Content-encoding", GZIP);
                break;

            default:
                throw new ArgumentOutOfRangeException("compressType");
            }
        }
Example #18
0
        public static byte[] compress_auto(byte[] input, out CompressType usedType, CompressType allowedTypes = CompressType.ALL)
        {
            // Sanity checking...
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }
            if (allowedTypes == CompressType.NULL)
            {
                throw new ArgumentException("Allowed compression type cannot be NULL!", nameof(allowedTypes));
            }

            Dictionary <CompressType, byte[]> mapping = new Dictionary <CompressType, byte[]>();

            byte[] output = null;
            usedType = CompressType.NULL;

            if ((allowedTypes & CompressType.RAWW) == CompressType.RAWW)
            {
                mapping.Add(CompressType.RAWW, RAWW.compress(input));
            }
            if ((allowedTypes & CompressType.JDLZ) == CompressType.JDLZ)
            {
                mapping.Add(CompressType.JDLZ, JDLZ.compress(input));
            }

            int minLength = int.MaxValue;

            foreach (KeyValuePair <CompressType, byte[]> entry in mapping)
            {
                // NOTE: if the length is EQUAL TO the shortest one, we decide based on the complexity of that type's decompression.
                if ((entry.Value.Length < minLength) || (entry.Value.Length == minLength && entry.Key < usedType))
                {
                    minLength = entry.Value.Length;
                    output    = entry.Value;
                    usedType  = entry.Key;
                }
            }

            return(output);
        }
Example #19
0
        /// <summary>
        ///     解压缩数据流中的数据
        /// </summary>
        /// <param name="ms">要解压缩的数据流</param>
        /// <param name="type">解压缩使用的算法</param>
        /// <returns>返回解压缩后的数据流</returns>
        public static Stream UnCompressStream(this Stream ms, CompressType type)
        {
            Stream compressStream = null;

            MemoryStream resultMs = null;

            if (ms.CanSeek)
            {
                resultMs = new MemoryStream((int)ms.Length);
                ms.Seek(0, SeekOrigin.Begin);
            }
            else
            {
                resultMs = new MemoryStream(4096);
            }


            switch (type)
            {
            case CompressType.Zip_GZip:
                compressStream = new GZipStream(ms, CompressionMode.Decompress, true);
                StreamAbout.CopyTo(compressStream, resultMs);
                compressStream.Flush();
                compressStream.Close();
                break;

            case CompressType.Zip_Deflate:
                compressStream = new DeflateStream(ms, CompressionMode.Decompress, true);
                StreamAbout.CopyTo(compressStream, resultMs);
                compressStream.Flush();
                compressStream.Close();
                break;

            default:
                return(ms);
            }

            resultMs.Seek(0, SeekOrigin.Begin);

            return(resultMs);
        }
Example #20
0
        public string GetCompressionName(FIBITMAP dib)
        {
            long _compression;

            if (dib.IsNull)
            {
                throw new Exception("dib is empty - image haven't been loaded!");
            }

            //Searching tag in metadata.
            ImageMetadata iMetadata = new ImageMetadata(dib);

            foreach (MetadataModel metadataModel in iMetadata)
            {
                if (metadataModel.ToString() == "FIMD_EXIF_MAIN")
                {
                    try
                    {
                        long.TryParse((metadataModel.GetTag("Compression")?.Value as ushort[])?[0].ToString(), out _compression);
                    }
                    catch (Exception ex)
                    {
                        return("Unknown");
                    }


                    if (CompressType.ContainsKey(_compression))
                    {
                        string _compressionName;
                        CompressType.TryGetValue(_compression, out _compressionName);

                        if (_compressionName != null)
                        {
                            return(_compressionName);
                        }
                    }
                }
            }

            return("Unknown");
        }
Example #21
0
        private (string?encoding, ReadOnlyMemory <byte> data) CompressData(ReadOnlyMemory <byte> source,
                                                                           CompressType type)
        {
            _logger.LogTrace("compress type : {type}", type);
            if (type == CompressType.None)
            {
                return("utf8", source);
            }

            switch (type)
            {
            case CompressType.GZip:
                return(GzipStreamHelper.ContentEncoding, GzipStreamHelper.Compress(source));

            case CompressType.Deflate:
                return(DeflateStreamHelper.ContentEncoding, DeflateStreamHelper.Compress(source));

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }
        }
Example #22
0
 static void FetchBuildInfoList(List <string> folders, string searchPattern, CompressType compressType, BuildType buildType)
 {
     //包含所有资源的bundle
     for (int i = 0; i < folders.Count; i++)
     {
         if (!Directory.Exists(folders[i]))
         {
             continue;
         }
         string resDir = BMEditUtility.Relativity2Absolute(folders[i]);
         if (resDir == null)
         {
             continue;
         }
         BuildInfo buildInfo = FetchBuildInfo(resDir, searchPattern, buildType);
         buildInfo.buildName    = folders[i].EndsWith("/")?folders[i].Substring(0, folders[i].Length - 1):folders[i];
         buildInfo.buildType    = buildType;
         buildInfo.compressType = compressType;
         buildInfoList.Add(buildInfo);
     }
 }
Example #23
0
        /// <summary>
        /// Creates the compressor.
        /// </summary>
        /// <param name="compressType">Type of the compress.</param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">compressor</exception>
        public static ICompressor CreateCompressor(CompressType compressType)
        {
            if (_compressorTable.TryGetValue(compressType, out var compressor))
            {
                return(compressor);
            }

            var type = Type.GetType($"HiLoSocket.Compressor.Implements.{compressType.GetDescription( )}");

            if (type != null)
            {
                compressor = Activator.CreateInstance(type) as ICompressor;
                _compressorTable.Add(compressType, compressor);
            }

            if (compressor == null)
            {
                throw new InvalidOperationException($"無法建立對應 {nameof( compressor )} 的物件。");
            }

            return(compressor);
        }
Example #24
0
        public static CompressType GetCompressType(HttpContext context)
        {
            CompressType compressType         = CompressType.None;
            string       acceptEncodingString = context.Request.Headers ["Accept-encoding"];

            if (!string.IsNullOrEmpty(acceptEncodingString))
            {
                acceptEncodingString = acceptEncodingString.ToLower();
                BrowserType browserType = Browser();
                switch (browserType)
                {
                case BrowserType.Ie:
                    //if ( acceptEncodingString.IndexOf ( DEFLATE ) >= 0 )
                    //{
                    //    compressType = CompressType.Deflate;
                    //}
                    break;

                case BrowserType.Ie7:
                case BrowserType.Firefox:
                case BrowserType.Opera:
                case BrowserType.Safari:
                case BrowserType.Other:
                    if (acceptEncodingString.IndexOf(GZIP) >= 0)
                    {
                        compressType = CompressType.Gzip;
                    }
                    else if (acceptEncodingString.IndexOf(DEFLATE) >= 0)
                    {
                        compressType = CompressType.Deflate;
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            return(compressType);
        }
Example #25
0
        public static string Compress(string value, CompressType type)
        {
            try
            {
                if (value.Length <= GetDeflateDefaultValue())
                {
                    return(AddCompressMark(value, CompressType.Decompress));
                }
                byte[] buffer = Encoding.UTF8.GetBytes(value);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    Stream compressStream;

                    if (type == CompressType.CompressByZip)
                    {
                        compressStream = new GZipStream(memoryStream, CompressionMode.Compress, true);
                    }
                    else
                    {
                        compressStream = new DeflateStream(memoryStream, CompressionMode.Compress, true);
                    }

                    using (compressStream)
                    {
                        compressStream.Write(buffer, 0, buffer.Length);
                    }

                    return(AddCompressMark(Convert.ToBase64String(memoryStream.ToArray()), type));
                }
            }
            catch (InvalidDataException ex)
            {
                throw new Exception(ex.Message);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Example #26
0
        public static void CompressPage(HttpContext context)
        {
            CompressType compressType = GetCompressType(context);

            switch (compressType)
            {
            case CompressType.None:
                break;

            case CompressType.Deflate:
                context.Response.Filter = new DeflateStream(context.Response.Filter, CompressionMode.Compress);
                context.Response.AppendHeader("Content-encoding", DEFLATE);
                break;

            case CompressType.Gzip:
                context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
                context.Response.AppendHeader("Content-encoding", GZIP);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Example #27
0
        private Boolean TryGetCompressTypeHeader(out CompressType compressType)
        {
            if (!this.HttpResponseMessage.Headers.TryGetValues(LogHeaders.CompressType, out var compressTypes))
            {
                // No header
                compressType = CompressType.None;
                return(false);
            }

            var compressTypeValue = compressTypes.FirstOrDefault(); // Fault tolerance (TODO: Show warns about duplicated keys)

            if (compressTypeValue.IsEmpty())
            {
                // Header is empty
                compressType = CompressType.None;
                return(false);
            }

            // Convert value to enum
            return(Enum.TryParse(compressTypeValue, true, out compressType)
                ? true
                : throw new ArgumentException($"Compress type [{compressTypeValue}] is not supported.", LogHeaders.CompressType));
        }
Example #28
0
        private (string?encoding, byte[] data) CompressData(byte[] source, CompressType type)
        {
            _logger.LogTrace("compress type : {type}", type);
            if (type == CompressType.None)
            {
                return("utf8", source);
            }

            using var input = new MemoryStream();
            input.Write(source, 0, source.Length);
            input.Seek(0, SeekOrigin.Begin);
            switch (type)
            {
            case CompressType.GZip:
                return(GzipStreamHelper.ContentEncoding, GzipStreamHelper.Compress(input));

            case CompressType.Deflate:
                return(DeflateStreamHelper.ContentEncoding, DeflateStreamHelper.Compress(input));

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }
        }
Example #29
0
        /// <summary>
        ///     压缩数据流
        /// </summary>
        /// <param name="ms">要压缩的数据流</param>
        /// <param name="type">压缩使用的算法</param>
        /// <returns>返回压缩后的数据流</returns>
        public static Stream CompressStream(this Stream ms, CompressType type)
        {
            Stream compressStream = null;

            var resultMs = new MemoryStream(4096);


            if (ms.CanSeek)
            {
                ms.Seek(0, SeekOrigin.Begin);
            }

            switch (type)
            {
            case CompressType.Zip_GZip:
                compressStream = new GZipStream(resultMs, CompressionMode.Compress, true);
                StreamAbout.CopyTo(ms, compressStream);
                compressStream.Flush();
                compressStream.Close();
                break;

            case CompressType.Zip_Deflate:
                compressStream = new DeflateStream(resultMs, CompressionMode.Compress, true);
                StreamAbout.CopyTo(ms, compressStream);
                compressStream.Flush();
                compressStream.Close();
                break;

            default:
                return(ms);
            }

            resultMs.Seek(0, SeekOrigin.Begin);

            return(resultMs);
        }
Example #30
0
        public IRequestBuilder <HttpRequestMessage> Compress(CompressType compressType)
        {
            if (this.SerializedContent == null)
            {
                throw new InvalidOperationException("Nothing to compress.");
            }

            switch (compressType)
            {
            case CompressType.None:
            {
                break;
            }

            case CompressType.Lz4:
            {
                this.SetCompressType("lz4");
                this.content = LZ4Codec.Encode(this.SerializedContent, 0, this.SerializedContent.Length);
                break;
            }

            case CompressType.Deflate:
            {
                this.SetCompressType("deflate");
                this.content = ZlibStream.CompressBuffer(this.SerializedContent);
                break;
            }

            default:
            {
                throw new ArgumentOutOfRangeException(nameof(compressType), compressType, null);
            }
            }

            return(this);
        }
Example #31
0
 /// <summary>
 /// 
 /// </summary>
 private Compressor()
 {
     _compressType = CompressType.Deflate;
 }
Example #32
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="compressType"></param>
 private Compressor(CompressType compressType)
 {
     _compressType = compressType;
 }
Example #33
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="inputString"></param>
 /// <param name="compressType"></param>
 /// <returns></returns>
 public static byte[] Compress(string inputString, CompressType compressType)
 {
     return new Compressor(compressType).InternalCompress(inputString);
 }
Example #34
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="inputData"></param>
 /// <param name="compressType"></param>
 /// <returns></returns>
 public static byte[] Compress(byte[] inputData, CompressType compressType)
 {
     return new Compressor(compressType).InternalCompress(inputData);
 }
 /// <remarks/>
 public void IDExchangeAsync(string InputListKey, IDOperationType Operation, PCIDType OutputType, string OutputSourceName, IDOutputFormatType OutputFormat, string ToWebEnv, CompressType eCompress, bool eCompressSpecified) {
     this.IDExchangeAsync(InputListKey, Operation, OutputType, OutputSourceName, OutputFormat, ToWebEnv, eCompress, eCompressSpecified, null);
 }
Example #36
0
        /// <summary>
        /// 从选择的文件压缩Css脚本
        /// </summary>
        /// <param name="cssFilesPath"></param>
        /// <param name="resultRender"></param>
        /// <param name="ct"></param>
        private async void CompressCssCodeFromFiles(IEnumerable<string> cssFilesPath, TextBox resultRender, CompressType ct)
        {
            int toBase64ImgMaxSize = this.css_checkBox_1.Checked ? (int)this.css_numericUpDown_1.Value * 1024 : 0;

            if (ct == CompressType.FileSingle)
            {
                foreach (var cssFile in cssFilesPath)
                {
                    resultRender.Text += string.Format("正在处理文件 {0} \r\n", cssFile);
                    string resultCode = await cssFile.CompressCssFromFile(string.Empty, toBase64ImgMaxSize);
                    if (!string.IsNullOrEmpty(resultCode))
                    {
                        string saveFilePath = new List<string> { cssFile }.GetCompressFileName();
                        if (!string.IsNullOrEmpty(saveFilePath))
                        {
                            await saveFilePath.WriteTxtFile(resultCode);
                            resultRender.Text += string.Format("压缩完成,已经保存至文件 {0} \r\n", saveFilePath);
                        }
                        else
                        {
                            resultRender.Text += string.Format("*** 压缩完成,保存文件失败! \r\n");
                        }
                    }
                    else
                    {
                        resultRender.Text += string.Format("*** 压缩失败,请检查文件及内容! \r\n");
                    }
                    resultRender.Text += string.Format("====================================================================\r\n\r\n");
                }
            }
            else
            {
                StringBuilder jsBuilder = new StringBuilder();
                string resultCode;

                foreach (var cssFile in cssFilesPath)
                {
                    resultRender.Text += string.Format("正在处理文件 {0} \r\n", cssFile);
                    resultCode = await cssFile.CompressCssFromFile(string.Empty, toBase64ImgMaxSize);
                    if (!string.IsNullOrEmpty(resultCode))
                    {
                        resultRender.Text += "压缩完成 \r\n";
                        if (ct == CompressType.MergeAndCompressed)
                        {
                            jsBuilder.Append(resultCode);
                        }
                        else
                        {
                            jsBuilder.AppendLine("/* " + Path.GetFileName(cssFile) + " */");
                            jsBuilder.AppendLine(resultCode);
                        }
                    }
                    else
                    {
                        resultRender.Text += string.Format("*** 压缩失败,请检查文件及内容! \r\n");
                    }
                    resultRender.Text += string.Format("-------------------------------\r\n");
                }

                resultRender.Text += "\r\n============== 文件读取并压缩完成!开始合并及保存 ==============\r\n";
                resultCode = jsBuilder.ToString();

                jsBuilder.Clear();
                jsBuilder = null;

                string saveFilePath = cssFilesPath.GetCompressFileName();
                if (!string.IsNullOrEmpty(saveFilePath))
                {
                    await saveFilePath.WriteTxtFile(resultCode);
                    resultRender.Text += string.Format("任务完成,已经保存至文件 {0} \r\n", saveFilePath);
                }
                else
                {
                    resultRender.Text += string.Format("*** 保存文件失败! \r\n");
                }
            }
        }
 /// <remarks/>
 public void ScoreMatrixAsync(string ListKey, string SecondaryListKey, ScoreTypeType ScoreType, MatrixFormatType MatrixFormat, CompressType eCompress, bool eCompressSpecified, int N3DConformers, bool N3DConformersSpecified, bool No3DParent, bool No3DParentSpecified, object userState) {
     if ((this.ScoreMatrixOperationCompleted == null)) {
         this.ScoreMatrixOperationCompleted = new System.Threading.SendOrPostCallback(this.OnScoreMatrixOperationCompleted);
     }
     this.InvokeAsync("ScoreMatrix", new object[] {
                 ListKey,
                 SecondaryListKey,
                 ScoreType,
                 MatrixFormat,
                 eCompress,
                 eCompressSpecified,
                 N3DConformers,
                 N3DConformersSpecified,
                 No3DParent,
                 No3DParentSpecified}, this.ScoreMatrixOperationCompleted, userState);
 }
 public string AssayDownload(string AssayKey, AssayFormatType AssayFormat, CompressType eCompress, [System.Xml.Serialization.XmlIgnoreAttribute()] bool eCompressSpecified) {
     object[] results = this.Invoke("AssayDownload", new object[] {
                 AssayKey,
                 AssayFormat,
                 eCompress,
                 eCompressSpecified});
     return ((string)(results[0]));
 }
 /// <remarks/>
 public void AssayDownloadAsync(string AssayKey, AssayFormatType AssayFormat, CompressType eCompress, bool eCompressSpecified) {
     this.AssayDownloadAsync(AssayKey, AssayFormat, eCompress, eCompressSpecified, null);
 }
 /// <remarks/>
 public void AssayDownloadAsync(string AssayKey, AssayFormatType AssayFormat, CompressType eCompress, bool eCompressSpecified, object userState) {
     if ((this.AssayDownloadOperationCompleted == null)) {
         this.AssayDownloadOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAssayDownloadOperationCompleted);
     }
     this.InvokeAsync("AssayDownload", new object[] {
                 AssayKey,
                 AssayFormat,
                 eCompress,
                 eCompressSpecified}, this.AssayDownloadOperationCompleted, userState);
 }
 /// <remarks/>
 public void DownloadAsync(string ListKey, FormatType eFormat, CompressType eCompress, bool eCompressSpecified, bool Use3D, bool Use3DSpecified, int N3DConformers, bool N3DConformersSpecified, bool SynchronousSingleRecord, bool SynchronousSingleRecordSpecified) {
     this.DownloadAsync(ListKey, eFormat, eCompress, eCompressSpecified, Use3D, Use3DSpecified, N3DConformers, N3DConformersSpecified, SynchronousSingleRecord, SynchronousSingleRecordSpecified, null);
 }
 /// <remarks/>
 public void DownloadAsync(string ListKey, FormatType eFormat, CompressType eCompress, bool eCompressSpecified, bool Use3D, bool Use3DSpecified, int N3DConformers, bool N3DConformersSpecified, bool SynchronousSingleRecord, bool SynchronousSingleRecordSpecified, object userState) {
     if ((this.DownloadOperationCompleted == null)) {
         this.DownloadOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDownloadOperationCompleted);
     }
     this.InvokeAsync("Download", new object[] {
                 ListKey,
                 eFormat,
                 eCompress,
                 eCompressSpecified,
                 Use3D,
                 Use3DSpecified,
                 N3DConformers,
                 N3DConformersSpecified,
                 SynchronousSingleRecord,
                 SynchronousSingleRecordSpecified}, this.DownloadOperationCompleted, userState);
 }
 /// <remarks/>
 public void IDExchangeAsync(string InputListKey, IDOperationType Operation, PCIDType OutputType, string OutputSourceName, IDOutputFormatType OutputFormat, string ToWebEnv, CompressType eCompress, bool eCompressSpecified, object userState) {
     if ((this.IDExchangeOperationCompleted == null)) {
         this.IDExchangeOperationCompleted = new System.Threading.SendOrPostCallback(this.OnIDExchangeOperationCompleted);
     }
     this.InvokeAsync("IDExchange", new object[] {
                 InputListKey,
                 Operation,
                 OutputType,
                 OutputSourceName,
                 OutputFormat,
                 ToWebEnv,
                 eCompress,
                 eCompressSpecified}, this.IDExchangeOperationCompleted, userState);
 }
Example #44
0
        public byte[,] parse(CompressType compress, uint offset, bool fixAlphaMap = true)
        {
            byte[,] alphaMap = new byte[64, 64];
            if (compress == CompressType.COMPRESSED)
            {
                // Compressed.
                uint intOffset = 0;
                while (intOffset < 4096)
                {
                    byte read = data[offset];
                    bool mode = (read & 0x80) == 0x80; // true: Fill, false: copy.
                    int val = read & 0x7F;
                    offset++;

                    for (int v = 0; v < val; v++)
                    {
                        if (intOffset == 4096) break; // Map full. Job's done.
                        byte temp = data[offset];
                        alphaMap[intOffset / 64, intOffset % 64] = temp;
                        intOffset++;

                        if (!mode)
                            offset++;
                    }

                    if (mode)
                        offset++;
                }
            }
            else if (compress == CompressType.UNCOMPRESSED_2048)
            {
                // No compression, 4-bit values.
                uint intOffset = 0;
                for (int i = 0; i < 2048; i++)
                {
                    byte val = data[offset];
                    byte a = (byte)(val & 0x0F);
                    byte b = (byte)((val & 0xF0) >> 4);

                    alphaMap[intOffset / 64, intOffset % 64] = (byte) (a * 17);
                    intOffset++;

                    alphaMap[intOffset / 64, intOffset % 64] = (byte)(b * 17);
                    intOffset++;

                    offset++;
                }
            }
            else if (compress == CompressType.UNCOMPRESSED_4096)
            {
                // No compression, full data.
                for (int x = 0; x < 64; x++)
                {
                    for (int y = 0; y < 64; y++)
                    {
                        alphaMap[x, y] = data[offset];
                        offset++;
                    }
                }
            }

            if (fixAlphaMap)
            {
                for (int i = 0; i < 64; i++)
                {
                    alphaMap[i, 63] = alphaMap[i, 62];
                    alphaMap[63, i] = alphaMap[62, i];
                }
            }

            return alphaMap;
        }
 /// <remarks/>
 public void ScoreMatrixAsync(string ListKey, string SecondaryListKey, ScoreTypeType ScoreType, MatrixFormatType MatrixFormat, CompressType eCompress, bool eCompressSpecified, int N3DConformers, bool N3DConformersSpecified, bool No3DParent, bool No3DParentSpecified) {
     this.ScoreMatrixAsync(ListKey, SecondaryListKey, ScoreType, MatrixFormat, eCompress, eCompressSpecified, N3DConformers, N3DConformersSpecified, No3DParent, No3DParentSpecified, null);
 }
Example #46
0
        /// <summary>
        /// 从选择的文件压缩JS脚本
        /// </summary>
        /// <param name="jsFilesPath"></param>
        /// <param name="resultRender"></param>
        /// <param name="ct"></param>
        private async void CompressjsCodeFromFiles(IEnumerable<string> jsFilesPath, TextBox resultRender, CompressType ct)
        {
            #region CompressType.FileSingle

            if (ct == CompressType.FileSingle)
            {
                foreach (var jsFile in jsFilesPath)
                {
                    resultRender.Text += string.Format("正在处理文件 {0} \r\n", jsFile);
                    string sourceCode = await jsFile.ReadFileText();
                    if (!string.IsNullOrEmpty(sourceCode))
                    {
                        string resultCode = await sourceCode.ComoressJsCode();
                        if (!string.IsNullOrEmpty(resultCode) && !sourceCode.Equals(resultCode))
                        {
                            string saveFilePath = new List<string> { jsFile }.GetCompressFileName();
                            if (!string.IsNullOrEmpty(saveFilePath))
                            {
                                await saveFilePath.WriteTxtFile(resultCode);
                                resultRender.Text += string.Format("压缩完成,已经保存至文件 {0} \r\n", saveFilePath);
                            }
                            else
                            {
                                resultRender.Text += string.Format("*** 压缩完成,保存文件失败! \r\n");
                            }
                        }
                        else
                        {
                            resultRender.Text += string.Format("*** 压缩失败,请检查文件及内容! \r\n");
                        }
                    }
                    else
                    {
                        resultRender.Text += string.Format("*** 读取失败,请检查文件及内容! \r\n");
                    }
                    resultRender.Text += string.Format("====================================================================\r\n\r\n");
                }
            }

            #endregion 

            #region CompressType.MergeAndCompressed

            if (ct == CompressType.MergeAndCompressed)
            {
                StringBuilder jsBuilder = new StringBuilder();
                string sourceCode;
                foreach (var jsFile in jsFilesPath)
                {
                    resultRender.Text += string.Format("正在读取文件 {0} \r\n", jsFile);
                    sourceCode = await jsFile.ReadFileText();
                    if (!string.IsNullOrEmpty(sourceCode))
                    {
                        jsBuilder.AppendLine(sourceCode);
                        resultRender.Text += "读取完成!\r\n";
                    }
                    else
                    {
                        resultRender.Text += string.Format("*** 读取失败,请检查文件及内容! \r\n");
                    }
                    resultRender.Text += string.Format("-------------------------------\r\n");
                }

                resultRender.Text += "\r\n============== 文件读取完成!开始压缩 ==============\r\n";
                sourceCode = jsBuilder.ToString();

                jsBuilder.Clear();
                jsBuilder = null;

                string resultCode = await sourceCode.ComoressJsCode();
                if (!string.IsNullOrEmpty(resultCode) && !sourceCode.Equals(resultCode))
                {
                    string saveFilePath = jsFilesPath.GetCompressFileName();
                    if (!string.IsNullOrEmpty(saveFilePath))
                    {
                        await saveFilePath.WriteTxtFile(resultCode);
                        resultRender.Text += string.Format("压缩完成,已经保存至文件 {0} \r\n", saveFilePath);
                    }
                    else
                    {
                        resultRender.Text += string.Format("*** 压缩完成,保存文件失败! \r\n");
                    }
                }
                else
                {
                    resultRender.Text += string.Format("*** 压缩失败,请检查文件及内容! \r\n");
                }
            }

            #endregion 

            #region CompressType.CompressedAndMerge

            if (ct == CompressType.CompressedAndMerge)
            {
                StringBuilder jsBuilder = new StringBuilder();
                string sourceCode, resultCode;

                foreach (var jsFile in jsFilesPath)
                {
                    resultRender.Text += string.Format("正在处理文件 {0} \r\n", jsFile);
                    sourceCode = await jsFile.ReadFileText();
                    if (!string.IsNullOrEmpty(sourceCode))
                    {
                        resultCode = await sourceCode.ComoressJsCode();
                        if (!string.IsNullOrEmpty(resultCode) && !sourceCode.Equals(resultCode))
                        {
                            resultRender.Text += "压缩完成 \r\n";
                            jsBuilder.AppendLine("//" + Path.GetFileName(jsFile));
                            jsBuilder.AppendLine(resultCode);
                        }
                        else
                        {
                            resultRender.Text += string.Format("*** 压缩失败,请检查文件及内容! \r\n");
                        }
                    }
                    else
                    {
                        resultRender.Text += string.Format("*** 读取失败,请检查文件及内容! \r\n");
                    }
                    resultRender.Text += string.Format("-------------------------------\r\n");
                }

                resultRender.Text += "\r\n============== 文件读取并压缩完成!开始合并及保存 ==============\r\n";
                resultCode = jsBuilder.ToString();

                jsBuilder.Clear();
                jsBuilder = null;

                string saveFilePath = jsFilesPath.GetCompressFileName();
                if (!string.IsNullOrEmpty(saveFilePath))
                {
                    await saveFilePath.WriteTxtFile(resultCode);
                    resultRender.Text += string.Format("合并完成,已经保存至文件 {0} \r\n", saveFilePath);
                }
                else
                {
                    resultRender.Text += string.Format("*** 保存文件失败! \r\n");
                }
            }

            #endregion 
        }
 public string ScoreMatrix(string ListKey, string SecondaryListKey, ScoreTypeType ScoreType, MatrixFormatType MatrixFormat, CompressType eCompress, [System.Xml.Serialization.XmlIgnoreAttribute()] bool eCompressSpecified, int N3DConformers, [System.Xml.Serialization.XmlIgnoreAttribute()] bool N3DConformersSpecified, bool No3DParent, [System.Xml.Serialization.XmlIgnoreAttribute()] bool No3DParentSpecified) {
     object[] results = this.Invoke("ScoreMatrix", new object[] {
                 ListKey,
                 SecondaryListKey,
                 ScoreType,
                 MatrixFormat,
                 eCompress,
                 eCompressSpecified,
                 N3DConformers,
                 N3DConformersSpecified,
                 No3DParent,
                 No3DParentSpecified});
     return ((string)(results[0]));
 }
 public string Download(string ListKey, FormatType eFormat, CompressType eCompress, [System.Xml.Serialization.XmlIgnoreAttribute()] bool eCompressSpecified, bool Use3D, [System.Xml.Serialization.XmlIgnoreAttribute()] bool Use3DSpecified, int N3DConformers, [System.Xml.Serialization.XmlIgnoreAttribute()] bool N3DConformersSpecified, bool SynchronousSingleRecord, [System.Xml.Serialization.XmlIgnoreAttribute()] bool SynchronousSingleRecordSpecified, out DataBlobType DataBlob) {
     object[] results = this.Invoke("Download", new object[] {
                 ListKey,
                 eFormat,
                 eCompress,
                 eCompressSpecified,
                 Use3D,
                 Use3DSpecified,
                 N3DConformers,
                 N3DConformersSpecified,
                 SynchronousSingleRecord,
                 SynchronousSingleRecordSpecified});
     DataBlob = ((DataBlobType)(results[1]));
     return ((string)(results[0]));
 }
 public string IDExchange(string InputListKey, IDOperationType Operation, PCIDType OutputType, string OutputSourceName, IDOutputFormatType OutputFormat, string ToWebEnv, CompressType eCompress, [System.Xml.Serialization.XmlIgnoreAttribute()] bool eCompressSpecified, out string DownloadKey) {
     object[] results = this.Invoke("IDExchange", new object[] {
                 InputListKey,
                 Operation,
                 OutputType,
                 OutputSourceName,
                 OutputFormat,
                 ToWebEnv,
                 eCompress,
                 eCompressSpecified});
     DownloadKey = ((string)(results[1]));
     return ((string)(results[0]));
 }