示例#1
0
        public void TestDecompressData2()
        {
            string base64Data = "IwgMIyKA";
            var    data       = LZString.decompressFromBase64(base64Data);

            Assert.AreEqual("1110111111111111", data);
        }
        public void CompatibilityDecompressUInt8ArrayFromNode(LZStringTestCase test)
        {
            var compress   = test.CompressedUInt8Array;
            var uncompress = LZString.DecompressFromUint8Array(compress);

            Assert.That(uncompress, Is.EqualTo(test.Uncompressed));
        }
示例#3
0
        public void TestCompressData()
        {
            string data       = "1111111111111111";
            string base64Data = LZString.compressToBase64(data);

            Assert.AreEqual("Iw1/Ew==", base64Data);
        }
示例#4
0
        public string GetDataDirect(string actionName)
        {
            // get all of data.
            var _ds = new Select().SelectLists(actionName);

            return(LZString.CompressToUTF16(_ds.GetXml()));
        }
示例#5
0
        public void UrlEncode()
        {
            //check that all chars are URL safe
            {
                var sb   = new StringBuilder();
                var rand = new Random();
                for (var i = 0; i < 1000; i++)
                {
                    sb.Append(rand.NextDouble()).Append(' ');
                }
                var testString = sb.ToString();

                var compressed = LZString.CompressToEncodedUriComponent(testString);
                Assert.IsFalse(compressed.Contains("="));
                Assert.IsFalse(compressed.Contains("/"));
                var decompressed = LZString.DecompressFromEncodedUriComponent(compressed);
                Assert.AreEqual(testString, decompressed);
            }

            //check that + and ' ' are interchangeable in decompression
            {
                var decompressed = "During tattooing, ink is injected into the skin, initiating an immune response, and cells called \"macrophages\" move into the area and \"eat up\" the ink. The macrophages carry some of the ink to the body's lymph nodes, but some that are filled with ink stay put, embedded in the skin. That's what makes the tattoo visible under the skin. Dalhousie Uiversity's Alec Falkenham is developing a topical cream that works by targeting the macrophages that have remained at the site of the tattoo. New macrophages move in to consume the previously pigment-filled macrophages and then migrate to the lymph nodes, eventually taking all the dye with them. \"When comparing it to laser-based tattoo removal, in which you see the burns, the scarring, the blisters, in this case, we've designed a drug that doesn't really have much off-target effect,\" he said. \"We're not targeting any of the normal skin cells, so you won\'t see a lot of inflammation. In fact, based on the process that we're actually using, we don't think there will be any inflammation at all and it would actually be anti-inflammatory.";
                var compressed   = "CIVwTglgdg5gBAFwIYIQezdGAaO0DWeAznlAFYCmAxghQCanqIAWFcR 0u0ECEKWOEih4AtqJBQ2YCkQAOaKEQq5hDKhQA2mklSTb6cAESikVMGjnMkMWUbii0ANzbQmCVkJlIhUBkYoUOBA5ew9XKHwAOjgAFU9Tc0trW10kMDAAT3Y0UTY0ADMWCMJ3TwAjNDpMgHISTUzRKzgoKtlccpAEHLyWIPS2AogDBgB3XmZSQiJkbLku3ApRcvo6Q2hi9k4oGPiUOrhR627TfFlN5FQMOCcIIghyzTZJNbBNjmgY4H1mNBB7tgAVQgLjA9wQtRIAEEnlQ4AAxfRnKDWUTEOBrFyaSyCHzoOQQPSaODmQJojxBUZoMD4EjlbLIMC2PiwTaJCxWGznCndawuOAyUzQQxBcLsXj5Ipiy7oNAxAByFFGDjMHJS50c-I2TCoiiIIF6YrkMlufyIDTgBJgeSgCAAtEMRiqkpzUr4GOERKIIDAwCg2GU2A0mpNWmsiIsXLaQPoLchtvBY5tqmxxh5iqIYkYAOqsES6prpQS8RBoOCaJDKMB28qVwwy66C5z6bgiI6EyaZP7sCgBirgJS4MVEPQZLBDiqaO60MGtlh3El13CjCg1fnhn1SBg OhgEDwHkYtCyKA1brebTZPlsCRUSaFAp2xnMuAUAoFagIbD2TxEJAQOgs2zVcZBaNBumfCgWUTKBskKTZWjAUxiQ fMtB0XAiDLLsQEORQzx7NgfGxbp4OgAoK3EARFBiABJEQCjML84FrZQGEUTZjTQDQiBIQ8VxqUCmJjS9gnuWBlzYOh8Ig5gCGKUDxm0FiiNg0gKKQKi A4-plLUPBuipEBNG3GgRItFZfD4O1yMo0x0CyKIgAAA$$";
                var decomp2      = LZString.DecompressFromEncodedUriComponent(compressed);
                Assert.AreEqual(decompressed, decomp2);
            }
        }
示例#6
0
        public string GetSelect2()
        {
            HttpContext Context    = HttpContext.Current;
            string      pageNum    = Context.Request["pageNum"],
                        pageSize   = Context.Request["pageSize"],
                        searchTerm = Context.Request["searchTerm"],
                        fnName     = Context.Request["fnName"],
                        names      = Context.Request["names"],
                        values     = Context.Request["values"];

            // grid static parameters
            string[] defaultNames = { "pageNum", "pageSize", "key" },
            defaultValues = { pageNum, pageSize, searchTerm },

            // get dynamic more parameters from user
            addtionNames  = string.IsNullOrEmpty(names) ? new string[0] : names.Split('~'),
            addtionValues = string.IsNullOrEmpty(values) ? new string[0] : values.Split('~'),

            // merge all parameters (union)
            namesAll  = defaultNames.Concat(addtionNames).ToArray(),
            valuesAll = defaultValues.Concat(addtionValues).ToArray();

            var _ds = new Select().SelectLists(fnName, namesAll, valuesAll);

            return(LZString.CompressToUTF16(_ds.GetXml()));
        }
示例#7
0
文件: WebBv.cs 项目: yymqwl/Barrage
        protected override void OnMessage(MessageEventArgs e)
        {
            //Loger.Debug(ID+ $"OnMessage{e.Data.Length}:" + e.Data);
            //Loger.Debug(LZString.Decompress(e.Data));
            try
            {
                var     Json_Data = LZString.DecompressFromUint8Array(e.RawData);
                var     MsgBody   = JObject.Parse(Json_Data);
                var     id        = MsgBody.GetValue("Id").Value <ushort>();
                JObject data      = MsgBody.GetValue("Data").Value <JObject>();

                IWebSocketSession session;
                this.Sessions.TryGetSession(ID, out session);


                GameMainEntry.Instance.WebServerModule.Dispather.Dispatch(session, new MessageInfo_Json(id, data));

                /*
                 * OneThreadSynchronizationContext.Instance.Post((obj) =>
                 * {
                 *  GameMainEntry.Instance.WebServerModule.Dispather.Dispatch(session, new MessageInfo_Json(id, data));//拉到主线程处理
                 * }, null);
                 */
            }
            catch (Exception ex)
            {
                Loger.Error($"{ID} OnMessage:" + ex.ToString());
            }
            base.OnMessage(e);
        }
        /// <summary>
        /// 重写  控制器的 action 执行方法
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            //注意 web api 在本设计中 ,不让设置 页面标识 Cookie 。增加这个Cookie 是为了防止采集和蜘蛛
            if (context.Controller is BaseApiController)
            {
                base.OnActionExecuting(context);
                return;
            }

            //1监测是否有了必须的Cookie标识  如果没有 那么追加
            var cookieWebbrowserSign = context.HttpContext.GetCookie <string>(Contanst.Cookie_Key_BrowserSign);

            if (string.IsNullOrEmpty(cookieWebbrowserSign))
            {
                cookieWebbrowserSign = string.Concat(WorkContext.SiteName, "|", DateTime.Now.ToOfenTimeString());
                string encodedSign = LZString.Compress(cookieWebbrowserSign, true);
                //将加密后的cookie  写入到响应客户端
                string domain = null;
                //string webStatus = ConfigHelper.AppSettingsConfiguration.GetConfig("WebStatus");
                //判断是否为正式环境
                if (WorkContext.HostingEnvironment.IsProduction())
                {
                    //正式环境cookie 过期为1天
                    domain = Contanst.Global_Site_Domain_Cookie;
                    context.HttpContext.SetCookie <string>(domain, Contanst.Cookie_Key_BrowserSign, encodedSign, 1, true);
                }
                else
                {
                    //测试环境 cookie 不过期
                    context.HttpContext.SetCookie <string>(domain, Contanst.Cookie_Key_BrowserSign, encodedSign, true);
                }
            }
            base.OnActionExecuting(context);
        }
        public void CompatibilityCompressUInt8ArrayFromCSharp(LZStringTestCase test)
        {
            var compress   = LZString.CompressToUint8Array(test.Uncompressed);
            var uncompress = test.Uncompressed;

            Assert.That(uncompress, Is.EqualTo(test.Uncompressed));
        }
示例#10
0
        /// <summary>
        /// 验证是否是合法的请求标识
        /// </summary>
        /// <returns></returns>
        public static bool CheckIsValidRequestSign(string sign)
        {
            bool result = false;

            if (string.IsNullOrEmpty(sign))
            {
                return(false);
            }
            try
            {
                //1 先解密
                string deCodeString = LZString.Decompress(sign, true);
                //2 获取里面的时间戳内容对应的时间
                DateTime clientTimeSign = deCodeString.ToLong().ConvertUnixTimeTokenToDateTime();
                //3 比较时间是否超出 2分钟 超过2分钟的请求sign 标志为失效的请求
                if (DateTime.Now.Subtract(clientTimeSign).TotalSeconds <= SignTimeOut)
                {
                    result = true;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

            return(result);
        }
示例#11
0
 public string Decompress(string data)
 {
     if (Compression)
     {
         return(LZString.DecompressFromUTF16(data));
     }
     return(data);
 }
示例#12
0
        private void LoadSaveFile(string strFile)
        {
            StreamReader sr       = new StreamReader(strFile);
            string       textFile = LZString.DecompressFromBase64(sr.ReadToEnd());

            textBoxSaveFileContent.Text = textFile;
            sr.Close();
        }
        public void CompatibilityCompressUTF16FromCSharp(LZStringTestCase test)
        {
            var compress   = LZString.CompressToUTF16(test.Uncompressed);
            var uncompress = RunNodeLzString("decompressFromUTF16", compress);

            Console.WriteLine("c# compression result:");
            Console.WriteLine(compress);
            Assert.That(uncompress, Is.EqualTo(test.Uncompressed));
        }
示例#14
0
        public string Compress(string data)
        {
            if (Compression)
            {
                return(LZString.CompressToUTF16(data));
            }

            return(data);
        }
示例#15
0
        public static byte[] Create_Msg_Json <T>(NetOpCode id, T msg) where T : IMessage
        {
            JObject msg_json = new JObject();

            msg_json["Id"]   = (ushort)id;
            msg_json["Data"] = JObject.FromObject(msg);
            var str_msg = JsonConvert.SerializeObject(msg_json);

            return(LZString.CompressToUint8Array(str_msg));
        }
示例#16
0
        public static byte[] Create_Msg_Json(NetOpCode id, JObject data)
        {
            JObject msg_json = new JObject();

            msg_json["Id"]   = (ushort)id;
            msg_json["Data"] = data;
            var str_msg = JsonConvert.SerializeObject(msg_json);

            return(LZString.CompressToUint8Array(str_msg));
        }
示例#17
0
        public string GetDataByID(string actionName, string value)
        {
            // create filter parameters
            string[,] _params = { { "Id", value } };

            // get all of data.
            var _ds = new Select().SelectLists(actionName, _params);

            return(LZString.CompressToUTF16(_ds.GetXml()));
        }
示例#18
0
        public async Task writeMp3(Voice value)
        {
            var decompressed = LZString.decompressFromUTF16(value.base64);

            byte[] data = Convert.FromBase64String(decompressed);
            var    path = HttpContext.Current.Server.MapPath("~/uploads/Webinar/" + value.Token + "/Voice.mp3");

            using (FileStream st = new FileStream(path, FileMode.Append))
            {
                await st.WriteAsync(data, 0, data.Length);
            }
        }
示例#19
0
        public string GetDataList(DataListModel param)
        {
            if (param == null)
            {
                return("Error!! null paramters");
            }

            // get all of data.
            var _ds = new Select().SelectLists(param.actionName, param.names, param.values);

            return(LZString.CompressToUTF16(_ds.GetXml()));
        }
示例#20
0
 public async Task writeWebp(CanvasRec value)
 {
     foreach (var item in value.frames)
     {
         var    decompressed = LZString.decompressFromUTF16(item.F);
         byte[] data         = Convert.FromBase64String(decompressed);
         var    path         = HttpContext.Current.Server.MapPath("~/Uploads/Webinar/" + value.Token + "/Frames/" + item.name + ".jpg");
         using (FileStream st = new FileStream(path, FileMode.Create))
         {
             await st.WriteAsync(data, 0, data.Length);
         }
     }
 }
示例#21
0
        private static bool TryPrepareSharplabPreview(string url, int markdownLength, out string?preview)
        {
            if (!url.Contains("#v2:"))
            {
                preview = null;
                return(false);
            }

            try
            {
                // Decode the compressed code from the URL payload
                var base64Text = url.Substring(url.IndexOf("#v2:") + "#v2:".Length);
                var plainText  = LZString.DecompressFromBase64(base64Text);

                // Extract the option and get the target language
                var textParts      = Regex.Match(plainText, @"([^|]*)\|([\s\S]*)$");
                var languageOption = Regex.Match(textParts.Groups[1].Value, @"l:(\w+)");
                var language       = languageOption.Success ? languageOption.Groups[1].Value : "cs";
                var sourceCode     = textParts.Groups[2].Value;

                // Replace the compression tokens
                if (language is "cs")
                {
                    sourceCode = ReplaceTokens(sourceCode, _sharplabCSTokens);

                    // Strip using directives
                    sourceCode = Regex.Replace(sourceCode, @"using \w+(?:\.\w+)*;", string.Empty);
                }
                else if (language is "il")
                {
                    sourceCode = ReplaceTokens(sourceCode, _sharplabILTokens);
                }
                else
                {
                    sourceCode = sourceCode.Replace("@@", "@");
                }

                var maxPreviewLength = EmbedBuilder.MaxDescriptionLength - (markdownLength + language.Length + "```\n\n```".Length);

                preview = FormatUtilities.FormatCodeForEmbed(language, sourceCode, maxPreviewLength);

                return(!string.IsNullOrWhiteSpace(preview));
            }
            catch
            {
                preview = null;
                return(false);
            }
        }
示例#22
0
文件: XmlUtils.cs 项目: Levrum/Levrum
        public static Stream GetXmlStream(string compressedContents, FileInfo xmlFile)
        {
            Stream stream = null;

            if (!string.IsNullOrEmpty(compressedContents))
            {
                string xmlContents = LZString.decompressFromUTF16(compressedContents);
                stream = new MemoryStream(Encoding.UTF8.GetBytes(xmlContents));
            }
            else
            {
                stream = xmlFile.OpenRead();
            }

            return(stream);
        }
示例#23
0
        public List <string> GetColumns()
        {
            const string fn = "CsvSource.GetColumns()";

            if (CsvFile == null || !CsvFile.Exists)
            {
                return(new List <string>());
            }
            Stream stream = null;

            try
            {
                if (Parameters.ContainsKey("CompressedContents"))
                {
                    string compressedContents = Parameters["CompressedContents"];
                    string csvContents        = LZString.decompressFromUTF16(compressedContents);

                    stream = new MemoryStream(Encoding.UTF8.GetBytes(csvContents));
                }
                else
                {
                    stream = CsvFile.OpenRead();
                }
                if ((!CsvFile.Directory.Exists) || (!CsvFile.Exists))
                {
                    return(new List <string>());
                }
                using (StreamReader sr = new StreamReader(stream))
                    using (CsvReader csvReader = new CsvReader(sr, CultureInfo.CurrentCulture))
                    {
                        csvReader.Read();
                        csvReader.ReadHeader();
                        return(new List <string>(csvReader.Context.Reader.HeaderRecord));
                    }
            }
            catch (Exception ex)
            {
                LogHelper.LogException(ex, "Exception in GetColumns");
                return(new List <string>());
            } finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }
        }
        public void CompatibilityDecompressEncodedURIComponentFromNode(LZStringTestCase test)
        {
            var compress   = RunNodeLzString("compressToEncodedURIComponent", test.Uncompressed);
            var uncompress = "";

            try
            {
                uncompress = LZString.DecompressFromEncodedURIComponent(compress);
            }
            catch (FormatException exc)
            {
                Assert.Fail($"Invalid EncodedURIComponent string: '{compress}'{Environment.NewLine}{exc.Message}");
            }
            Console.WriteLine("lz-string compression result:");
            Console.WriteLine(compress);
            Assert.That(uncompress, Is.EqualTo(test.Uncompressed));
        }
示例#25
0
        public List <string> GetColumnValues(string column)
        {
            Stream stream = null;

            try
            {
                if (Parameters.ContainsKey("CompressedContents"))
                {
                    string compressedContents = Parameters["CompressedContents"];
                    string csvContents        = LZString.decompressFromUTF16(compressedContents);

                    stream = new MemoryStream(Encoding.UTF8.GetBytes(csvContents));
                }
                else
                {
                    stream = CsvFile.OpenRead();
                }

                List <string> values = new List <string>();
                using (StreamReader sr = new StreamReader(stream))
                    using (CsvReader csvReader = new CsvReader(sr, CultureInfo.CurrentCulture))
                    {
                        csvReader.Read();
                        csvReader.ReadHeader();
                        while (csvReader.Read())
                        {
                            values.Add(csvReader.GetField(column));
                        }
                        ;
                    }

                return(values);
            } catch (Exception ex)
            {
                LogHelper.LogException(ex, "Exception in GetColumnValues");
                return(new List <string>());
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }
        }
示例#26
0
        private void 保存SToolStripButton_Click(object sender, EventArgs e)
        {
            if (strSaveFile == "")
            {
                if (saveFileDialog1.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                strSaveFile = saveFileDialog1.FileName;
            }
            else
            {
                File.Copy(strSaveFile, strSaveFile + ".bak");
            }
            StreamWriter wr = new StreamWriter(strSaveFile);

            wr.Write(LZString.CompressToBase64(textBoxSaveFileContent.Text));
            wr.Close();
        }
        public void CompressToBase64Performance()
        {
            var value = new string('x', 65536);

            LZString.CompressToBase64(value); // Warmup

            var timer = new Stopwatch();

            timer.Start();
            const int times = 1024;

            for (var i = 0; i < times; i++)
            {
                LZString.CompressToBase64(value);
            }

            timer.Stop();
            Assert.Pass($"Did {times} compressions in {timer.Elapsed.TotalSeconds}s. Average: {timer.ElapsedMilliseconds / times}ms");
        }
示例#28
0
        public string GetLoadDataTables()
        {
            var param   = new jQueryDataTableParamModel();
            var Context = HttpContext.Current;

            param.sEcho          = String.IsNullOrEmpty(Context.Request["sEcho"]) ? 0 : Convert.ToInt32(Context.Request["sEcho"]);
            param.sSearch        = String.IsNullOrEmpty(Context.Request["sSearch"]) ? "" : Context.Request["sSearch"];
            param.iDisplayStart += String.IsNullOrEmpty(Context.Request["iDisplayStart"]) ? 0 : Convert.ToInt32(Context.Request["iDisplayStart"]);
            param.iDisplayLength = String.IsNullOrEmpty(Context.Request["iDisplayLength"]) ? 0 : Convert.ToInt32(Context.Request["iDisplayLength"]);
            var sortColumnIndex = Convert.ToInt32(Context.Request["iSortCol_0"]);
            var sortDirection   = Context.Request["sSortDir_0"];// asc or desc

            // create filter parameters
            string[,] _params = { { "DisplayStart", param.iDisplayStart.ToString() }, { "DisplayLength", param.iDisplayLength.ToString() },
                                  { "SearchParam",  param.sSearch                  }, { "SortColumn",    sortColumnIndex.ToString()      },{ "SortDirection", sortDirection } };

            // get all of data.
            var _ds = new Select().SelectLists(Context.Request["funName"], _params);

            return(LZString.CompressToUTF16(_ds.GetXml()));
        }
示例#29
0
        public string GetTaskMessage(string taskId)
        {
            var msg = string.Empty;

            var taskModel = this.GetModelById(taskId);

            if (null == taskModel)
            {
                return(msg);
            }
            //开始处理消息
            // 对数据进行解压缩
            if (taskModel.IsCompressed)
            {
                msg = LZString.decompressFromEncodedURIComponent(taskModel.Message);
            }
            else
            {
                msg = taskModel.Message;
            }
            return(msg);
        }
示例#30
0
            public static String DecompressFromUTF16(String input)
            {
                if (input == null)
                {
                    return("");
                }
                StringBuilder output = new StringBuilder(200);
                int           current = 0, c, status = 0, i = 0;

                while (i < input.Length)
                {
                    c = (((int)input[i]) - 32);

                    switch (status++)
                    {
                    case 0:
                        current = c << 1;
                        break;

                    case 1:
                        output.Append((char)(current | (c >> 14)));
                        current = (c & 16383) << 2;
                        break;

                    case 2:
                        output.Append((char)(current | (c >> 13)));
                        current = (c & 8191) << 3;
                        break;

                    case 3:
                        output.Append((char)(current | (c >> 12)));
                        current = (c & 4095) << 4;
                        break;

                    case 4:
                        output.Append((char)(current | (c >> 11)));
                        current = (c & 2047) << 5;
                        break;

                    case 5:
                        output.Append((char)(current | (c >> 10)));
                        current = (c & 1023) << 6;
                        break;

                    case 6:
                        output.Append((char)(current | (c >> 9)));
                        current = (c & 511) << 7;
                        break;

                    case 7:
                        output.Append((char)(current | (c >> 8)));
                        current = (c & 255) << 8;
                        break;

                    case 8:
                        output.Append((char)(current | (c >> 7)));
                        current = (c & 127) << 9;
                        break;

                    case 9:
                        output.Append((char)(current | (c >> 6)));
                        current = (c & 63) << 10;
                        break;

                    case 10:
                        output.Append((char)(current | (c >> 5)));
                        current = (c & 31) << 11;
                        break;

                    case 11:
                        output.Append((char)(current | (c >> 4)));
                        current = (c & 15) << 12;
                        break;

                    case 12:
                        output.Append((char)(current | (c >> 3)));
                        current = (c & 7) << 13;
                        break;

                    case 13:
                        output.Append((char)(current | (c >> 2)));
                        current = (c & 3) << 14;
                        break;

                    case 14:
                        output.Append((char)(current | (c >> 1)));
                        current = (c & 1) << 15;
                        break;

                    case 15:
                        output.Append((char)(current | c));

                        status = 0;
                        break;
                    }

                    i++;
                }

                return(LZString.Decompress(output.ToString()));
                // return output;
            }