Exemple #1
0
        /// <summary>
        /// 删除首尾无意义的字符,比如空格和制表符等
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string TrimMeaninglessChars(string str)
        {
            str = ConvertHelper.GetString(str);
            if (str.Length <= 0)
            {
                return(str);
            }
            var trim = new string[] { "\n", "\t", ' '.ToString() };

            while (true)
            {
                var len = str.Length;
                foreach (var t in trim)
                {
                    str = StringHelper.Trim(str, t, ignoreCase: true);
                }

                //break if trim end
                var not_trimed = str.Length == len;
                if (not_trimed)
                {
                    break;
                }
            }
            return(str);
        }
Exemple #2
0
        /// <summary>
        /// 通过给定参数生成分页html
        /// </summary>
        /// <param name="url"></param>
        /// <param name="pageKey"></param>
        /// <param name="urlParams"></param>
        /// <param name="itemCount"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static string GetPagerHtmlByData(
            string url, string pageKey,
            Dictionary <string, string> urlParams,
            int itemCount, int page, int pageSize)
        {
            url = ConvertHelper.GetString(url).Trim();
            if (!url.EndsWith("?"))
            {
                url += "?";
            }

            if (!ValidateHelper.IsPlumpString(pageKey))
            {
                pageKey = "page";
            }

            url += Com.DictToUrlParams(urlParams);
            if (ValidateHelper.IsPlumpDict(urlParams))
            {
                url += "&";
            }

            url += pageKey + "={0}";

            int pageCount = GetPageCount(itemCount, pageSize);

            return(GetPagerHtml(page, pageCount, url));
        }
Exemple #3
0
        /// <summary>
        /// 比较两个json结构是否相同
        /// </summary>
        /// <param name="json_1"></param>
        /// <param name="json_2"></param>
        /// <returns></returns>
        public static bool HasSameStructure(string json_1, string json_2)
        {
            var path_list = new List <string>();

            void FindJsonNode(JToken token)
            {
                if (token == null)
                {
                    return;
                }
                if (token.Type == JTokenType.Property)
                {
                    path_list.Add(token.Path);
                }
                //find next node
                var children = token.Children();

                foreach (var child in children)
                {
                    FindJsonNode(child);
                }
            }

            FindJsonNode(JToken.Parse(json_1));
            FindJsonNode(JToken.Parse(json_2));

            path_list = path_list.Select(x => ConvertHelper.GetString(x).Trim()).ToList();

            //这里其实有bug
            //如果一个json是空,另一个是两个a.b.c(虽然不可能出现)
            //就会导致两个不一样的json被判断为一样
            //介于不太可能发生,就不想改了,什么时候c#内置函数支持ref再改(强迫症=.=)
            return(path_list.Count == path_list.Distinct().Count() * 2);
        }
Exemple #4
0
        /*
         * string username = "******";
         * byte[] buffer = System.Text.Encoding.UTF8.GetBytes(username); //这是把字符串转成字节数组
         * Console.WriteLine(System.Text.Encoding.UTF8.GetString(buffer)); //这是把字节数组再转回到字符串
         *
         * Console.WriteLine(BitConverter.ToString(buffer)); // 这是把字节数组当作字符串输出(长度较长)
         * Console.WriteLine(Convert.ToBase64String(buffer)); //这是把字节数组当作一种所谓的Base64的字符串格式输出
         */

        public string GetByteString(string str, Encoding encode = null)
        {
            if (encode == null)
            {
                encode = Encoding.UTF8;
            }
            byte[] b = encode.GetBytes(ConvertHelper.GetString(str));
            return(BitConverter.ToString(b));
        }
Exemple #5
0
 /// <summary>
 /// 截取字符串
 /// </summary>
 public static string SubString(string str, int startIndex, int length)
 {
     str = ConvertHelper.GetString(str);
     if (str.Length > (startIndex + length))
     {
         return(str.Substring(startIndex, length));
     }
     return(str);
 }
Exemple #6
0
        /// <summary>
        /// 字典变url格式(a=1&b=3)
        /// </summary>
        public static string DictToUrlParams(IDictionary <string, string> data)
        {
            if (!ValidateHelper.IsPlumpDict(data))
            {
                return(string.Empty);
            }
            var arr = data.Keys.Select(x => $"{x}={ConvertHelper.GetString(data[x])}");

            return(string.Join("&", arr));
        }
Exemple #7
0
        /// <summary>
        /// 提取文本中@对象 @用户
        /// http://blog.csdn.net/hfut_jf/article/details/49745701
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static List <string> FindAtFromStr(string str)
        {
            var matchs = RegexHelper.FindMatchs(ConvertHelper.GetString(str), "@[\u4e00-\u9fa5a-zA-Z0-9_-]{2,30}");
            var list   = matchs?.Where(x => x.Success).Select(x => x.Value).Distinct().ToList();

            if (list == null)
            {
                list = new List <string>();
            }
            return(list);
        }
Exemple #8
0
        /// <summary>
        /// 提取文本中的话题,格式:#话题#
        /// http://blog.csdn.net/hfut_jf/article/details/49745701
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static List <string> FindTagsFromStr(string str)
        {
            var matchs = RegexHelper.FindMatchs(ConvertHelper.GetString(str), "#[^#]+#");
            var list   = matchs?.Where(x => x.Success).Select(x => x.Value).Distinct().ToList();

            if (list == null)
            {
                list = new List <string>();
            }
            return(list);
        }
Exemple #9
0
        /// <summary>
        /// 移除前导字符串
        /// </summary>
        public static string TrimStart(string str, string trimStr, bool ignoreCase = true)
        {
            str     = ConvertHelper.GetString(str);
            trimStr = ConvertHelper.GetString(trimStr);

            while (str.StartsWith(trimStr, ignoreCase, CultureInfo.CurrentCulture))
            {
                str = str.Remove(0, trimStr.Length);
            }

            return(str);
        }
Exemple #10
0
        /// <summary>
        /// 移除后导字符串
        /// </summary>
        public static string TrimEnd(string str, string trimStr, bool ignoreCase = true)
        {
            str     = ConvertHelper.GetString(str);
            trimStr = ConvertHelper.GetString(trimStr);

            while (str.EndsWith(trimStr, ignoreCase, CultureInfo.CurrentCulture))
            {
                str = str.Substring(0, str.Length - trimStr.Length);
            }

            return(str);
        }
Exemple #11
0
        /// <summary>
        /// 根据attribute验证model
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static List <string> CheckEntity_ <T>(T model) where T : IDBTable
        {
            var list = new List <string>();

            if (model == null)
            {
                list.Add("实体对象不能为Null");
                return(list);
            }

            //checker
            bool CheckProp(IEnumerable <ValidationAttribute> validators, object data, PropertyInfo p)
            {
                foreach (var validator in ConvertHelper.NotNullEnumerable(validators))
                {
                    if (!validator.IsValid(data))
                    {
                        var msg = ConvertHelper.GetString(validator.ErrorMessage).Trim();
                        if (!ValidateHelper.IsPlumpString(msg))
                        {
                            msg = $"字段{p.Name}未通过{validator.GetType().Name}标签的验证";
                        }
                        list.Add(msg);
                        return(false);
                    }
                }
                return(true);
            };

            foreach (var prop in model.GetType().GetProperties())
            {
                if (prop.GetCustomAttributes <NotMappedAttribute>().Any())
                {
                    continue;
                }

                var value = prop.GetValue(model);

                if (!CheckProp(prop.GetCustomAttributes_ <ValidationAttribute>(), value, prop))
                {
                    continue;
                }
            }

            list = list.Where(x => IsPlumpString(x)).Distinct().ToList();

            if (ValidateHelper.IsPlumpList(list))
            {
                Console.WriteLine("".Join_(list));
            }

            return(list);
        }
Exemple #12
0
 /// <summary>
 /// 是否是图片
 /// </summary>
 /// <param name="urlOrPathOrName"></param>
 /// <returns></returns>
 public static bool IsImage(string urlOrPathOrName)
 {
     urlOrPathOrName = ConvertHelper.GetString(urlOrPathOrName).Trim().ToLower();
     foreach (var ext in ImageExtesions)
     {
         if (urlOrPathOrName.EndsWith(ext))
         {
             return(true);
         }
     }
     return(false);
 }
Exemple #13
0
        /// <summary>
        /// join 不会返回空
        /// </summary>
        public static string Join(string spliter, IList <string> list)
        {
            string str = string.Empty;

            if (!ValidateHelper.IsPlumpList(list))
            {
                return(str);
            }
            list.ToList().ForEach(delegate(string s)
            {
                s    = ConvertHelper.GetString(s);
                str += ((str == string.Empty) ? string.Empty : spliter) + s;
            });
            return(str);
        }
Exemple #14
0
        /// <summary>
        /// 根据attribute验证model
        /// </summary>
        public static List <string> CheckEntity_ <T>(T model) where T : IDBTable
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            var list = new List <string>();

            //checker
            bool CheckProp(IEnumerable <ValidationAttribute> validators, PropertyInfo p)
            {
                var data = p.GetValue(model);

                foreach (var validator in ConvertHelper.NotNullList(validators))
                {
                    if (!validator.IsValid(data))
                    {
                        var msg = ConvertHelper.GetString(validator.ErrorMessage).Trim();
                        if (!ValidateHelper.IsPlumpString(msg))
                        {
                            msg = $"字段{p.Name}未通过{validator.GetType().Name}标签的验证";
                        }
                        list.Add(msg);
                        return(false);
                    }
                }
                return(true);
            };

            foreach (var prop in model.GetType().GetProperties())
            {
                if (prop.HasCustomAttributes_ <NotMappedAttribute>(inherit: false))
                {
                    continue;
                }

                //忽略父级的验证属性
                var validators = prop.GetCustomAttributes_ <ValidationAttribute>(inherit: false);
                if (!CheckProp(validators, prop))
                {
                    continue;
                }
            }

            list = list.NotEmptyAndDistinct(x => x).ToList();

            return(list);
        }
Exemple #15
0
        /// <summary>
        /// 筛选+排序
        /// </summary>
        public static SortedDictionary <string, string> FilterAndSort(Dictionary <string, string> dict, string sign_key, IComparer <string> comparer)
        {
            Func <KeyValuePair <string, string>, bool> filter = x =>
            {
                if (x.Key == null || x.Key == sign_key || x.Key.Length > 32 || x.Value?.Length > 32)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            };
            var filtered = dict.Where(x => filter(x)).ToDictionary(x => x.Key, x => ConvertHelper.GetString(x.Value));

            return(new SortedDictionary <string, string>(filtered, comparer));
        }
Exemple #16
0
 /// <summary>
 /// 获取MD5
 /// </summary>
 /// <param name="str"></param>
 /// <param name="getShort"></param>
 /// <returns></returns>
 public static string GetMD5(string str, bool getShort = false)
 {
     using (var md5 = new MD5CryptoServiceProvider())
     {
         byte[] bytes_md5_in = Encoding.UTF8.GetBytes(str);
         //把字节数组(byte[])转换成16进制
         string md5_ret = BitConverter.ToString(md5.ComputeHash(bytes_md5_in));
         md5_ret = ConvertHelper.GetString(md5_ret).Trim().Replace("-", "");
         if (md5_ret.Length != 32)
         {
             return(string.Empty);
         }
         if (getShort)
         {
             return(md5_ret.Substring(8, 16));
         }
         return(md5_ret);
     }
 }
Exemple #17
0
        /// <summary>
        /// 格式化数字格式
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static string FormatNumber(string num)
        {
            var sp = ConvertHelper.GetString(num).Split('.');

            if (sp.Length != 2)
            {
                return(num);
            }
            var right = ConvertHelper.GetString(sp[1]);

            right = right.TrimEnd('0');
            var left = sp[0];

            if (ValidateHelper.IsNotEmpty(right))
            {
                left += "." + right;
            }
            return(left);
        }
Exemple #18
0
 /// <summary>
 /// 简单判断是否是json,不一定全部正确
 /// </summary>
 /// <param name="json"></param>
 /// <returns></returns>
 public static bool IsJson(string json)
 {
     json = ConvertHelper.GetString(json);
     return((json.StartsWith("{") && json.EndsWith("}")) ||
            (json.StartsWith("[") && json.EndsWith("]")));
 }
Exemple #19
0
 /// <summary>
 /// 可能返回空
 /// </summary>
 /// <param name="str"></param>
 /// <param name="spliter"></param>
 /// <returns></returns>
 public static List <string> Split(string str, params char[] spliter)
 {
     return(ConvertHelper.GetString(str).Split(spliter).ToList());
 }
Exemple #20
0
 /// <summary>
 /// 判断字符串的长度是否在范围之内,str可以为空
 /// </summary>
 /// <param name="str"></param>
 /// <param name="min"></param>
 /// <param name="max"></param>
 /// <param name="withBorder"></param>
 /// <returns></returns>
 public static bool IsLenInRange(string str, int min, int max)
 {
     str = ConvertHelper.GetString(str);
     return(str.Length >= min && str.Length <= max);
 }
Exemple #21
0
 /// <summary>
 /// 把对象可读属性读出来变成字典
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public static Dictionary <string, string> ObjectToStringDict(object data)
 {
     return(ObjectToDict_(data).ToDictionary(x => x.Key, x => ConvertHelper.GetString(x.Value)));
 }
Exemple #22
0
 /// <summary>
 /// 获取字符前几位,并加省略号
 /// </summary>
 /// <param name="str"></param>
 /// <param name="len"></param>
 /// <returns></returns>
 public static string GetPreviewString(string str, int len)
 {
     str = ConvertHelper.GetString(str);
     return((str.Length <= len) ? str : str.Substring(0, len) + "...");
 }
Exemple #23
0
 /// <summary>
 /// 获取请求ID
 /// </summary>
 /// <returns></returns>
 public static string GetRequestID() => ConvertHelper.GetString(HttpContext.Current.Items["req_guid"]);