public TaskManager() { var ps = typeof(ITaskJob).GetAllSubclasses(); _jobPlugins = ps.Where(e => e.IsClass).Select(e => TypeX.CreateInstance(e) as ITaskJob).ToArray(); _jobProcessTimer = new Timer[_jobPlugins.Length]; }
static Boolean GetControlValue(ControlBase control, out Object value) { TypeX tx = control.GetType(); String name = tx.GetCustomAttributeValue <ControlValuePropertyAttribute, String>(); PropertyInfoX pix = null; if (!String.IsNullOrEmpty(name)) { pix = PropertyInfoX.Create(tx.BaseType, name); } if (pix == null) { pix = PropertyInfoX.Create(tx.BaseType, "Value"); } if (pix == null) { pix = PropertyInfoX.Create(tx.BaseType, "Text"); } if (pix != null) { value = pix.GetValue(control); return(true); } value = null; return(false); }
/// <summary>从提供者和连接字符串猜测数据库处理器</summary> /// <param name="connStr"></param> /// <param name="provider"></param> /// <returns></returns> internal static Type GetProviderType(String connStr, String provider) { if (!String.IsNullOrEmpty(provider)) { //Type type = XCodeService.ResolveType<IDatabase>(m => "" + m.Identity != "" && GetDefault((DatabaseType)m.Identity).Support(provider)); //if (type != null) return type; foreach (var item in XCodeService.Container.ResolveAllMaps(typeof(IDatabase))) { if ("" + item.Identity == "") { continue; } var db = item.Instance as IDatabase; if (db != null && db.Support(provider)) { return(item.ImplementType); } } var type = TypeX.GetType(provider, true); if (type != null) { XCodeService.Register <IDatabase>(type, provider); } return(type); } else { // 这里的默认值来自于上面Reg里面的最后那个 return(XCodeService.ResolveType <IDatabase>(String.Empty)); } }
public static SqlCeEngine Create(String connstr) { if (EngineType == null) { return(null); } if (String.IsNullOrEmpty(connstr)) { return(null); } try { var e = TypeX.CreateInstance(EngineType, connstr); if (e == null) { return(null); } var sce = new SqlCeEngine(); sce.Engine = e; return(sce); } catch { return(null); } }
/// <summary>写入枚举数据,复杂类型使用委托方法进行处理</summary> /// <param name="value">对象</param> /// <param name="type">类型</param> /// <param name="callback">使用指定委托方法处理复杂数据</param> /// <returns>是否写入成功</returns> public virtual Boolean WriteEnumerable(IEnumerable value, Type type, WriteObjectCallback callback) { if (value == null) { return(true); } type = CheckAndWriteType("WriteEnumerableType", value, type); //type = value.GetType(); if (type != null && !typeof(IEnumerable).IsAssignableFrom(type)) { throw new InvalidOperationException("目标类型不是枚举类型!"); } // 计算元素类型,如果无法计算,这里不能处理,否则能写不能读(因为不知道元素类型) var elementType = TypeX.GetElementType(type); //if (elementType == null) return false; Int32 i = 0; foreach (var item in value) { Depth++; if (!WriteItem(item, elementType, i++, callback)) { return(false); } Depth--; } return(true); }
private void btnAddTable_Click(object sender, EventArgs e) { if (Tables == null || Tables.Count < 1) { return; } Type type = Tables[0].GetType(); if (type == null) { return; } IDataTable table = TypeX.CreateInstance(type) as IDataTable; if (table == null) { return; } Tables.Add(table); table.ID = Tables.Count; table.Name = "NewTable" + table.ID; table.Description = "新建表" + table.ID; SetTables(Tables, Tables.Count - 1); }
/// <summary>读取</summary> /// <param name="reader"></param> /// <param name="value"></param> public static void ReadXml(XmlReader reader, Object value) { foreach (var item in GetProperties(value.GetType())) { if (!item.Property.CanRead) { continue; } if (AttributeX.GetCustomAttribute <XmlIgnoreAttribute>(item.Member, false) != null) { continue; } var v = reader.GetAttribute(item.Name); if (String.IsNullOrEmpty(v)) { continue; } if (item.Type == typeof(String[])) { var ss = v.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries); item.SetValue(value, ss); } else { item.SetValue(value, TypeX.ChangeType(v, item.Type)); } } //reader.Skip(); }
private static Boolean SetControlValue(Control control, Object value) { TypeX tx = control.GetType(); String name = tx.GetCustomAttributeValue <ControlValuePropertyAttribute, String>(); PropertyInfoX pix = null; if (!String.IsNullOrEmpty(name)) { pix = PropertyInfoX.Create(tx.Type, name); } if (pix == null) { pix = PropertyInfoX.Create(tx.Type, "Value"); } if (pix == null) { pix = PropertyInfoX.Create(tx.Type, "Text"); } if (pix != null) { if (value == null && pix.Type.IsValueType) { return(false); } pix.SetValue(control, value); return(true); } return(false); }
public static DriverBase CreateDriver(IConfigurationSource src = null, string typename = TypeName) { lock (lockobj) { string driverString; string connString; try { if (db != null) { return(db); } if (Starter.Properties == null) { Starter.Initialize(typename, src); } Starter.Properties.TryGetValue(Environment.ConnectionDriver, out driverString); Starter.Properties.TryGetValue(Environment.ConnectionString, out connString); TypeX typex = TypeX.Create(ReflectHelper.ClassForName(driverString)); db = (DriverBase)typex.CreateInstance(); //db = (DriverBase)Activator.CreateInstance(ReflectHelper.ClassForName(driverString)); db.ConnString = connString; return(db); } catch (Exception ex) { throw ex; } } }
public IEnumerable <T> BindModel <T>(object source) { DataTable dt = (DataTable)source; IEnumerable <DataColumn> dclist = dt.Columns.Cast <DataColumn>(); List <T> modellist = new List <T>(); foreach (DataRow dr in dt.Rows) { TypeX typex = TypeX.Create(typeof(T)); T modelInstance = (T)typex.CreateInstance(); //T modelInstance = (T)Activator.CreateInstance(typeof(T)); foreach (PropertyInfo property in typeof(T).GetProperties()) { DataColumn dc = dclist.Where(item => string.Compare(property.Name, item.ColumnName, true) == 0).FirstOrDefault(); if (null != dc) { PropertyInfoX propx = PropertyInfoX.Create(property); propx.SetValue(modelInstance, dr[dc.ColumnName]); //property.SetValue(modelInstance, Convert.ChangeType(dr[dc.ColumnName], property.PropertyType),null); } } modellist.Add(modelInstance); } return(modellist); }
/// <summary>根据名称获取默认提供者</summary> /// <param name="dbType"></param> /// <returns></returns> internal static IDatabase GetDefault(Type dbType) { if (dbType == null) { return(null); } return(defaultDbs2.GetItem(dbType, dt => (IDatabase)TypeX.CreateInstance(dt))); }
public void TestFastPropertyGet() { var a = new { ID = 1, Name = "张三" }; TypeX type = a.GetType(); Assert.AreEqual(1, type.GetProperty("ID").GetValue(a)); Assert.AreEqual("张三", type.GetProperty("Name").GetValue(a)); }
/// <summary>尝试从指定数据行中读取指定名称列的数据</summary> /// <typeparam name="T"></typeparam> /// <param name="dr"></param> /// <param name="name">名称</param> /// <param name="value">数值</param> /// <returns></returns> protected static Boolean TryGetDataRowValue <T>(DataRow dr, String name, out T value) { value = default(T); if (dr == null || !dr.Table.Columns.Contains(name) || dr.IsNull(name)) { return(false); } Object obj = dr[name]; // 特殊处理布尔类型 if (Type.GetTypeCode(typeof(T)) == TypeCode.Boolean && obj != null) { if (obj is Boolean) { value = (T)obj; return(true); } if ("YES".EqualIgnoreCase(obj.ToString())) { value = (T)(Object)true; return(true); } if ("NO".EqualIgnoreCase(obj.ToString())) { value = (T)(Object)false; return(true); } } try { if (obj is T) { value = (T)obj; } else { if (obj != null) { var tx = TypeX.Create(obj.GetType()); if (tx.IsInt) { var n = Convert.ToUInt64(obj); if (n == UInt32.MaxValue && Type.GetTypeCode(typeof(T)) == TypeCode.Int32) { obj = -1; } } } value = (T)Reflect.ChangeType(obj, typeof(T)); } } catch { return(false); } return(true); }
private void StartAttachServers() { var dic = Config.GetConfigByPrefix("XAgent.AttachServer."); if (dic != null && dic.Count > 0) { // 实例化 foreach (var item in dic) { if (!item.Key.IsNullOrWhiteSpace() && !item.Value.IsNullOrWhiteSpace()) { WriteLine(""); WriteLine("正在加载:{0} = {1}", item.Key, item.Value); var type = TypeX.GetType(item.Value, true); if (type != null) { var service = TypeX.CreateInstance(type) as IServer; if (service != null) { AttachServers[item.Key] = service; } } } } // 加载配置。【服务名.属性】的配置方式 foreach (var item in AttachServers) { if (item.Value != null) { var type = item.Value.GetType(); // 遍历所有属性,查找指定的设置项 foreach (var pi in type.GetProperties(true)) { var name = String.Format("XAgent.{0}.{1}", item.Key, pi.Name); Object value = null; // 读取配置,并赋值 if (Config.TryGetConfig(name, pi.PropertyType, out value)) { WriteLine("配置:{0} = {1}", name, value); //PropertyInfoX.Create(pi).SetValue(item.Value, value); item.Value.SetValue(pi, value); } } } } // 启动 foreach (var item in AttachServers) { if (item.Value != null) { WriteLine("启动:{0}", item.Key); item.Value.Start(); } } } }
/// <summary>创建实例</summary> /// <returns></returns> protected virtual T Create() { if (OnCreate != null) { return(OnCreate()); } return((T)TypeX.CreateInstance(typeof(T))); }
/// <summary>从数据读写器加载数据。无数据时返回空集合而不是null。</summary> /// <param name="dr">数据读写器</param> /// <returns>实体数组</returns> public IEntityList LoadData(IDataReader dr) { //if (dr == null) return null; //// 先移到第一行,要取字段名等信息 //if (!dr.Read()) return null; // 准备好实体列表 IEntityList list = TypeX.CreateInstance(typeof(EntityList <>).MakeGenericType(EntityType)) as IEntityList; if (dr == null) { return(list); } // 先移到第一行,要取字段名等信息 if (!dr.Read()) { return(list); } List <FieldItem> ps = new List <FieldItem>(); List <String> exts = new List <String>(); for (int i = 0; i < dr.FieldCount; i++) { String name = dr.GetName(i); FieldItem fi = null; if (FieldItems.TryGetValue(name, out fi)) { ps.Add(fi); } else { exts.Add(name); } } // 遍历每一行数据,填充成为实体 do { // 由实体操作者创建实体对象,因为实体操作者可能更换 IEntity entity = Factory.Create(); foreach (FieldItem item in ps) { SetValue(entity, item.Name, item.Type, dr[item]); } foreach (String item in exts) { SetValue(entity, item, null, dr[item]); } list.Add(entity); } while (dr.Read()); return(list); }
protected T GetData <T>(string name) { object data = this.GetData(name); if (data == null) { return(default(T)); } return((T)TypeX.ChangeType(data, typeof(T))); }
/// <summary>获取自定义属性的值。可用于ReflectionOnly加载的程序集</summary> /// <typeparam name="TAttribute"></typeparam> /// <typeparam name="TResult"></typeparam> /// <param name="target">目标对象</param> /// <param name="inherit">是否递归</param> /// <returns></returns> public static TResult GetCustomAttributeValue <TAttribute, TResult>(this MemberInfo target, Boolean inherit = true) where TAttribute : Attribute { if (target == null) { return(default(TResult)); } try { var list = CustomAttributeData.GetCustomAttributes(target); if (list != null && list.Count > 0) { foreach (var item in list) { if (!TypeX.Equal(typeof(TAttribute), item.Constructor.DeclaringType)) { continue; } var args = item.ConstructorArguments; if (args != null && args.Count > 0) { return((TResult)args[0].Value); } } } if (inherit && target is Type) { target = (target as Type).BaseType; if (target != null && target != typeof(Object)) { return(GetCustomAttributeValue <TAttribute, TResult>(target, inherit)); } } } catch { // 出错以后,如果不是仅反射加载,可以考虑正面来一次 if (!target.Module.Assembly.ReflectionOnly) { //var att = GetCustomAttribute<TAttribute>(target, inherit); var att = target.GetCustomAttribute <TAttribute>(inherit); if (att != null) { var pi = typeof(TAttribute).GetProperties().FirstOrDefault(p => p.PropertyType == typeof(TResult)); if (pi != null) { return((TResult)att.GetValue(pi)); } } } } return(default(TResult)); }
private void SetEntityItem(IEntity entity, FieldItem field, Object value) { // 先转为目标类型 value = TypeX.ChangeType(value, field.Type); // 如果是字符串,并且为空,则让它等于实体里面的值,避免影响脏数据 if (field.Type == typeof(String) && String.IsNullOrEmpty((String)value) && String.IsNullOrEmpty((String)entity[field.Name])) { value = entity[field.Name]; } entity.SetItem(field.Name, value); }
/// <summary>获取数据,主要处理类型转换</summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <returns></returns> protected T GetData <T>(String name) { Object obj = GetData(name); if (obj == null) { return(default(T)); } return((T)TypeX.ChangeType(obj, typeof(T))); }
private static IObjectContainer Reg <T>(this IObjectContainer container, Object id = null) { IDatabase db = TypeX.CreateInstance(typeof(T)) as IDatabase; if (id == null) { id = db.DbType; } // 把这个实例注册进去,作为默认实现 return(container.Register(typeof(IDatabase), null, db, id)); }
/// <summary>尝试获取指定名称的设置项</summary> /// <param name="name"></param> /// <param name="type"></param> /// <param name="value"></param> /// <returns></returns> public static Boolean TryGetConfig(String name, Type type, out Object value) { value = null; try { NameValueCollection nvs = AppSettings; if (nvs == null || nvs.Count < 1) { return(false); } String str = nvs[name]; if (String.IsNullOrEmpty(str)) { return(false); } TypeCode code = Type.GetTypeCode(type); if (code == TypeCode.String) { value = str; } else if (code == TypeCode.Int32) { value = Convert.ToInt32(str); } else if (code == TypeCode.Boolean) { Boolean b = false; if (str == "1" || str.EqualIgnoreCase(Boolean.TrueString)) { value = true; } else if (str == "0" || str.EqualIgnoreCase(Boolean.FalseString)) { value = false; } else if (Boolean.TryParse(str.ToLower(), out b)) { value = b; } } else { value = TypeX.ChangeType(str, type); } return(true); } catch (ConfigurationErrorsException) { return(false); } }
/// <summary>加载插件。此时是加载所有插件,无法识别哪些是需要的</summary> public void Load() { var list = new List <IPlugin>(); // 此时是加载所有插件,无法识别哪些是需要的 foreach (var item in LoadPlugins()) { if (item != null) { list.Add(TypeX.CreateInstance(item) as IPlugin); } } _Plugins = list; }
/// <summary>读取实现了可序列化接口的对象</summary> /// <param name="type">要读取的对象类型</param> /// <param name="value">要读取的对象</param> /// <param name="callback">处理成员的方法</param> /// <returns>是否读取成功</returns> public override bool ReadSerializable(Type type, ref object value, ReadObjectCallback callback) { if (!typeof(IXmlSerializable).IsAssignableFrom(type)) { return(base.ReadSerializable(type, ref value, callback)); } if (value == null) { value = TypeX.CreateInstance(type); } ((IXmlSerializable)value).ReadXml(Reader); return(true); }
static String GetName(Type type) { if (type.HasElementType) { return("ArrayOf" + GetName(type.GetElementType())); } String name = TypeX.Create(type).Name; name = name.Replace("<", "_"); //name = name.Replace(">", "_"); name = name.Replace(",", "_"); name = name.Replace(">", ""); return(name); }
/// <summary> /// 从流中读取消息 /// </summary> /// <param name="stream"> /// </param> /// <returns> /// The <see cref="EntityBase" />. /// </returns> public static TtsEntity Read(Stream stream) { var ms = stream; var start = ms.Position; ms.Position = 0; // 读取命令码 var function = (TtsFunction)ms.ReadByte(); // 读取了响应类型和消息类型后,动态创建消息对象 var type = ObjectContainer.Current.ResolveType <IResponse>(function); var entity = TypeX.CreateInstance(type) as TtsEntity; entity.Function = function; return(entity); }
static SpacePluginProvider() { //try //{ // _sp = (SpacePluginBase)Activator.CreateInstance(Type.GetType("Discuz.Space.SpacePlugin, Discuz.Space", false, true)); //} //catch //{ // _sp = null; //} foreach (var item in AssemblyX.FindAllPlugins(typeof(SpacePluginBase), true)) { _sp = TypeX.CreateInstance(item) as SpacePluginBase; break; } }
static MallPluginProvider() { //try //{ // _sp = (MallPluginBase)Activator.CreateInstance(Type.GetType("BBX.Mall.MallPlugin, BBX.Mall", false, true)); //} //catch //{ // _sp = null; //} foreach (var item in AssemblyX.FindAllPlugins(typeof(MallPluginBase), true)) { _sp = TypeX.CreateInstance(item) as MallPluginBase; break; } }
/// <summary>指定键是否为空。一般业务系统设计不允许主键为空,包括自增的0和字符串的空</summary> /// <param name="key">键值</param> /// <param name="type">类型</param> /// <returns></returns> public static Boolean IsNullKey(Object key, Type type) { if (key == null) { return(true); } if (type == null) { type = key.GetType(); } key = TypeX.ChangeType(key, type); //由于key的实际类型是由类型推倒而来,所以必须根据实际传入的参数类型分别进行装箱操作 //如果不根据类型分别进行会导致类型转换失败抛出异常 switch (Type.GetTypeCode(type)) { case TypeCode.Int16: return(((Int16)key) <= 0); case TypeCode.Int32: return(((Int32)key) <= 0); case TypeCode.Int64: return(((Int64)key) <= 0); case TypeCode.UInt16: return(((UInt16)key) <= 0); case TypeCode.UInt32: return(((UInt32)key) <= 0); case TypeCode.UInt64: return(((UInt64)key) <= 0); case TypeCode.String: return(String.IsNullOrEmpty((String)key)); default: break; } if (type == typeof(Guid)) { return(((Guid)key) == Guid.Empty); } if (type == typeof(Byte[])) { return(((Byte[])key).Length <= 0); } return(false); }
/// <summary> /// 根据实体名称,获取此实体字段名称的数组List<string> /// </summary> /// <param name="typeName">完整实体名称, [命名空间.实体名称]</param> /// <returns></returns> public static List <string> GetEntityFieldList(this string tableName) { List <string> list = new List <string>(); tableName = string.Format("{0}.{1}", ConfigHelper.GetAppSettings("EntitySpaceName"), tableName); TypeX EntityType = TypeX.Create(TypeX.GetType(tableName, true)); //根据类的完整名称建立类的类型,用于动态创建类 如: Clump.Mobile.Models.NewsInfo Object objEntity = EntityType.CreateInstance(); //动态建立类的对象 实体类的对象Object objEntity = EntityType.CreateInstance(true);意思是在创建实体对象时 A a = new A(true) PropertyInfo[] props = objEntity.GetType().GetProperties(); //获取此对象的,字段集合 object propertValue = String.Empty; foreach (PropertyInfo item in props) { list.Add(item.Name); } return(list); }