public static T ConvertToObject <T>(this IDictionary <string, object> dict) where T : class, new() { var obj = new T(); var clazz = ReflectionClass.Reflection(typeof(T)); foreach (var key in dict.Keys) { var propName = key.Substring(0, 1).ToUpper(); if (key.Length > 1) { propName += key.Substring(1); } var value = dict[key]; if (!clazz.Properties.TryGetValue(propName, out var prop)) { continue; } if (value == null) { continue; } var propType = prop.PropertyType; if (propType != value.GetType()) { var propValue = value.ChangeType(propType); prop.Setter(obj, propValue); } else { prop.Setter(obj, value); } } return(obj); }
public void TestMethod1() { var container = new UnityContainer(); container.RegisterType <IDBAccess, SqlDataAccess>(); Employee employee = container.Resolve <Employee>(); Console.WriteLine(employee._IDBAccess.connection); Rediff rediff = (Rediff)Activator.CreateInstance(typeof(Rediff)); rediff._name = "Nasreen"; rediff.PrintName(); Type type = Type.GetType("UnityContainerExam.ReflectionExam.ReflectionClass"); ReflectionClass reflectionClass = (ReflectionClass)Activator.CreateInstance(type, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { "yusoof", "mohmed" }, null); ReflectionClass reflectionClass1 = GenericReturn <ReflectionClass>(); Console.WriteLine(reflectionClass1._Property1); Console.WriteLine(reflectionClass1._Property2); Func <int, string> func1 = (int a) => String.Format("string {0}", a); Console.WriteLine(func1(1)); Console.WriteLine(func3()); Console.WriteLine(func4); }
public ChaosInvocationResp ProcessInvocation(ChaosInvocation chaosInvocation) { try { var realImplementObject = _serviceResolver.GetService(chaosInvocation.InterfaceTypeFullName); var realImplementType = realImplementObject.GetType(); var realImplementInfo = ReflectionClass.Reflection(realImplementType); var mi = FindMethod(realImplementInfo, chaosInvocation); var requestParameters = chaosInvocation.Parameters; var args = requestParameters.DeserializeToArguments(_serializer, _typeFinder) .ToArray(); var returnValue = mi.Func(realImplementObject, args); var invocationReply = ToChaosInvocationResp(chaosInvocation, returnValue); return(invocationReply); } catch (Exception ex) { var invocationReply = ToChaosInvocationResp(chaosInvocation, (object)null); invocationReply.Exception = SerializeException.CreateFromException(ex); return(invocationReply); } }
protected override IClass GetClass(Type type) { ICompilationUnit cu = new ReflectionProjectContent("TestName", "testlocation", new DomAssemblyName[0], ParserService.DefaultProjectContentRegistry).AssemblyCompilationUnit; IClass c = new ReflectionClass(cu, type, type.FullName, null); cu.ProjectContent.AddClassToNamespaceList(c); return(c); }
protected override IClass GetClass(Type type) { ICompilationUnit cu = new ReflectionProjectContent("TestName", "testlocation", new DomAssemblyName[0], new ProjectContentRegistry()).AssemblyCompilationUnit; ((ReflectionProjectContent)cu.ProjectContent).AddReferencedContent(mscorlib); IClass c = new ReflectionClass(cu, type, type.FullName, null); cu.ProjectContent.AddClassToNamespaceList(c); return(c); }
public ReflectionMethod(MethodBase methodBase, ReflectionClass declaringType) : base(declaringType, methodBase is ConstructorInfo ? "#ctor" : methodBase.Name) { if (methodBase is MethodInfo) { this.ReturnType = ReflectionReturnType.Create(this, ((MethodInfo)methodBase).ReturnType, false); } else if (methodBase is ConstructorInfo) { this.ReturnType = DeclaringType.DefaultReturnType; } foreach (ParameterInfo paramInfo in methodBase.GetParameters()) { this.Parameters.Add(new ReflectionParameter(paramInfo, this)); } if (methodBase.IsGenericMethodDefinition) { foreach (Type g in methodBase.GetGenericArguments()) { this.TypeParameters.Add(new DefaultTypeParameter(this, g)); } int i = 0; foreach (Type g in methodBase.GetGenericArguments()) { declaringType.AddConstraintsFromType(this.TypeParameters[i++], g); } } if (methodBase.IsStatic) { foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(methodBase)) { string attributeName = data.Constructor.DeclaringType.FullName; if (attributeName == "System.Runtime.CompilerServices.ExtensionAttribute" || attributeName == "Boo.Lang.ExtensionAttribute") { this.IsExtensionMethod = true; } } } ModifierEnum modifiers = ModifierEnum.None; if (methodBase.IsStatic) { modifiers |= ModifierEnum.Static; } if (methodBase.IsPrivate) { // I assume that private is used most and public last (at least should be) modifiers |= ModifierEnum.Private; } else if (methodBase.IsFamily || methodBase.IsFamilyOrAssembly) { modifiers |= ModifierEnum.Protected; } else if (methodBase.IsPublic) { modifiers |= ModifierEnum.Public; } else { modifiers |= ModifierEnum.Internal; } if (methodBase.IsVirtual) { modifiers |= ModifierEnum.Virtual; } if (methodBase.IsAbstract) { modifiers |= ModifierEnum.Abstract; } this.Modifiers = modifiers; }
public void GetFieldList_PropertyCount_ExactNumber() { // Arrange ReflectionClass rc = ReflectionCache.GetReflection(typeof(ExampleObject)); // Act int count = rc.Properties.Count; // Assert Assert.AreEqual(4, count); }
public void FindPropertyByName_PropertyExist_NotNull() { // Arrange ReflectionClass rc = ReflectionCache.GetReflection(typeof(ExampleObject)); // Act var property = rc.Properties["Property1"]; // Assert Assert.IsNotNull(property); }
public void FindMethodsByName_MethodNotExist_EmptyList() { // Arrange ReflectionClass rc = ReflectionCache.GetReflection(typeof(ExampleObject)); // Act var methods = rc.Methods["TestMethodNotExist"]; // Assert Assert.AreEqual(0, methods.Count); }
public void GetMethodList_MethodCount_WithoutPropertiesWithStandart() { // Arrange ReflectionClass rc = ReflectionCache.GetReflection(typeof(ExampleObject)); // Act int count = rc.Methods.Count; // Assert Assert.AreEqual(7, count); }
static void Main(string[] args) { var reflection = new ReflectionClass(); reflection.RunDistincted(); Console.WriteLine("Press any key to continue.."); Console.ReadKey(true); reflection.RunnAll(); Console.WriteLine("Press any key to quit.."); Console.ReadKey(true); }
public ReflectionMethod(MethodBase methodBase, ReflectionClass declaringType) : base(declaringType, methodBase is ConstructorInfo ? "#ctor" : methodBase.Name) { if (methodBase is MethodInfo) { MethodInfo m = ((MethodInfo)methodBase); this.ReturnType = ReflectionReturnType.Create(this, m.ReturnType, attributeProvider: m.ReturnTypeCustomAttributes); } else if (methodBase is ConstructorInfo) { this.ReturnType = DeclaringType.DefaultReturnType; } foreach (ParameterInfo paramInfo in methodBase.GetParameters()) { this.Parameters.Add(new ReflectionParameter(paramInfo, this)); } if (methodBase.IsGenericMethodDefinition) { foreach (Type g in methodBase.GetGenericArguments()) { this.TypeParameters.Add(new DefaultTypeParameter(this, g)); } int i = 0; foreach (Type g in methodBase.GetGenericArguments()) { ReflectionClass.AddConstraintsFromType(this.TypeParameters[i++], g); } } ModifierEnum modifiers = ModifierEnum.None; if (methodBase.IsStatic) { modifiers |= ModifierEnum.Static; } if (methodBase.IsPrivate) { // I assume that private is used most and public last (at least should be) modifiers |= ModifierEnum.Private; } else if (methodBase.IsFamily || methodBase.IsFamilyOrAssembly) { modifiers |= ModifierEnum.Protected; } else if (methodBase.IsPublic) { modifiers |= ModifierEnum.Public; } else { modifiers |= ModifierEnum.Internal; } if (methodBase.IsFinal) { modifiers |= ModifierEnum.Sealed; } else if (methodBase.IsAbstract) { modifiers |= ModifierEnum.Abstract; } else if (methodBase.IsVirtual) { if ((methodBase.Attributes & MethodAttributes.NewSlot) != 0) modifiers |= ModifierEnum.Virtual; else modifiers |= ModifierEnum.Override; } this.Modifiers = modifiers; ReflectionClass.AddAttributes(declaringType.ProjectContent, this.Attributes, CustomAttributeData.GetCustomAttributes(methodBase)); ApplySpecialsFromAttributes(this); }
internal ReflectionMethod(MethodInfo method, ReflectionClass parent) { this.method = method; this.parent = parent; this.returnType = this.method.ReturnType; this.attributes = new ReflectionAttributeList(this.method.GetCustomAttributes(true).OfType<Attribute>().ToList()); this.name = this.method.Name; this.parameters = this.method.GetParameters(); }
public void FindFieldByName_FieldNotExist_Null() { // Arrange ReflectionClass rc = ReflectionCache.GetReflection(typeof(ExampleObject)); // Act var property = rc.Properties["Field12"]; // Assert Assert.IsNull(property); }
private void AnalyBlockList(DataTable tb, DataRow dr, List <BlockInfoModel> blList, string dataKey) { int bimIndex = 0; int colIndex = 0; string colText = dataKey + "图形"; if (!tb.Columns.Contains(colText)) { // colNum++; DataColumn dc = new DataColumn(colText); tb.Columns.Add(dc); } foreach (BlockInfoModel item in blList) { if (item.DbText != null) { foreach (DbTextModel lineMode in item.DbText) { dr[colText] += ReflectionClass.GetAllPropertyInfo <DbTextModel>(lineMode, "文本"); } } if (item.PolyLine != null) { foreach (PolyLineModel lineMode in item.PolyLine) { dr[colText] += ReflectionClass.GetAllPropertyInfo <PolyLineModel>(lineMode, "多段线"); } } if (item.Line != null && item.Line.Count > 0) { foreach (LineModel lineMode in item.Line) { dr[colText] += ReflectionClass.GetAllPropertyInfo <LineModel>(lineMode, "直线"); } } if (item.Hatch != null) { foreach (HatchModel lineMode in item.Hatch) { dr[colText] += ReflectionClass.GetAllPropertyInfo <HatchModel>(lineMode, "填充"); } } if (item.Circle != null && item.Circle.Count > 0) { foreach (CircleModel lineMode in item.Circle) { dr[colText] += ReflectionClass.GetAllPropertyInfo <CircleModel>(lineMode, "圆"); } } } }
public ReflectionProjectContent(Assembly assembly, string assemblyLocation, ProjectContentRegistry registry) : this(assembly.FullName, assemblyLocation, DomAssemblyName.Convert(assembly.GetReferencedAssemblies()), registry) { foreach (Type type in assembly.GetExportedTypes()) { string name = type.FullName; if (name.IndexOf('+') < 0) // type.IsNested { AddClassToNamespaceListInternal(new ReflectionClass(assemblyCompilationUnit, type, name, null)); } } ReflectionClass.AddAttributes(this, assemblyCompilationUnit.Attributes, CustomAttributeData.GetCustomAttributes(assembly)); InitializeSpecialClasses(); }
protected override IClass GetClass(Type type) { ICompilationUnit cu = new ReflectionProjectContent("TestName", "testlocation", new DomAssemblyName[0], ParserService.DefaultProjectContentRegistry).AssemblyCompilationUnit; IClass c = new ReflectionClass(cu, type, type.FullName, null); cu.ProjectContent.AddClassToNamespaceList(c); MemoryStream memory = new MemoryStream(); DomPersistence.WriteProjectContent((ReflectionProjectContent)c.ProjectContent, memory); memory.Position = 0; return(DomPersistence.LoadProjectContent(memory, ParserService.DefaultProjectContentRegistry).Classes.Single()); }
static void Main(string[] args) { Console.WriteLine("This is a Demo of BasicLearn.Reflection.Part1 "); ReflectionClass ReflectionClass1 = new ReflectionClass(1); ReflectionClass ReflectionClass2 = new ReflectionClass(2); Type _type = ReflectionClass1.GetType(); MethodInfo method = _type.GetMethod("MethodOne"); for (int i = 1; i <= 5; i++) method.Invoke(ReflectionClass2, new object[]{i}); Console.ReadKey(); }
/// <summary> /// 获取块参照数据 /// </summary> /// <param name="block2">块参照</param> /// <returns>提取的数据字符串</returns> public static List <string> AnalysisBlockReferenceFun(Autodesk.AutoCAD.DatabaseServices.BlockReference _br) { List <string> result = new List <string>(); Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; using (Transaction trans = db.TransactionManager.StartTransaction()) { result.Add("#BlockReference#"); result.Add(ReflectionClass.GetAllPropertyInfoEx(_br, "BlockReference")); BlockTableRecord block = trans.GetObject(_br.BlockTableRecord, OpenMode.ForWrite) as BlockTableRecord; foreach (ObjectId id in block) { DBObject ODB = id.GetObject(OpenMode.ForRead); if (ODB.GetRXClass().Equals(RXClass.GetClass(typeof(BlockReference)))) { BlockReference br = trans.GetObject(id, OpenMode.ForRead) as BlockReference; BlockTableRecord block1 = trans.GetObject(br.BlockTableRecord, OpenMode.ForWrite) as BlockTableRecord; result.Add("#Sub_BlockReference#"); result.Add(ReflectionClass.GetAllPropertyInfoEx(br, "Sub_BlockReference")); foreach (var item in block1) { result.Add("#" + item.GetObject(OpenMode.ForRead).GetRXClass().Name + "#"); result.Add(ReflectionClass.GetAllPropertyInfoEx(trans.GetObject(item, OpenMode.ForRead), item.GetObject(OpenMode.ForRead).GetRXClass().Name)); result.Add("#" + item.GetObject(OpenMode.ForRead).GetRXClass().Name + "#"); } result.Add("#Sub_BlockReference#"); break; } else { result.Add("#" + id.GetObject(OpenMode.ForRead).GetRXClass().Name + "#"); result.Add(ReflectionClass.GetAllPropertyInfoEx(trans.GetObject(id, OpenMode.ForRead), id.GetObject(OpenMode.ForRead).GetRXClass().Name)); result.Add("#" + id.GetObject(OpenMode.ForRead).GetRXClass().Name + "#"); } } } //扩展数据 result.Add("#BlockReference#"); return(result); }
void AddTypes(Collection <TypeDefinition> types) { foreach (TypeDefinition td in types) { if ((td.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.Public) { string name = td.FullName; if (name.Length == 0 || name[0] == '<') { continue; } name = ReflectionClass.SplitTypeParameterCountFromReflectionName(name); AddClassToNamespaceListInternal(new CecilClass(this.AssemblyCompilationUnit, null, td, name)); } } }
public static T ToSummary <T>(this IEnumerable <T> list) where T : class, new() { var summary = new T(); var clazzz = ReflectionClass.Reflection(typeof(T)); var first = true; foreach (var item in list) { foreach (var prop in clazzz.Properties.Values) { if (!prop.PropertyType.IsValueType) { continue; } var propValue = prop.Getter(item); if (first) { prop.Setter(summary, propValue); if (prop.PropertyType == typeof(DateTime)) { prop.Setter(summary, DateTime.Now); } } else { var sumValue = prop.Getter(summary); if (prop.PropertyType == typeof(decimal)) { sumValue = (decimal)sumValue + (decimal)propValue; } else if (prop.PropertyType == typeof(int)) { sumValue = (int)sumValue + (int)propValue; } else if (prop.PropertyType == typeof(long)) { sumValue = (long)sumValue + (long)propValue; } prop.Setter(summary, sumValue); } } first = false; } return(summary); }
protected override IClass GetClass(Type type) { ICompilationUnit cu = new ReflectionProjectContent("TestName", "testlocation", new DomAssemblyName[0], new ProjectContentRegistry()).AssemblyCompilationUnit; IClass c = new ReflectionClass(cu, type, type.FullName, null); cu.ProjectContent.AddClassToNamespaceList(c); MemoryStream memory = new MemoryStream(); DomPersistence.WriteProjectContent((ReflectionProjectContent)c.ProjectContent, memory); memory.Position = 0; ReflectionProjectContent loadedPC = DomPersistence.LoadProjectContent(memory, new ProjectContentRegistry()); loadedPC.AddReferencedContent(mscorlib); return(loadedPC.Classes.Single()); }
public static string GetDisplayTitle(this object obj) { var sb = new StringBuilder(); var delimiter = new StringBuilder(); var clazz = ReflectionClass.Reflection(obj.GetType()); var first = true; foreach (var prop in clazz.Properties.Values) { var propInfo = (PropertyInfo)prop.Info; var decimalAttr = propInfo.GetCustomAttribute <DecimalStringAttribute>(false); if (decimalAttr != null) { var value = prop.Getter(obj); if (!first) { sb.Append(" "); delimiter.Append(" "); } sb.Append(prop.Name.ToFixLenString(decimalAttr.MaxLength, AlignType.Right)); delimiter.Append(new String('-', decimalAttr.MaxLength)); first = false; continue; } var displayAttr = propInfo.GetCustomAttribute <DisplayStringAttribute>(false); if (displayAttr != null) { if (!first) { sb.Append(" "); delimiter.Append(" "); } var value = prop.Getter(obj); sb.Append(displayAttr.ToDisplayString(prop.Name)); delimiter.Append(new String('-', displayAttr.MaxLength)); first = false; continue; } } return(sb.ToString() + "\r\n" + delimiter.ToString()); }
public void ReflectionParserTest() { ICompilationUnit cu = new ReflectionProjectContent("TestName", "testlocation", new AssemblyName[0], ParserService.DefaultProjectContentRegistry).AssemblyCompilationUnit; IClass c = new ReflectionClass(cu, typeof(TestClass <,>), typeof(TestClass <,>).FullName, null); cu.ProjectContent.AddClassToNamespaceList(c); CheckClass(c); MemoryStream memory = new MemoryStream(); DomPersistence.WriteProjectContent((ReflectionProjectContent)cu.ProjectContent, memory); memory.Position = 0; foreach (IClass c2 in DomPersistence.LoadProjectContent(memory, ParserService.DefaultProjectContentRegistry).Classes) { CheckClass(c2); } }
public static List <SqlDataRecord> ToSqlVariableTvp(this object obj) { var dataTable = new List <SqlDataRecord>(); var clazz = ReflectionClass.Reflection(obj.GetType()); foreach (var prop in clazz.Properties) { var dr = new SqlDataRecord( new SqlMetaData("Name", SqlDbType.VarChar, 255), new SqlMetaData("DataType", SqlDbType.VarChar, 255), new SqlMetaData("DataValue", SqlDbType.Variant) ); dr.SetString(0, "@" + prop.Key); dr.SetString(1, GetSqlDbType((PropertyInfo)prop.Value.Info)); dr.SetValue(2, prop.Value.Getter(obj)); dataTable.Add(dr); } return(dataTable); }
private static IEnumerable <ColumnInfo> GetTableColumnsInfo(Type entityType) { var entityClass = ReflectionClass.Reflection(entityType); foreach (var prop in entityClass.Properties) { var propName = prop.Key; var propType = prop.Value.PropertyType; var keyAttribute = prop.Value.Info.GetCustomAttribute <KeyAttribute>(); var isKey = keyAttribute != null; var dataType = GetDataType(propType); yield return(new ColumnInfo { Name = propName, DataType = dataType, IsKey = isKey }); } }
public IEnumerable <StockExchangeData> GetStockList(string stockId) { if (Data == null) { yield break; } var stockTranObjInfo = ReflectionClass.Reflection(typeof(StockExchangeData)); foreach (var dataItem in Data) { var stockTran = new StockExchangeData(); stockTran.StockId = stockId; foreach (var item in Fields.Select((value, idx) => new { name = FieldNames[value], idx })) { var valueStr = dataItem[item.idx]; var propInfo = stockTranObjInfo.Properties[item.name]; var value = (object)valueStr; if (propInfo.PropertyType != typeof(string)) { if (propInfo.PropertyType.IsValueType) { valueStr = valueStr.Replace(",", ""); valueStr = valueStr.Replace("X", ""); } value = valueStr.ChangeType(propInfo.PropertyType); if (propInfo.Name == nameof(StockExchangeData.Date)) { var date = (DateTime)value; date = date.AddYears(1911); value = date; } } propInfo.Setter(stockTran, value); } yield return(stockTran); } }
internal ReflectionProperty(PropertyInfo property, ReflectionClass parent) { this.property = property; this.parent = parent; this.attributes = new ReflectionAttributeList(this.property.GetCustomAttributes(true).OfType<Attribute>().ToList()); this.name = this.property.Name; this.propertyType = this.property.PropertyType; var method = this.property.GetGetMethod() ?? this.property.GetGetMethod(true); if (method != null) { this.getMethod = new ReflectionMethod(method, parent); } method = this.property.GetSetMethod() ?? this.property.GetSetMethod(true); if (method != null) { this.setMethod = new ReflectionMethod(method, parent); } }
void AddTypes(TypeDefinitionCollection types) { foreach (TypeDefinition td in types) { if ((td.Attributes & TypeAttributes.Public) == TypeAttributes.Public) { if ((td.Attributes & TypeAttributes.NestedAssembly) == TypeAttributes.NestedAssembly || (td.Attributes & TypeAttributes.NestedPrivate) == TypeAttributes.NestedPrivate || (td.Attributes & TypeAttributes.NestedFamANDAssem) == TypeAttributes.NestedFamANDAssem) { continue; } string name = td.FullName; if (name.Length == 0 || name[0] == '<') { continue; } name = ReflectionClass.SplitTypeParameterCountFromReflectionName(name); AddClassToNamespaceListInternal(new CecilClass(this.AssemblyCompilationUnit, null, td, name)); } } }
public static void GetDisplayValue(this object obj, Action <string, string> propValueString) { var clazz = ReflectionClass.Reflection(obj.GetType()); var first = true; foreach (var prop in clazz.Properties.Values) { var propInfo = (PropertyInfo)prop.Info; var decimalAttr = propInfo.GetCustomAttribute <DecimalStringAttribute>(false); if (decimalAttr != null) { var value = (decimal)prop.Getter(obj); if (!first) { propValueString(string.Empty, " "); } var numberString = value.ToNumberString(decimalAttr.MaxLength); propValueString(prop.Name, numberString); first = false; continue; } var displayAttr = propInfo.GetCustomAttribute <DisplayStringAttribute>(false); if (displayAttr != null) { if (!first) { propValueString(string.Empty, " "); } var value = prop.Getter(obj); var str = displayAttr.ToDisplayString(value); propValueString(prop.Name, str); first = false; continue; } } }
private ReflectObjectToTableClass AddRecords(ReflectObjectToTableClass reflectionClass, SQLDB sqlDb) { Params parameters = new Params(); ReflectObjectToTableClass myAddedParameters = new ReflectObjectToTableClass(); //SQLDB sqlDB = new SQLDB(connectionString); string lastCashName = ""; int paramId = -1; // sqlDB.OpenConnection(); //sqlDB.OpenTransaction(); // Console.WriteLine("Adding Parameters...."); foreach (int n in reflectionClass.getAllItemsLevels()) { foreach (ReflectionClass item in reflectionClass.GetItemsByLevel(n)) { /*Новая версия с развитым кешем*/ paramId = GetParamIdFromCashe(item.name, -1, true); if (paramId == -1) { paramId = parameters.AddParam(item.name, item.GetParentParamName(), 0, sqlDb); if (paramId == -1) { throw new Exception("Error adding parameters!"); } GetParamIdFromCashe(item.name, paramId, false); } /*Новая версия с развитым кешем*/ ReflectionClass r = new ReflectionClass(); r.name = item.name; r.PARAM_ID = paramId; //старая версия с одним кешем r.value = item.value; myAddedParameters.reflectedItemsList.Add(r); } } return(myAddedParameters); }
/// <summary> /// Создает список параметров для разобранного файла, либо бедет айди, если параметр есть /// либо создает новый /// </summary> /// <param name="reflectionClass">Разобранный обьект</param> /// <returns>список параметров для разобранного файла с ID</returns> private ReflectObjectToTableClass AddRecords(ReflectObjectToTableClass reflectionClass) { Params parameters = new Params(); ReflectObjectToTableClass myAddedParameters = new ReflectObjectToTableClass(); //SQLDB sqlDB = new SQLDB(connectionString); string lastCashName = ""; int paramId = -1; // sqlDB.OpenConnection(); //sqlDB.OpenTransaction(); Console.WriteLine("Adding Parameters...."); foreach (int n in reflectionClass.getAllItemsLevels()) { foreach (ReflectionClass item in reflectionClass.GetItemsByLevel(n)) { /*Новая версия с развитым кешем*/ paramId = GetParamIdFromCashe(item.name, -1, true); if (paramId == -1) { paramId = parameters.AddParam(item.name, item.GetParentParamName(), 0, sqlDb); if (paramId == -1) { throw new Exception("Error adding parameters!"); } GetParamIdFromCashe(item.name, paramId, false); } /*Новая версия с развитым кешем*/ ReflectionClass r = new ReflectionClass(); r.name = item.name; r.PARAM_ID = paramId; //старая версия с одним кешем r.value = item.value; myAddedParameters.reflectedItemsList.Add(r); } } return myAddedParameters; }
void InitMembers(TypeDefinition type) { string defaultMemberName = null; foreach (CustomAttribute att in type.CustomAttributes) { if (att.Constructor.DeclaringType.FullName == "System.Reflection.DefaultMemberAttribute" && att.ConstructorArguments.Count == 1) { defaultMemberName = att.ConstructorArguments[0].Value as string; } } foreach (TypeDefinition nestedType in type.NestedTypes) { TypeAttributes visibility = nestedType.Attributes & TypeAttributes.VisibilityMask; if (visibility == TypeAttributes.NestedPublic || visibility == TypeAttributes.NestedFamily || visibility == TypeAttributes.NestedFamORAssem) { string name = nestedType.Name; int pos = name.LastIndexOf('/'); if (pos > 0) { name = name.Substring(pos + 1); } if (name.Length == 0 || name[0] == '<') { continue; } name = ReflectionClass.SplitTypeParameterCountFromReflectionName(name); name = this.FullyQualifiedName + "." + name; InnerClasses.Add(new CecilClass(this.CompilationUnit, this, nestedType, name)); } } foreach (FieldDefinition field in type.Fields) { if (IsVisible(field.Attributes) && !field.IsSpecialName) { DefaultField f = new DefaultField(this, field.Name); f.Modifiers = TranslateModifiers(field); f.ReturnType = CreateType(this.ProjectContent, this, field.FieldType, field); AddAttributes(CompilationUnit.ProjectContent, f, f.Attributes, field); Fields.Add(f); } } foreach (PropertyDefinition property in type.Properties) { AddProperty(defaultMemberName, property); } foreach (EventDefinition eventDef in type.Events) { if (eventDef.AddMethod != null && IsVisible(eventDef.AddMethod.Attributes)) { DefaultEvent e = new DefaultEvent(this, eventDef.Name); if (this.ClassType == ClassType.Interface) { e.Modifiers = ModifierEnum.Public | ModifierEnum.Abstract; } else { e.Modifiers = TranslateModifiers(eventDef); } e.ReturnType = CreateType(this.ProjectContent, this, eventDef.EventType, eventDef); AddAttributes(CompilationUnit.ProjectContent, e, e.Attributes, eventDef); Events.Add(e); } } this.AddDefaultConstructorIfRequired = (this.ClassType == ClassType.Struct || this.ClassType == ClassType.Enum); foreach (MethodDefinition method in type.Methods) { if (method.IsConstructor || !method.IsSpecialName) { AddMethod(method); } } }
public CecilClass(ICompilationUnit compilationUnit, IClass declaringType, TypeDefinition td, string fullName) : base(compilationUnit, declaringType) { this.FullyQualifiedName = fullName; AddAttributes(compilationUnit.ProjectContent, this, this.Attributes, td); // set classtype if (td.IsInterface) { this.ClassType = ClassType.Interface; } else if (td.IsEnum) { this.ClassType = ClassType.Enum; } else if (td.IsValueType) { this.ClassType = ClassType.Struct; } else if (IsDelegate(td)) { this.ClassType = ClassType.Delegate; } else { this.ClassType = ClassType.Class; } if (td.GenericParameters.Count > 0) { foreach (GenericParameter g in td.GenericParameters) { this.TypeParameters.Add(new DefaultTypeParameter(this, g.Name, g.Position)); } int i = 0; foreach (GenericParameter g in td.GenericParameters) { AddConstraintsFromType(this.TypeParameters[i++], g); } } ModifierEnum modifiers = ModifierEnum.None; if (td.IsSealed) { modifiers |= ModifierEnum.Sealed; } if (td.IsAbstract) { modifiers |= ModifierEnum.Abstract; } if (td.IsSealed && td.IsAbstract) { modifiers |= ModifierEnum.Static; } if ((td.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic) { modifiers |= ModifierEnum.Public; } else if ((td.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamily) { modifiers |= ModifierEnum.Protected; } else if ((td.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamORAssem) { modifiers |= ModifierEnum.Protected; } else { modifiers |= ModifierEnum.Public; } this.Modifiers = modifiers; // set base classes if (td.BaseType != null) { BaseTypes.Add(CreateType(this.ProjectContent, this, td.BaseType)); } foreach (TypeReference iface in td.LegacyInterfaces) { BaseTypes.Add(CreateType(this.ProjectContent, this, iface)); } ReflectionClass.ApplySpecialsFromAttributes(this); InitMembers(td); }
static IReturnType CreateType(IProjectContent pc, IEntity member, TypeReference type, ICustomAttributeProvider attributeProvider, ref int typeIndex) { while (type is OptionalModifierType || type is RequiredModifierType) { type = ((TypeSpecification)type).ElementType; } if (type == null) { LoggingService.Warn("CecilReader: Null type for: " + member); return(new VoidReturnType(pc)); } if (type is ByReferenceType) { // TODO: Use ByRefRefReturnType return(CreateType(pc, member, (type as ByReferenceType).ElementType, attributeProvider, ref typeIndex)); } else if (type is PointerType) { typeIndex++; return(new PointerReturnType(CreateType(pc, member, (type as PointerType).ElementType, attributeProvider, ref typeIndex))); } else if (type is ArrayType) { typeIndex++; return(new ArrayReturnType(pc, CreateType(pc, member, (type as ArrayType).ElementType, attributeProvider, ref typeIndex), (type as ArrayType).Rank)); } else if (type is GenericInstanceType) { GenericInstanceType gType = (GenericInstanceType)type; IReturnType baseType = CreateType(pc, member, gType.ElementType, attributeProvider, ref typeIndex); IReturnType[] para = new IReturnType[gType.GenericArguments.Count]; for (int i = 0; i < para.Length; ++i) { typeIndex++; para[i] = CreateType(pc, member, gType.GenericArguments[i], attributeProvider, ref typeIndex); } return(new ConstructedReturnType(baseType, para)); } else if (type is GenericParameter) { GenericParameter typeGP = type as GenericParameter; if (typeGP.Owner is MethodDefinition) { IMethod method = member as IMethod; if (method != null) { if (typeGP.Position < method.TypeParameters.Count) { return(new GenericReturnType(method.TypeParameters[typeGP.Position])); } } return(new GenericReturnType(new DefaultTypeParameter(method, typeGP.Name, typeGP.Position))); } else { IClass c = (member is IClass) ? (IClass)member : (member is IMember) ? ((IMember)member).DeclaringType : null; if (c != null && typeGP.Position < c.TypeParameters.Count) { if (c.TypeParameters[typeGP.Position].Name == type.Name) { return(new GenericReturnType(c.TypeParameters[typeGP.Position])); } } return(new GenericReturnType(new DefaultTypeParameter(c, typeGP.Name, typeGP.Position))); } } else { string name = type.FullName; if (name == null) { throw new ApplicationException("type.FullName returned null. Type: " + type.ToString()); } int typeParameterCount; if (name.IndexOf('/') > 0) { typeParameterCount = 0; StringBuilder newName = new StringBuilder(); foreach (string namepart in name.Split('/')) { if (newName.Length > 0) { newName.Append('.'); } int partTypeParameterCount; newName.Append(ReflectionClass.SplitTypeParameterCountFromReflectionName(namepart, out partTypeParameterCount)); typeParameterCount += partTypeParameterCount; } name = newName.ToString(); } else { name = ReflectionClass.SplitTypeParameterCountFromReflectionName(name, out typeParameterCount); } if (typeParameterCount == 0 && name == "System.Object" && HasDynamicAttribute(attributeProvider, typeIndex)) { return(new DynamicReturnType(pc)); } IClass c = pc.GetClass(name, typeParameterCount); if (c != null) { return(c.DefaultReturnType); } else { // example where name is not found: pointers like System.Char* // or when the class is in a assembly that is not referenced return(new GetClassReturnType(pc, name, typeParameterCount)); } } }
/// <summary> /// Adds assembly attributes from the specified assembly. /// /// The constructor already does this, this method is meant for unit tests only! /// </summary> public void AddAssemblyAttributes(Assembly assembly) { ReflectionClass.AddAttributes(this, assemblyCompilationUnit.Attributes, CustomAttributeData.GetCustomAttributes(assembly)); }
private List<ReflectionClass> ParseRecord(List<ReflectionClass> reflectionClass) { List<ReflectionClass> returnReflectionClass = new List<ReflectionClass>(); string[] splitedString; List<Arrays> arrayNames = new List<Arrays>(); Arrays oneList; foreach (ReflectionClass r in reflectionClass) { splitedString = r.name.Split(new char[] { '.' }); for (int i = 0; i < splitedString.Length; i++) { if (splitedString[i].Contains('[') && splitedString[i].Contains(']')) { string arrayFullName = ""; oneList = new Arrays(); string[] splitNameNumber = splitedString[i].Split((new char[] { '[', ']' }), StringSplitOptions.RemoveEmptyEntries); for (int j = 0; j < r.paramStructure.Count; j++) { arrayFullName += r.paramStructure[j] + "."; } arrayFullName += splitNameNumber[0]; oneList.arrayName = arrayFullName; oneList.maxCount = Convert.ToInt32(splitNameNumber[1]); int result = arrayNames.FindIndex( delegate(Arrays arrayName) { if (arrayName.arrayName.Equals(arrayFullName)) return true; return false; } ); if (result != -1) { if (arrayNames[result].maxCount < oneList.maxCount) { Arrays temp = new Arrays(); temp.arrayName = oneList.arrayName; temp.maxCount = oneList.maxCount; arrayNames[result] = temp; } } else { arrayNames.Add(oneList); } } r.paramStructure.Add(splitedString[i]); } returnReflectionClass.Add(r); } foreach (Arrays n in arrayNames) { ReflectionClass r = new ReflectionClass(); r.name = n.arrayName + ".arrayCount"; r.value = (n.maxCount + 1).ToString(); returnReflectionClass.Add(r); } return returnReflectionClass; }
private void PerfectwORK(String name, Object obj, int parentParamId) { string s = ""; byte[] b = new byte[0]; if (obj == null) { /*ReflectionClass rf = new ReflectionClass(name, "NOTHING"); rf.PARAM_ID = ++currentId; rf.PARENT_PARAM_ID = parentParamId; reflectedItemsList.Add(rf);*/ } else { Type type = obj.GetType(); if (type.IsPrimitive || type.IsInstanceOfType(s)) { ReflectionClass rf = new ReflectionClass(name, obj.ToString()); rf.PARAM_ID = ++currentId; rf.PARENT_PARAM_ID = parentParamId; reflectedItemsList.Add(rf); } else if (type.IsInstanceOfType(b))//byte[] { ReflectionClass rf = new ReflectionClass(name, convertIntoString((byte[])obj).Trim()); rf.PARAM_ID = ++currentId; rf.PARENT_PARAM_ID = parentParamId; reflectedItemsList.Add(rf); } else if (type.IsArray)//array[] { IList list = (IList)obj; ReflectionClass parentItem = new ReflectionClass(name, "It's parent array"); parentItem.PARAM_ID = ++currentId; parentItem.PARENT_PARAM_ID = parentParamId; // reflectedItemsList.Add(parentItem); for (int idx = 0; idx < list.Count; idx++) { Object objectTemp = list[idx]; if (objectTemp != null) PerfectwORK(name, objectTemp, parentItem.PARAM_ID); } } else if (type.IsGenericType) { IList list = (IList)obj; ReflectionClass parentItem = new ReflectionClass(name, "It's parent array"); parentItem.PARAM_ID = ++currentId; parentItem.PARENT_PARAM_ID = parentParamId; // reflectedItemsList.Add(parentItem); for (int idx = 0; idx < list.Count; idx++) { Object objectTemp = list[idx]; if (objectTemp != null) PerfectwORK(name, objectTemp, parentItem.PARAM_ID); } } else if (type.IsClass) { PropertyInfo[] propertyInfo = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); if (propertyInfo.Length == 1) { object field2 = propertyInfo[0].GetValue(obj, null); PerfectwORK(name, field2, parentParamId); } else { ReflectionClass parentItem = new ReflectionClass(name, "It's parent"); parentItem.PARAM_ID = ++currentId; parentItem.PARENT_PARAM_ID = parentParamId; reflectedItemsList.Add(parentItem); foreach (PropertyInfo pi in propertyInfo) { string fieldName = name + "." + pi.Name; object field2 = pi.GetValue(obj, null); PerfectwORK(fieldName, field2, parentItem.PARAM_ID); } } } } }