/// <summary>
495 /// 生成随机字母字符串(数字字母混和)
496 /// </summary>
497 /// <param name="codeCount">待生成的位数</param>
498 public static string GetCheckCode(int codeCount)
499 {
500 string str = string.Empty;
501 int rep = 0;
502 long num2 = DateTime.Now.Ticks + rep;
503 rep++;
504 Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
505 for (int i = 0; i < codeCount; i++)
506 {
507 char ch;
508 int num = random.Next();
509 if ((num % 2) == 0)
510 {
511 ch = (char)(0x30 + ((ushort)(num % 10)));
512 }
513 else
514 {
515 ch = (char)(0x41 + ((ushort)(num % 0x1a)));
516 }
517 str = str + ch.ToString();
518 }
519 return str;
520 }
521 /// <summary>
522 /// 根据日期和随机码生成订单号
523 /// </summary>
524 /// <returns></returns>
525 public static string GetOrderNumber()
526 {
527 string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms
528 return num + Number(2).ToString();
529 }
530 private static int Next(int numSeeds, int length)
531 {
532 byte[] buffer = new byte[length];
533 System.Security.Cryptography.RNGCryptoServiceProvider Gen = new System.Security.Cryptography.RNGCryptoServiceProvider();
534 Gen.GetBytes(buffer);
535 uint randomResult = 0x0;//这里用uint作为生成的随机数
536 for (int i = 0; i < length; i++)
537 {
538 randomResult |= ((uint)buffer[i] << ((length - 1 - i) * 8));
539 }
540 return (int)(randomResult % numSeeds);
541 }
542 #endregion
543
544 #region 截取字符长度
545 /// <summary>
546 /// 截取字符长度
547 /// </summary>
548 /// <param name="inputString">字符</param>
549 /// <param name="len">长度</param>
550 /// <returns></returns>
551 public static string CutString(string inputString, int len)
552 {
553 if (string.IsNullOrEmpty(inputString))
554 return "";
555 inputString = DropHTML(inputString);
556 ASCIIEncoding ascii = new ASCIIEncoding();
557 int tempLen = 0;
558 string tempString = "";
559 byte[] s = ascii.GetBytes(inputString);
560 for (int i = 0; i < s.Length; i++)
561 {
562 if ((int)s[i] == 63)
563 {
564 tempLen += 2;
565 }
566 else
567 {
568 tempLen += 1;
569 }
570
571 try
572 {
573 tempString += inputString.Substring(i, 1);
574 }
575 catch
576 {
577 break;
578 }
579
580 if (tempLen > len)
581 break;
582 }
583 //如果截过则加上半个省略号
584 byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
585 if (mybyte.Length > len)
586 tempString += "…";
587 return tempString;
588 }
589 #endregion
590
591 #region 对象<-->JSON 4.0使用
592 /// <summary>
593 /// 对象转JSON
594 /// </summary>
595 /// <typeparam name="T">对象实体</typeparam>
596 /// <param name="t">内容</param>
597 /// <returns>json包</returns>
598 public static string ObjetcToJson<T>(T t)
599 {
600 try
601 {
602 DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
603 string szJson = "";
604 using (MemoryStream stream = new MemoryStream())
605 {
606 json.WriteObject(stream, t);
607 szJson = Encoding.UTF8.GetString(stream.ToArray());
608 }
609 return szJson;
610 }
611 catch { return ""; }
612 }
613
614 /// <summary>
615 /// Json包转对象
616 /// </summary>
617 /// <typeparam name="T">对象</typeparam>
618 /// <param name="jsonstring">json包</param>
619 /// <returns>异常抛null</returns>
620 public static object JsonToObject<T>(string jsonstring)
621 {
622 object result = null;
623 try
624 {
625 DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
626 using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonstring)))
627 {
628 result = json.ReadObject(stream);
629 }
630 return result;
631 }
632 catch { return result; }
633 }
634 #endregion
635
636 #region 对象<-->JSON 2.0 使用litjson插件
637 /// <summary>
638 /// 对象转JSON jsonData
639 /// </summary>
640 /// <typeparam name="T"></typeparam>
641 /// <param name="t"></param>
642 /// <returns></returns>
643 //public static string ObjetcToJsonData<T>(T t)
644 //{
645 // try
646 // {
647 // JsonData json = new JsonData(t);
648 // return json.ToJson();
649 // }
650 // catch
651 // {
652 // return "";
653 // }
654 //}
655
656 ///// <summary>
657 ///// 对象转JSON jsonMapper
658 ///// </summary>
659 ///// <typeparam name="T"></typeparam>
660 ///// <param name="t"></param>
661 ///// <returns></returns>
662 //public static string ObjetcToJsonMapper<T>(T t)
663 //{
664 // try
665 // {
666 // JsonData json = JsonMapper.ToJson(t);
667 // return json.ToJson();
668 // }
669 // catch
670 // {
671 // return "";
672 // }
673 //}
674
675 ///// <summary>
676 ///// json转对象 jsonMapper
677 ///// </summary>
678 ///// <param name="jsons"></param>
679 ///// <returns></returns>
680 //public static object JsonToObject(string jsons)
681 //{
682 // try
683 // {
684 // JsonData jsonObject = JsonMapper.ToObject(jsons);
685 // return jsonObject;
686 // }
687 // catch { return null; }
688 //}
689
690 #endregion
691
692 #region DataTable<-->JSON
693 /// <summary>
694 /// DataTable转为json
695 /// </summary>
696 /// <param name="dt">DataTable</param>
697 /// <returns>json数据</returns>
698 public static string DataTableToJson(DataTable dt)
699 {
700 List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
701 foreach (DataRow dr in dt.Rows)
702 {
703 Dictionary<string, object> result = new Dictionary<string, object>();
704 foreach (DataColumn dc in dt.Columns)
705 {
706 result.Add(dc.ColumnName, dr[dc]);
707 }
708 list.Add(result);
709 }
710
711 return SerializeToJson(list);
712 }
713 /// <summary>
714 /// 序列化对象为Json字符串
715 /// </summary>
716 /// <param name="obj">要序列化的对象</param>
717 /// <param name="recursionLimit">序列化对象的深度,默认为100</param>
718 /// <returns>Json字符串</returns>
719 public static string SerializeToJson(object obj, int recursionLimit = 100)
720 {
721 try
722 {
723 JavaScriptSerializer serialize = new JavaScriptSerializer();
724 serialize.RecursionLimit = recursionLimit;
725 return serialize.Serialize(obj);
726 }
727 catch { return ""; }
728 }
729 /// <summary>
730 /// json包转DataTable
731 /// </summary>
732 /// <param name="jsons"></param>
733 /// <returns></returns>
734 public static DataTable JsonToDataTable(string jsons)
735 {
736 DataTable dt = new DataTable();
737 try
738 {
739 JavaScriptSerializer serialize = new JavaScriptSerializer();
740 serialize.MaxJsonLength = Int32.MaxValue;
741 ArrayList list = serialize.Deserialize<ArrayList>(jsons);
742 if (list.Count > 0)
743 {
744 foreach (Dictionary<string, object> item in list)
745 {
746 if (item.Keys.Count == 0)//无值返回空
747 {
748 return dt;
749 }
750 if (dt.Columns.Count == 0)//初始Columns
751 {
752 foreach (string current in item.Keys)
753 {
754 dt.Columns.Add(current, item[current].GetType());
755 }
756 }
757 DataRow dr = dt.NewRow();
758 foreach (string current in item.Keys)
759 {
760 dr[current] = item[current];
761 }
762 dt.Rows.Add(dr);
763 }
764 }
765 }
766 catch
767 {
768 return dt;
769 }
770 return dt;
771 }
772 #endregion
773
774 #region List<--->DataTable
775 /// <summary>
776 /// DataTable转换泛型集合
777 /// </summary>
778 /// <typeparam name="T"></typeparam>
779 /// <param name="table"></param>
780 /// <returns></returns>
781 public static List<T> DataTableToList<T>(DataTable table)
782 {
783 List<T> list = new List<T>();
784 T t = default(T);
785 PropertyInfo[] propertypes = null;
786 string tempName = string.Empty;
787 foreach (DataRow row in table.Rows)
788 {
789 t = Activator.CreateInstance<T>();
790 propertypes = t.GetType().GetProperties();
791 foreach (PropertyInfo pro in propertypes)
792 {
793 tempName = pro.Name;
794 if (table.Columns.Contains(tempName))
795 {
796 object value = row[tempName];
797 if (!value.ToString().Equals(""))
798 {
799 pro.SetValue(t, value, null);
800 }
801 }
802 }
803 list.Add(t);
804 }
805 return list.Count == 0 ? null : list;
806 }
807
808 /// <summary>
809 /// 将集合类转换成DataTable
810 /// </summary>
811 /// <param name="list">集合</param>
812 /// <returns>DataTable</returns>
813 public static DataTable ListToDataTable(IList list)
814 {
815 DataTable result = new DataTable();
816 if (list != null && list.Count > 0)
817 {
818 PropertyInfo[] propertys = list[0].GetType().GetProperties();
819 foreach (PropertyInfo pi in propertys)
820 {
821 result.Columns.Add(pi.Name, pi.PropertyType);
822 }
823 for (int i = 0; i < list.Count; i++)
824 {
825 ArrayList tempList = new ArrayList();
826 foreach (PropertyInfo pi in propertys)
827 {
828 object obj = pi.GetValue(list[i], null);
829 tempList.Add(obj);
830 }
831 object[] array = tempList.ToArray();
832 result.LoadDataRow(array, true);
833 }
834 }
835 return result;
836 }
837 public static List<T> ConvertTo<T>(DataTable dt) where T : new()
838 {
839 if (dt == null) return null;
840 if (dt.Rows.Count <= 0) return null;
841
842 List<T> list = new List<T>();
843 try
844 {
845 List<string> columnsName = new List<string>();
846 foreach (DataColumn dataColumn in dt.Columns)
847 {
848 columnsName.Add(dataColumn.ColumnName);//得到所有的表头
849 }
850 list = dt.AsEnumerable().ToList().ConvertAll<T>(row => GetObject<T>(row, columnsName)); //转换
851 return list;
852 }
853 catch
854 {
855 return null;
856 }
857 }
858
859 public static T GetObject<T>(DataRow row, List<string> columnsName) where T : new()
860 {
861 T obj = new T();
862 try
863 {
864 string columnname = "";
865 string value = "";
866 PropertyInfo[] Properties = typeof(T).GetProperties();
867 foreach (PropertyInfo objProperty in Properties) //遍历T的属性
868 {
869 columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower()); //寻找可以匹配的表头名称
870 if (!string.IsNullOrEmpty(columnname))
871 {
872 value = row[columnname].ToString();
873 if (!string.IsNullOrEmpty(value))
874 {
875 if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null) //存在匹配的表头
876 {
877 value = row[columnname].ToString().Replace("$", "").Replace(",", ""); //从dataRow中提取数据
878 objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null); //赋值操作
879 }
880 else
881 {
882 value = row[columnname].ToString().Replace("%", ""); //存在匹配的表头
883 objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);//赋值操作
884 }
885 }
886 }
887 }
888 return obj;
889 }
890 catch
891 {
892 return obj;
893 }
894 }
895 /// <summary>
896 /// 将泛型集合类转换成DataTable
897 /// </summary>
898 /// <typeparam name="T">集合项类型</typeparam>
899 /// <param name="list">集合</param>
900 /// <param name="propertyName">需要返回的列的列名</param>
901 /// <returns>数据集(表)</returns>
902 public static DataTable ListToDataTable<T>(IList<T> list, params string[] propertyName)
903 {
904 List<string> propertyNameList = new List<string>();
905 if (propertyName != null)
906 propertyNameList.AddRange(propertyName);
907 DataTable result = new DataTable();
908 if (list != null && list.Count > 0)
909 {
910 PropertyInfo[] propertys = list[0].GetType().GetProperties();
911 foreach (PropertyInfo pi in propertys)
912 {
913 if (propertyNameList.Count == 0)
914 {
915 result.Columns.Add(pi.Name, pi.PropertyType);
916 }
917 else
918 {
919 if (propertyNameList.Contains(pi.Name))
920 result.Columns.Add(pi.Name, pi.PropertyType);
921 }
922 }
923 for (int i = 0; i < list.Count; i++)
924 {
925 ArrayList tempList = new ArrayList();
926 foreach (PropertyInfo pi in propertys)
927 {
928 if (propertyNameList.Count == 0)
929 {
930 object obj = pi.GetValue(list[i], null);
931 tempList.Add(obj);
932 }
933 else
934 {
935 if (propertyNameList.Contains(pi.Name))
936 {
937 object obj = pi.GetValue(list[i], null);
938 tempList.Add(obj);
939 }
940 }
941 }
942 object[] array = tempList.ToArray();
943 result.LoadDataRow(array, true);
944 }
945 }
946 return result;
947 }
948
949 #endregion
950
951 #region 清除HTML标记
952 public static string DropHTML(string Htmlstring)
953 {
954 if (string.IsNullOrEmpty(Htmlstring)) return "";
955 //删除脚本
956 Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
957 //删除HTML
958 Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
959 Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
960 Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
961 Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
962 Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
963 Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
964 Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
965 Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
966 Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
967 Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
968 Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
969 Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
970 Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
971
972 Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
973 Htmlstring.Replace("<", "");
974 Htmlstring.Replace(">", "");
975 Htmlstring.Replace("\r\n", "");
976 Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
977 return Htmlstring;
978 }
979 #endregion
980
981 #region 清除HTML标记且返回相应的长度
982 public static string DropHTML(string Htmlstring, int strLen)
983 {
984 return CutString(DropHTML(Htmlstring), strLen);
985 }
986 #endregion
987
988 #region TXT代码转换成HTML格式
989 /// <summary>
990 /// 字符串字符处理
991 /// </summary>
992 /// <param name="chr">等待处理的字符串</param>
993 /// <returns>处理后的字符串</returns>
994 /// //把TXT代码转换成HTML格式
995 public static String ToHtml(string Input)
996 {
997 StringBuilder sb = new StringBuilder(Input);
998 sb.Replace("&", "&");
999 sb.Replace("<", "<");
1000 sb.Replace(">", ">");
1001 sb.Replace("\r\n", "<br />");
1002 sb.Replace("\n", "<br />");
1003 sb.Replace("\t", " ");
1004 //sb.Replace(" ", " ");
1005 return sb.ToString();
1006 }
1007 #endregion