public static IEnumerable <Type> ExplodeDependencyTree(Type t, int level = 0, List <Type> dependedTypes = null) { var members = ReflectionTool.FieldsAndPropertiesOf(t); dependedTypes = dependedTypes ?? new List <Type>(); //Console.WriteLine($"EDT | {new String(' ', level)} -> {t.Name}"); foreach (var m in members) { var fk = m.GetCustomAttribute <ForeignKeyAttribute>(); if (fk != null) { if (!dependedTypes.Contains(fk.RefType)) { dependedTypes.Add(fk.RefType); yield return(fk.RefType); foreach (var innerDep in ExplodeDependencyTree(fk.RefType, level++, dependedTypes)) { if (!dependedTypes.Contains(innerDep)) { yield return(innerDep); } } } } } }
/// <summary> /// Build the entire type tree and type cache /// </summary> private void BuildTypeTree() { // Start with all public types var allTypes = new List <Type>(); var registeredTypes = Container.GetRegisteredImplementations(typeof(IResource)).ToList(); // Load full type tree from registered resources foreach (var type in registeredTypes.Union(ReflectionTool.GetPublicClasses <Resource>())) { var buffer = type; // Exclude the different base types from "Moryx.Resources" from the type tree do { if (buffer.IsGenericType) // Generic base types appear multiple times, use only the generic type { buffer = buffer.GetGenericTypeDefinition(); } if (!allTypes.Contains(buffer)) { allTypes.Add(buffer); } buffer = buffer.BaseType; } while (buffer != null && buffer != typeof(Resource)); } // Convert tree to TypeNodes objects RootType = Convert(typeof(Resource), allTypes, registeredTypes); }
public void ReadEmbeddedResourceFile() { var asm = ReflectionTool.LoadAssembly(typeof(ChartBase).Assembly.FullName); var swf = asm.GetEmbeddedResourceFile("line.swf"); Assert.IsNotNull(swf); }
public void Initialize(Type concreteType, IGenericMapperConfiguration config) { // Get JSON accessor var jsonColumn = typeof(IGenericColumns).GetProperty(config.JsonColumn); _jsonAccessor = ReflectionTool.PropertyAccessor <IGenericColumns, string>(jsonColumn); var baseProperties = typeof(TBase).GetProperties().Select(p => p.Name).ToArray(); var configuredProperties = config.PropertyConfigs.Select(cm => cm.PropertyName); var readOnlyProperties = concreteType.GetProperties() .Where(p => p.GetSetMethod() == null).Select(p => p.Name).ToArray(); // The json should not contain base, configured nor readonly properties var jsonIgnoredProperties = baseProperties .Concat(configuredProperties) .Concat(readOnlyProperties).ToArray(); _jsonSettings = JsonSettings.Minimal .Overwrite(j => j.ContractResolver = new DifferentialContractResolver <TReference>(jsonIgnoredProperties)); // Properties where no mapper should be created for: base and read only properties var mapperIgnoredProperties = baseProperties .Concat(readOnlyProperties).ToArray(); _configuredMappers = config.PropertyConfigs.Where(pc => !mapperIgnoredProperties.Contains(pc.PropertyName)) .Select(pc => MapperFactory.Create(pc, concreteType)).ToArray(); }
public DataBindingConnection(BaseViewModel viewModel, DataBindInfo dataBindInfo) { this.dataBindInfo = dataBindInfo; this.viewModel = viewModel; _getProperty = ReflectionTool.GetVmPropertyByName(viewModel.GetType(), dataBindInfo.propertyName); if (_getProperty == null) { Debug.LogErrorFormat("get property null {0}:{1}", viewModel.GetType(), dataBindInfo.propertyName); } ReflectionMethodItem item = ReflectionTool.GetComponentMethod(dataBindInfo.component.GetType(), dataBindInfo.invokeFunctionName, _getProperty.PropertyType); if (item == null) { Debug.LogErrorFormat("get invokeMethod null {0}", dataBindInfo.invokeFunctionName); } _invokeMethod = item.methodInfo; foreach (var bindingParameter in dataBindInfo.parameters) { _lstParameter.Add(new BindingParameterInfo(bindingParameter, viewModel)); } ps = new object[dataBindInfo.parameters.Length + 2]; ps[0] = dataBindInfo.component; }
public IQueryBuilder GenerateInsertQuery(IDataObject inputObject) { var type = inputObject.GetType(); QueryBuilder query = new QbFmt($"INSERT INTO {inputObject.GetType().Name}"); query.Append("("); query.Append(GenerateFieldsString(type, false)); query.Append(")"); query.Append("VALUES ("); var members = GetMembers(type); // members.RemoveAll(m => m.GetCustomAttribute<PrimaryKeyAttribute>() != null); for (int i = 0; i < members.Count; i++) { query.Append($"@{i + 1}", ReflectionTool.GetMemberValue(members[i], inputObject)); if (i < members.Count - 1) { query.Append(","); } } query.Append(")"); //query.Append("ON CONFLICT (" + GenerateKeysString(type) + ") DO UPDATE SET "); //var Fields = GetMembers(inputObject.GetType()); //for (int i = 0; i < Fields.Count; ++i) { // if (Fields[i].GetCustomAttribute(typeof(PrimaryKeyAttribute)) != null) // continue; // query.Append(String.Format("{0} = VALUES({0})", Fields[i].Name)); // if (i < Fields.Count - 1) { // query.Append(","); // } //} return(query); }
/// <summary> /// 根据放入AutoModelFilterDict的字段(要指定排序功能)自动生成一个对应的ModelSorter用于Sort排序,若SortRuleDict中没有规则,则返回null /// </summary> /// <returns></returns> public Comparison <T> GetModelSorter() { if (ModelSortRuleDict.IsNullOrEmptySet()) { return(null); } return(delegate(T modelX, T modelY) { int result = 0; //1,-1,0分别是大,小,相等,默认升序 Dictionary <string, KeyValuePair <Type, object> > modelxInfoDict = ReflectionTool.GetAllPropertyInfo <T>(modelX); //获取一个model字段的信息 foreach (var modelProperty in modelxInfoDict) { string fieldName = modelProperty.Key; Type type = modelProperty.Value.Key; if (ModelSortRuleDict.TryGetValue(fieldName, out KeyValuePair <int, bool> rule) && typeof(IComparable).IsAssignableFrom(type)) //若该字段有排序规则且实现了Comparable接口 { var xValue = modelProperty.Value.Value; //原始字段值 var yValue = typeof(T).GetProperty(fieldName)?.GetValue(modelY); //要比较的字段值 int weight = rule.Key; //该字段排序权重 if (rule.Value) { weight = -weight; //若该字段是降序则权重相反 } weight *= ((IComparable)xValue).CompareTo(yValue); result += weight; } } return result; }); }
public IQueryBuilder QueryIds <T>(List <T> rs) where T : IDataObject { var id = ReflectionTool.FieldsAndPropertiesOf(typeof(T)).FirstOrDefault(f => f.GetCustomAttribute <PrimaryKeyAttribute>() != null); var rid = ReflectionTool.FieldsAndPropertiesOf(typeof(T)).FirstOrDefault(f => f.GetCustomAttribute <ReliableIdAttribute>() != null); return(Qb.Fmt($"SELECT {id.Name}, {rid.Name} FROM {typeof(T).Name} WHERE") + Qb.In(rid.Name, rs, i => i.RID)); }
public void Initialize(PropertyMapperConfig config) { Config = config; // Create accessor for the column property var columnProp = typeof(IGenericColumns).GetProperty(config.Column); if (columnProp == null || columnProp.PropertyType != typeof(TColumn)) { throw new ArgumentException($"Column not found or type mismatch {config.PropertyName}"); } ColumnAccessor = ReflectionTool.PropertyAccessor <IGenericColumns, TColumn>(columnProp); // Retrieve and validate properties var objectProp = TargetType.GetProperty(config.PropertyName); if (objectProp == null) { throw new ArgumentException($"Target type {TargetType.Name} does not have a property {config.PropertyName}"); } // Create delegates for the object property as well ObjectAccessor = CreatePropertyAccessor(objectProp); }
public IQueryBuilder GetIdFromRid <T>(object Rid) where T : IDataObject, new() { var id = ReflectionTool.FieldsAndPropertiesOf(typeof(T)).FirstOrDefault(f => f.GetCustomAttribute <PrimaryKeyAttribute>() != null); var rid = ReflectionTool.FieldsAndPropertiesOf(typeof(T)).FirstOrDefault(f => f.GetCustomAttribute <ReliableIdAttribute>() != null); return(new QueryBuilder().Append($"SELECT {id.Name} FROM {typeof(T).Name} WHERE {rid.Name}=@???", Rid)); }
internal QueryBuilder GenerateUpdateValueParams(IDataObject tabelaInput, bool OmmitPk = true) { QueryBuilder Query = new QueryBuilder(); var lifi = GetMembers(tabelaInput.GetType()); int k = 0; for (int i = 0; i < lifi.Count; i++) { if (OmmitPk && lifi[i].GetCustomAttribute(typeof(PrimaryKeyAttribute)) != null) { continue; } foreach (CustomAttributeData att in lifi[i].CustomAttributes) { if (att.AttributeType == typeof(FieldAttribute)) { Object val = ReflectionTool.GetMemberValue(lifi[i], tabelaInput); Query.Append($"{lifi[i].Name} = @{(++k)}", val); if (i < lifi.Count - 1) { Query.Append(", "); } } } } return(Query); }
public IQueryBuilder GetCreationCommand(Type t) { String objectName = t.Name; var members = ReflectionTool .FieldsAndPropertiesOf(t).Where((m) => m?.GetCustomAttribute <FieldAttribute>() != null) .ToArray(); if (objectName == null || objectName.Length == 0) { return(null); } QueryBuilder CreateTable = new QbFmt($"CREATE TABLE IF NOT EXISTS {objectName} (\n"); for (int i = 0; i < members.Length; i++) { var info = members[i].GetCustomAttribute <FieldAttribute>(); CreateTable.Append(GetColumnDefinition(members[i], info)); CreateTable.Append(" "); CreateTable.Append(info.Options ?? ""); if (i != members.Length - 1) { CreateTable.Append(", \n"); } } CreateTable.Append(" );"); return(CreateTable); }
// Use this for initialization public static void Init(GameConsolePanelSettingConfig config, Action OnTriggerBoot) { Type[] types = ReflectionTool.GetChildTypes(typeof(BootFunctionBase)); Debug.Log("types.cout:" + types.Length); foreach (var item in types) { object obj = ReflectionTool.CreateDefultInstance(item); if (obj != null) { BootFunctionBase function = (BootFunctionBase)obj; bootFunctions.Add(function); } } foreach (var item in bootFunctions) { try { item.OnInit(config, OnTriggerBoot); } catch (Exception e) { Debug.LogError(e); } } }
/// <summary> /// Configure storage for <see cref="ProductInstance"/> /// </summary> public string ConfigureInstance(string instanceType) { var types = ReflectionTool.GetPublicClasses <ProductInstance>(); var instance = types.FirstOrDefault(p => p.Name == instanceType); if (instance == null) { return($"Found no instance type {instanceType ?? string.Empty}!\n" + "Available types: " + string.Join(", ", types.Select(t => t.Name))); } var result = string.Empty; if (Config.InstanceStrategies.Any(s => s.TargetType == instanceType)) { result += $"Product {instanceType} already has an InstanceStrategy configured. Overwriting configs is not supported!\n"; } else { var instanceConfig = StrategyConfig <IProductInstanceStrategy, ProductInstanceConfiguration, ProductInstance>(instance); if (instanceConfig == null) { result += $"Found no matching instance strategy for {instanceType}. Make sure you declared the '{nameof(StrategyConfigurationAttribute)}'!\n"; } else { Config.InstanceStrategies.Add(instanceConfig); result += $"Selected InstanceStrategy {instanceConfig.PluginName} for {instanceType}."; } } return(result); }
/// <summary> /// Отладочная информация поля /// </summary> private void DrawHelpers() { var cells = ReflectionTool.GetField <CellCollection>(Target, "_cells"); if (cells == null) { return; } var currentCellPos = ReflectionTool.GetField <Vector2Int>(Target, "_currentCellPosition"); var zoom = ReflectionTool.GetField <ZoomControl>(Target, "_zoom"); var precision = zoom.GetZoomPrecision(); for (int i = 0; i < cells._cells.Length; i++) { var cell = cells._cells[i]; if (cell == null) { continue; } var rect = cell.GetRect(precision); bool isVisible = cells.IsFullGeneratedCell(currentCellPos, cell.Pos); DrawRect(rect, isVisible ? Color.blue : Color.red, 1f, precision); } }
public ProductCustomization GetCustomization() { return(ExecuteCall <ProductCustomization>(delegate { return new ProductCustomization { ProductTypes = ReflectionTool .GetPublicClasses <ProductType>(new IsConfiguredFilter(Config.TypeStrategies).IsConfigured) .Select(Converter.ConvertProductType).ToArray(), RecipeTypes = ReflectionTool .GetPublicClasses <IProductRecipe>(new IsConfiguredFilter(Config.RecipeStrategies).IsConfigured) .Select(rt => new RecipeDefinitionModel { Name = rt.Name, DisplayName = rt.GetDisplayName() ?? rt.Name, HasWorkplans = typeof(IWorkplanRecipe).IsAssignableFrom(rt) }).ToArray(), Importers = ProductManager.Importers.Select(i => new ProductImporter { Name = i.Name, Parameters = ConvertParameters(i.Parameters) }).ToArray() }; })); }
private static void RegisterRepositories() { var types = typeof(TContext).Assembly.GetTypes(); var repoApis = from type in types let genericApi = type.GetInterfaces().FirstOrDefault(i => i.GetGenericArguments().Length == 1 && typeof(IRepository <>) == i.GetGenericTypeDefinition()) where type.IsInterface && genericApi != null select new { RepoApi = type, GenericApi = genericApi }; foreach (var apiPair in repoApis) { Type repoProxy; // Find implementations for the RepoAPI, which will also fit the generic API because of the inheritance var implementations = types.Where(t => t.IsClass && apiPair.RepoApi.IsAssignableFrom(t)).ToList(); if (implementations.Count == 0) { repoProxy = ProxyBuilder.Build(apiPair.RepoApi); } else { var selectedImpl = implementations.First(); repoProxy = ProxyBuilder.Build(apiPair.RepoApi, selectedImpl); } var constructorDelegate = ReflectionTool.ConstructorDelegate <Repository>(repoProxy); // Register constructor for both interfaces Repositories[apiPair.RepoApi] = Repositories[apiPair.GenericApi] = constructorDelegate; } }
public override ValidationErrors Validate() { ValidationErrors ve = new ValidationErrors(); var myType = this.GetType(); var myValues = new List <MemberInfo>(); myValues.AddRange(this.GetType().GetFields()); myValues.AddRange(this.GetType().GetProperties()); T obj = obj = (T)(IBusinessObject)this; foreach (var a in ValidationRules()) { foreach (var err in a.Validate(obj)) { ve.Add(err); } } // Validations foreach (var field in myValues.Where((f) => f.GetCustomAttribute <ValidationAttribute>() != null)) { var vAttribute = field.GetCustomAttribute <ValidationAttribute>(); if (vAttribute != null) { foreach (var a in vAttribute.Validate(field, ReflectionTool.GetMemberValue(field, this))) { ve.Add(a); } } } return(ve); }
/// <inheritdoc /> public void Initialize() { LoggerManagement.ActivateLogging(this); var dbContextTypes = ReflectionTool.GetPublicClasses(typeof(DbContext), delegate(Type type) { var modelAttr = type.GetCustomAttribute <ModelConfiguratorAttribute>(); return(modelAttr != null); }); _knownModels = dbContextTypes .Select(dbContextType => new { DbContextType = dbContextType, ModelConfiguratorAttr = dbContextType.GetCustomAttribute <ModelConfiguratorAttribute>() }).Select(t => { var wrapper = new ModelWrapper { DbContextType = t.DbContextType, Configurator = (IModelConfigurator)Activator.CreateInstance(t.ModelConfiguratorAttr.ConfiguratorType) }; return(wrapper); }).ToArray(); foreach (var wrapper in _knownModels) { var configuratorType = wrapper.Configurator.GetType(); var logger = Logger.GetChild(configuratorType.Name, configuratorType); wrapper.Configurator.Initialize(wrapper.DbContextType, ConfigManager, logger); } }
private static object JsonObjectToList(object obj, Type itemType) { IList <object> listData = obj as IList <object>; Type listType = list_Type.MakeGenericType(itemType); object list = ReflectionTool.CreateDefultInstance(listType); if (listData == null || listData.Count == 0) { return(list); } MethodInfo addMethod = listType.GetMethod("Add"); for (int i = 0; i < listData.Count; i++) { object obj0 = listData[i]; obj0 = ChangeJsonDataToObjectByType(itemType, obj0); if (obj0 == null) { continue; } addMethod.Invoke(list, new object[] { obj0 }); } return(list); }
public void Init(NetworkServerManager netManager) { this.netManager = netManager; allService.Clear(); Type[] childTypes = ReflectionTool.FastGetChildTypes(typeof(ServiceBase)); foreach (var item in childTypes) { if (item.IsAbstract) { continue; } Add(item); } foreach (var item in allService) { try { item.Value.OnInit(); } catch (Exception e) { Debug.LogError(e); } } }
/// <summary> /// Configure storage for <see cref="ProductRecipe"/> /// </summary> public string ConfigureRecipe(string recipeType) { var types = ReflectionTool.GetPublicClasses <IProductRecipe>(); var recipe = types.FirstOrDefault(p => p.Name == recipeType); if (recipe == null) { return($"Found no recipe type {recipeType ?? string.Empty}!\n" + "Available types: " + string.Join(", ", types.Select(t => t.Name))); } var result = string.Empty; if (Config.RecipeStrategies.Any(s => s.TargetType == recipeType)) { result += $"Recipe {recipeType} already has a RecipeStrategy configured. Overwriting configs is not supported!\n"; } else { // ProductionRecipe is technically not the correct base type, BUT it defines all relevant properties, which is the only thing that matters var recipeConfig = StrategyConfig <IProductRecipeStrategy, ProductRecipeConfiguration, ProductionRecipe>(recipe); if (recipeConfig == null) { result += $"Found no matching recipe strategy for {recipeType}. Make sure you declared the '{nameof(StrategyConfigurationAttribute)}'!\n"; } else { Config.RecipeStrategies.Add(recipeConfig); result += $"Selected RecipeStrategy {recipeConfig.PluginName} for {recipeType}."; } } return(result); }
/// <summary>输入的创建</summary> public static T Create <T>() where T : BaseInput { var rType = typeof(T); var rInput = ReflectionTool.Construct(rType) as T; return(rInput); }
public IProductRecipe ConvertRecipeBack(RecipeModel recipe, IProductType productType) { IProductRecipe productRecipe; if (recipe.Id == 0) { var type = ReflectionTool.GetPublicClasses <IProductRecipe>(t => t.Name == recipe.Type).First(); productRecipe = (IProductRecipe)Activator.CreateInstance(type); } else { productRecipe = RecipeManagement.Get(recipe.Id); } productRecipe.Name = recipe.Name; productRecipe.Revision = recipe.Revision; productRecipe.State = recipe.State; // Only load workplan if it changed var workplanRecipe = productRecipe as IWorkplanRecipe; if (workplanRecipe != null && workplanRecipe.Workplan?.Id != recipe.WorkplanId) { workplanRecipe.Workplan = WorkplanManagement.LoadWorkplan(recipe.WorkplanId); } if (productRecipe.Product == null) { productRecipe.Product = productType; } switch (recipe.Classification) { case RecipeClassificationModel.Unset: productRecipe.Classification = RecipeClassification.Unset; break; case RecipeClassificationModel.Default: productRecipe.Classification = RecipeClassification.Default; break; case RecipeClassificationModel.Alternative: productRecipe.Classification = RecipeClassification.Alternative; break; case RecipeClassificationModel.Intermediate: productRecipe.Classification = RecipeClassification.Intermediate; break; case RecipeClassificationModel.Part: productRecipe.Classification = RecipeClassification.Part; break; default: throw new ArgumentOutOfRangeException(); } EntryConvert.UpdateInstance(productRecipe, recipe.Properties, RecipeSerialization); return(productRecipe); }
public void SingleClassTest(Type type) { Type[] result = ReflectionTool.GetPublicClasses(type); Assert.AreEqual(1, result.Length, "Unexpected number of classes."); Assert.True(result.Contains(type)); }
private IDictionary <string, Type> GetCapabilities() { #pragma warning disable 618 return(ReflectionTool.GetPublicClasses <ConcreteCapabilities>(type => _capabilitiesFilter(type)) .ToDictionary(t => t.Name, t => t)); #pragma warning restore 618 }
public IProductType CreateType(string type) { // TODO: Use type wrapper var productType = ReflectionTool.GetPublicClasses <ProductType>(t => t.Name == type).First(); var product = (ProductType)Activator.CreateInstance(productType); return(product); }
public RecipeModel CreateRecipe(string recipeType) { // TODO: Use type wrapper var type = ReflectionTool.GetPublicClasses <IProductRecipe>(t => t.Name == recipeType).First(); var recipe = (IProductRecipe)Activator.CreateInstance(type); return(ConvertRecipe(recipe)); }
/// <summary> /// 지정된 srcType이 baseType과 같거나 상속받은 클래스인가를 검사한다. /// </summary> /// <param name="srcType">검사할 타입</param> /// <param name="baseType">기본 타입</param> /// <returns></returns> public static bool IsSameOrSubclassOf(Type srcType, Type baseType) { return(ReflectionTool.IsSameOrSubclassOf(srcType, baseType)); //if(srcType == null || baseType == null) // return false; //return (Equals(srcType, baseType) || srcType.IsSubclassOf(baseType)); }
/// <summary> /// Property filter for explicit properties /// </summary> private bool ExplicitPropertyFilter(PropertyInfo prop) { if (!FilterExplicitProperties) { return(true); } return(!ReflectionTool.IsExplicitInterfaceImplementation(prop)); }