/// <summary> /// Encryption via DES. this can be decrypted. /// </summary> /// <param name="value">the string need to be encrypted.</param> /// <param name="key">the key for encryption.</param> /// <returns>the encrypted string.</returns> public static string EncryptS(string value, string key) { ThrowExceptionUtil.ArgumentConditionTrue(!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(key), string.Empty, "should not be empty or null"); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); //把字符串放到byte数组中 //byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt); byte[] inputByteArray = Encoding.UTF8.GetBytes(value); des.Key = Encoding.UTF8.GetBytes(key); //建立加密对象的密钥和偏移量 des.IV = Encoding.UTF8.GetBytes(key); //原文使用ASCIIEncoding.ASCII方法的GetBytes方法 using (MemoryStream ms = new MemoryStream()) //使得输入密码必须输入英文文本 { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); } StringBuilder ret = new StringBuilder(); foreach (byte b in ms.ToArray()) { ret.AppendFormat("{0:X2}", b); } ret.ToString(); return(ret.ToString()); } }
/// <summary> /// 转换辅助类。 mapping暂未使用 /// </summary> /// <param name="type"></param> /// <param name="dataAdapter"></param> /// <param name="mapping"></param> /// <returns></returns> private static object ConvertDataToObject(Type type, BeeDataAdapter dataAdapter, Dictionary <string, string> mapping) { ThrowExceptionUtil.ArgumentNotNull(type, "type"); ThrowExceptionUtil.ArgumentNotNull(dataAdapter, "dataAdapter"); object result = ReflectionUtil.CreateInstance(type); if (result != null) { IEntityProxy entityProxy = EntityProxyManager.Instance.GetEntityProxyFromType(type); foreach (string key in dataAdapter.Keys) { string value = dataAdapter[key] as string; if (value != null && value.Length == 0) { /// 空字符串并且目标类型不是字符型则不转换 PropertySchema schema = entityProxy[key]; if (schema != null && schema.PropertyType != typeof(string)) { continue; } } entityProxy.SetPropertyValue(result, key, dataAdapter[key]); } } return(result); }
/// <summary> /// Decryption via DES. /// </summary> /// <param name="value">the string need to be decrypted.</param> /// <param name="key">the key for decryption.</param> /// <returns>the decrypted string.</returns> public static string DecryptS(string value, string key) { ThrowExceptionUtil.ArgumentConditionTrue(!string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(key), string.Empty, "should not be empty or null"); DESCryptoServiceProvider des = new DESCryptoServiceProvider(); byte[] inputByteArray = new byte[value.Length / 2]; for (int x = 0; x < value.Length / 2; x++) { int i = (Convert.ToInt32(value.Substring(x * 2, 2), 16)); inputByteArray[x] = (byte)i; } des.Key = Encoding.UTF8.GetBytes(key); //建立加密对象的密钥和偏移量,此值重要,不能修改 des.IV = Encoding.UTF8.GetBytes(key); using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); } StringBuilder ret = new StringBuilder(); //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象 return(System.Text.Encoding.UTF8.GetString(ms.ToArray())); } }
/// <summary> /// Provided for query the data table using condition and order clause and pagination in a instance of DataTable. /// </summary> /// <param name="src">The instance of DataTable.</param> /// <param name="sqlCriteria">the condition using the <typeparamref name="SqlCriteria"/></param> /// <param name="orderbyClause">Order By Clause.</param> /// <param name="pageIndex">the page index.</param> /// <param name="pageSize">the page size.</param> /// <param name="recordCount">the count of the result.</param> /// <returns>the data in the provided condition for the parameter of src.</returns> public static DataTable Query(DataTable src, SqlCriteria sqlCriteria, string orderbyClause, int pageIndex, int pageSize, ref int recordCount) { ThrowExceptionUtil.ArgumentNotNull(src, "src"); DataTable table = src; DataRow[] rows = src.Select(sqlCriteria != null ? sqlCriteria.FilterClause : "", orderbyClause); recordCount = rows.Length; if (pageIndex >= 0 && pageSize > 0) { pageIndex = pageIndex == 0 ? 1 : pageIndex; rows = rows.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToArray(); } if (rows.Length != 0) { table = rows.CopyToDataTable(); } else { table = table.Clone(); } return(table); }
/// <summary> /// Provided for common clone for the object. /// the object should be a class. /// </summary> /// <typeparam name="T">the type of the object</typeparam> /// <param name="value">the instance of the type.</param> /// <returns>the cloned instance.</returns> public static T CommonClone <T>(object value) where T : class { ThrowExceptionUtil.ArgumentNotNull(value, "value"); BeeDataAdapter dataAdapter = BeeDataAdapter.From(value); return(ConvertDataToObject <T>(dataAdapter)); }
public static string AbSolutePath(this string content) { ThrowExceptionUtil.ArgumentNotNull(content, "content"); string replaceString = @"src=""{0}$1""".FormatWith(HttpContextUtil.EnterUrl); return(AbsolutePathRegex.Replace(content, replaceString)); }
/// <summary> /// Getting the AppSetting value in list of the provided type. /// </summary> /// <typeparam name="T">the provided typ.</typeparam> /// <param name="key">the key of the appsetting.</param> /// <param name="splitChar">the split char.</param> /// <returns>the list of the provided type.</returns> public static List <T> GetAppSettingValue <T>(string key, char splitChar) { ThrowExceptionUtil.ArgumentNotNull(key, "key"); string value = ConfigurationManager.AppSettings[key]; return((from item in value.Split(new char[] { splitChar }) select ConvertUtil.CommonConvert <T>(item)).ToList()); }
/// <summary> /// Getting the AppSetting value in the provided type. /// </summary> /// <typeparam name="T">the provided type.</typeparam> /// <param name="key">the key of the appsetting.</param> /// <param name="defaultValue">the default value</param> /// <returns>the value of the configuration in the provided type.</returns> public static T GetAppSettingValue <T>(string key, T defaultValue) { ThrowExceptionUtil.ArgumentNotNull(key, "key"); string value = ConfigurationManager.AppSettings[key]; if (!string.IsNullOrEmpty(value)) { return(ConvertUtil.CommonConvert <T>(value)); } return(defaultValue); }
/// <summary> /// Create the image by the valid code. /// </summary> /// <param name="validCode">the valid code.</param> /// <returns>the image of the valid code.</returns> public static Bitmap CreateImage(string validCode) { ThrowExceptionUtil.ArgumentNotNullOrEmpty(validCode, "validCode"); int iwidth = (int)(validCode.Length * 15); System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 25); using (Graphics g = Graphics.FromImage(image)) { g.Clear(Color.White); Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.SteelBlue, Color.Black, Color.Purple }; string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" }; Random rand = new Random(); for (int i = 0; i < 25; i++) { int x1 = rand.Next(image.Width); int x2 = rand.Next(image.Width); int y1 = rand.Next(image.Height); int y2 = rand.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } for (int i = 0; i < validCode.Length; i++) { int cindex = rand.Next(7); int findex = rand.Next(5); Font f = new System.Drawing.Font(font[findex], 14, System.Drawing.FontStyle.Bold); Brush b = new System.Drawing.SolidBrush(c[cindex]); int ii = 2; if ((i + 1) % 2 == 0) { ii = 0; } g.DrawString(validCode.Substring(i, 1), f, b, (i * 13), ii); } for (int i = 0; i < 100; i++) { int x = rand.Next(image.Width); int y = rand.Next(image.Height); image.SetPixel(x, y, Color.FromArgb(rand.Next())); } g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1); } return(image); }
/// <summary> /// Convert the initial value to the target type. /// </summary> /// <param name="initialValue">the initial value.</param> /// <param name="targetType">the target type.</param> /// <returns>the result that is target type.</returns> /// <exception cref="ArgumentException"> /// when the parameter of the initial value is null. /// or when parameter of the target type is null. /// or when the target type is interface or abstract, or generic type. /// </exception> public static object Convert(object initialValue, Type targetType) { object result = null; try { result = Convert(initialValue, CultureInfo.InvariantCulture, targetType); } catch (Exception e) { ThrowExceptionUtil.ThrowMessageException("Convert error!initialValue:{0}, targetType:{1}, Exception:{2}".FormatWith(initialValue, targetType, e)); } return(result); }
/// <summary> /// /// </summary> /// <param name="dataTable"></param> /// <param name="mapping"></param> /// <param name="keySrcFlag">是否以mapping的值作为列名</param> /// <returns></returns> public static DataTable Clone(DataTable dataTable, Dictionary <string, string> mapping, bool keySrcFlag) { DataTable result = new DataTable(); if (keySrcFlag) { foreach (string key in mapping.Keys) { DataColumn column = dataTable.Columns[key]; ThrowExceptionUtil.ArgumentConditionTrue(column != null, "mapping", "datatable does not contains column:{0}".FormatWith(key)); result.Columns.Add(mapping[key], column.DataType); } foreach (DataRow row in dataTable.Rows) { DataRow newRow = result.NewRow(); foreach (string key in mapping.Keys) { newRow[mapping[key]] = row[key]; } result.Rows.Add(newRow); } } else { foreach (string key in mapping.Keys) { if (dataTable.Columns.Contains(mapping[key])) { result.Columns.Add(key, dataTable.Columns[mapping[key]].DataType); } } foreach (DataRow row in dataTable.Rows) { DataRow newRow = result.NewRow(); foreach (DataColumn column in result.Columns) { newRow[column.ColumnName] = row[mapping[column.ColumnName]]; } result.Rows.Add(newRow); } } return(result); }
/// <summary> /// Provided to fomat string using the razor format. /// </summary> /// <param name="format">string format</param> /// <param name="obj">the instance.</param> /// <returns>the converted string.</returns> public static string RazorFormat(this string format, object obj) { ThrowExceptionUtil.ArgumentNotNull(format, "format"); ThrowExceptionUtil.ArgumentNotNull(obj, "obj"); string result = string.Empty; List <string> propertyList = new List <string>(); Match match = FormatRegex.Match(format); while (match.Success) { propertyList.Add(match.Groups["name"].Value); match = match.NextMatch(); } result = format; if (obj is DataRow) { DataRow rowItem = obj as DataRow; foreach (string item in propertyList) { if (rowItem.Table.Columns.Contains(item)) { result = result.Replace("@" + item, rowItem[item].ToString()); } } } else if (obj is BeeDataAdapter) { BeeDataAdapter dataAdapter = obj as BeeDataAdapter; foreach (string item in propertyList) { result = result.Replace("@" + item, dataAdapter.Format(item)); } } else { IEntityProxy entityProxy = EntityProxyManager.Instance.GetEntityProxyFromType(obj.GetType()); foreach (string item in propertyList) { object propertyValue = entityProxy.GetPropertyValue(obj, item); result = result.Replace("@" + item, propertyValue == null ? string.Empty : propertyValue.ToString()); } } return(result); }
internal static CheckMethodResult GetEntityMethodName(Type type, string methodName, BeeDataAdapter dataAdapter) { ThrowExceptionUtil.ArgumentNotNull(type, "type"); ThrowExceptionUtil.ArgumentNotNullOrEmpty(methodName, "methodName"); if (dataAdapter == null) { dataAdapter = new BeeDataAdapter(); } CheckMethodResult result = new CheckMethodResult(); MethodSchema methodSchema = null; List <MethodSchema> list = null; //lock (lockobject) { // 保证参数长的先被匹配 // 该方法本身就排过序了 list = EntityProxyManager.Instance.GetEntityMethods(type); foreach (MethodSchema item in list) { // Check the name of the method. if (string.Compare(item.Name, methodName, true) == 0) { if (CheckMethod(item, methodName, dataAdapter, out result.DataAdapter)) { methodSchema = item; break; } } } } if (methodSchema != null) { result.MethodName = methodSchema.MemberInfo.ToString(); } else { CoreException exception = new CoreException("Can not match a method for {0}.{1}\r\n".FormatWith(type.Name, methodName)); exception.ErrorCode = ErrorCode.MVCNoAction; throw exception; } return(result); }
/// <summary> /// Check can be converted from initial type to the target type. /// </summary> /// <param name="initialType">the initial type.</param> /// <param name="targetType">the target type.</param> /// <returns>true, if can convert; or false.</returns> public static bool CanConvertType(Type initialType, Type targetType) { ThrowExceptionUtil.ArgumentNotNull(initialType, "initialType"); ThrowExceptionUtil.ArgumentNotNull(targetType, "targetType"); if (ReflectionUtil.IsNullableType(targetType)) { targetType = Nullable.GetUnderlyingType(targetType); } if (targetType == initialType) { return(true); } if (typeof(IConvertible).IsAssignableFrom(initialType) && typeof(IConvertible).IsAssignableFrom(targetType)) { return(true); } if ((initialType == typeof(DateTime)) && (targetType == typeof(DateTimeOffset))) { return(true); } if ((initialType == typeof(Guid)) && ((targetType == typeof(Guid)) || (targetType == typeof(string)))) { return(true); } if ((initialType == typeof(Type)) && (targetType == typeof(string))) { return(true); } TypeConverter converter = TypeDescriptor.GetConverter(initialType); if ((((converter != null) && !(converter is ComponentConverter)) && converter.CanConvertTo(targetType)) && ((converter.GetType() != typeof(TypeConverter)))) { return(true); } TypeConverter converter2 = TypeDescriptor.GetConverter(targetType); return((((converter2 != null) && !(converter2 is ComponentConverter)) && converter2.CanConvertFrom(initialType)) || ((initialType == typeof(DBNull)) && ReflectionUtil.IsNullableType(targetType))); }
/// <summary> /// Provided the method to copy the value from src to target via map. /// if the mapping is null or empty, so use the property name mapping. /// </summary> /// <param name="src">the source data.</param> /// <param name="target">the target data.</param> /// <param name="map">the property mapping.</param> public static void CopyProperty(object src, object target, Dictionary <string, string> mapping) { ThrowExceptionUtil.ArgumentNotNull(src, "src"); ThrowExceptionUtil.ArgumentNotNull(target, "target"); IEntityProxy srcProxy = EntityProxyManager.Instance.GetEntityProxyFromType(src.GetType()); IEntityProxy targetProxy = EntityProxyManager.Instance.GetEntityProxyFromType(target.GetType()); if (mapping != null) { foreach (string item in mapping.Keys) { targetProxy.SetPropertyValue(target, mapping[item], srcProxy.GetPropertyValue(src, item)); } } else { List <PropertySchema> list = srcProxy.GetPropertyList(); foreach (PropertySchema item in list) { targetProxy.SetPropertyValue(target, item.Name, srcProxy.GetPropertyValue(src, item.Name)); } } }
/// <summary> /// Get the vlaue of the ConnectionStringSetting. /// </summary> /// <param name="key">the key of the ConnectionStrings.</param> /// <returns>The ConnectionStringSetting value.</returns> public static ConnectionStringSettings GetConnectionString(string key) { ThrowExceptionUtil.ArgumentNotNull(key, "key"); return(ConfigurationManager.ConnectionStrings[key]); }
/// <summary> /// Provided the extended method of string to format. /// </summary> /// <param name="format">the format string.</param> /// <param name="args">the arguments of the format stirng.</param> /// <returns>the result.</returns> public static string FormatWith(this string format, params object[] args) { ThrowExceptionUtil.ArgumentNotNull(format, "format"); return(format.FormatWith(CultureInfo.CurrentCulture, args)); }
/// <summary> /// Check the type is <typeparamref name="Nullable<>"/> /// </summary> /// <param name="type">the type.</param> /// <returns>true, if the type is subclass of the <typeparamref name="Nullable<>"/></returns> public static bool IsNullableType(Type type) { ThrowExceptionUtil.ArgumentNotNull(type, "type"); return(type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable <>))); }
/// <summary> /// Combine the path using the base directory of current AppDomain. /// </summary> /// <param name="relativePath">the relative path.</param> /// <returns>the combined path.</returns> public static string CombinePath(string relativePath) { ThrowExceptionUtil.ArgumentNotNullOrEmpty(relativePath, "relativePath"); return(Path.Combine(baseDirectory, relativePath)); }
/// <summary> /// Provided the extended method of string to format. /// </summary> /// <param name="format">the format string.</param> /// <param name="provider">the formating mechanism.</param> /// <param name="args">the arguments of the format stirng.</param> /// <returns>the result.</returns> public static string FormatWith(this string format, IFormatProvider provider, params object[] args) { ThrowExceptionUtil.ArgumentNotNull(format, "format"); return(string.Format(provider, format, args)); }
public static object Convert(object initialValue, CultureInfo culture, Type targetType) { //return initialValue; //ThrowExceptionUtil.ArgumentNotNull(initialValue, "initialValue"); ThrowExceptionUtil.ArgumentNotNull(targetType, "targetType"); if (initialValue == null) { if (targetType.IsValueType) { return(ReflectionUtil.CreateInstance(targetType)); } else { return(initialValue); } } else { string tempValue = initialValue as string; if (tempValue != null && tempValue.Length == 0) { // if the initial value is string, and the string is empty. if (targetType.IsValueType) { return(ReflectionUtil.CreateInstance(targetType)); } } } if (initialValue == DBNull.Value) { if (targetType.IsValueType) { return(ReflectionUtil.CreateInstance(targetType)); } else { return(null); } } Type t = initialValue.GetType(); if (targetType == t || targetType.IsAssignableFrom(t)) { return(initialValue); } if (targetType.IsGenericType && (targetType.GetGenericTypeDefinition() == typeof(Nullable <>))) { targetType = Nullable.GetUnderlyingType(targetType); } if (targetType == t || targetType.IsAssignableFrom(t)) { return(initialValue); } if ((initialValue is string) && typeof(Type).IsAssignableFrom(targetType)) { return(Type.GetType((string)initialValue, true)); } if ((targetType.IsInterface || targetType.IsGenericTypeDefinition) || targetType.IsAbstract) { throw new ArgumentException("Target type {0} is not a value type or a non-abstract class.".FormatWith(targetType), "targetType"); } if ((initialValue is IConvertible) && typeof(IConvertible).IsAssignableFrom(targetType)) { if (targetType.IsEnum) { return(Enum.Parse(targetType, initialValue.ToString(), true)); } return(System.Convert.ChangeType(initialValue, targetType, culture)); } if ((initialValue is string) && (targetType == typeof(Guid))) { return(new Guid((string)initialValue)); } TypeConverter converter = TypeDescriptor.GetConverter(t); if ((converter != null) && converter.CanConvertTo(targetType)) { return(converter.ConvertTo(null, culture, initialValue, targetType)); } TypeConverter converter2 = TypeDescriptor.GetConverter(targetType); if ((converter2 != null) && converter2.CanConvertFrom(t)) { return(converter2.ConvertFrom(null, culture, initialValue)); } return(null); }