private void GenerateType(ModuleBuilder module, TypeMetadata typeMetadata) { if(typeMetadata == null) throw new ArgumentNullException("typeMetadata"); if(typeMetadata is ClassMetadata) { this.GenerateClass(module, typeMetadata as ClassMetadata); } else { throw new InvalidOperationException("unknown method"); } }
public static TypeMetadata GetDocs(this Type type, XPathNavigator docs) { var node = docs.SelectSingleNode(type.XPathQuery()); var rtn = new TypeMetadata { Name = Utils.GetCleanTypeName(type), Summary = Utils.GetNodeValue(node, "summary"), Remarks = Utils.GetNodeValue(node, "remarks"), Properties = GetPropertyDocs(type, docs) }; return rtn; }
public MemberMetadata(string memberName, TypeMetadata memberType) { MemberName = memberName; MemberType = memberType; }
/* * Go through all reference assemblies of .NET Core and generate the type catalog -> Dictionary<NamespaceQualifiedTypeName, TPAStrongName> * Then auto-generate the partial class 'PowerShellAssemblyLoadContext' that has the code to initialize the type catalog cache. * * In CoreCLR, there is no way to get all loaded TPA assemblies (.NET Framework Assemblies). In order to get type based on type name, powershell needs to know what .NET * types are available and in which TPA assemblies. So we have to generate the type catalog based on the reference assemblies of .NET Core. */ public static void Main(string[] args) { if (args.Length < 2 || args.Length > 3) { string message = string.Format(CultureInfo.CurrentCulture, HelpMessage, Param_TargetCSharpFilePath, Param_ReferenceListPath, Param_PrintDebugMessage); Console.WriteLine(message); return; } bool printDebugMessage = args.Length == 3 && string.Equals(Param_PrintDebugMessage, args[2], StringComparison.OrdinalIgnoreCase); string targetFilePath = ResolveTargetFilePath(args[0]); List <string> refAssemblyFiles = ResolveReferenceAssemblies(args[1]); Dictionary <string, TypeMetadata> typeNameToAssemblyMap = new Dictionary <string, TypeMetadata>(StringComparer.OrdinalIgnoreCase); // mscorlib.metadata_dll doesn't contain any type definition. foreach (string filePath in refAssemblyFiles) { if (!filePath.EndsWith(".METADATA_DLL", StringComparison.OrdinalIgnoreCase) && !filePath.EndsWith(".DLL", StringComparison.OrdinalIgnoreCase)) { string message = string.Format(CultureInfo.CurrentCulture, UnexpectedFileExtension, filePath); throw new InvalidOperationException(message); } using (Stream stream = File.OpenRead(filePath)) using (PEReader peReader = new PEReader(stream)) { MetadataReader metadataReader = peReader.GetMetadataReader(); string strongAssemblyName = GetAssemblyStrongName(metadataReader); foreach (TypeDefinitionHandle typeHandle in metadataReader.TypeDefinitions) { // We only care about public types TypeDefinition typeDefinition = metadataReader.GetTypeDefinition(typeHandle); // The visibility mask is used to mask out the bits that contain the visibility. // The visibilities are not combineable, e.g. you can't be both public and private, which is why these aren't independent powers of two. TypeAttributes visibilityBits = typeDefinition.Attributes & TypeAttributes.VisibilityMask; if (visibilityBits != TypeAttributes.Public && visibilityBits != TypeAttributes.NestedPublic) { continue; } string fullName = GetTypeFullName(metadataReader, typeDefinition); bool isTypeObsolete = IsTypeObsolete(metadataReader, typeDefinition); if (!typeNameToAssemblyMap.ContainsKey(fullName)) { // Add unique type. typeNameToAssemblyMap.Add(fullName, new TypeMetadata(strongAssemblyName, isTypeObsolete)); } else if (typeNameToAssemblyMap[fullName].IsObsolete && !isTypeObsolete) { // Duplicate types found defined in different assemblies, but the previous one is obsolete while the current one is not. // Replace the existing type with the current one. if (printDebugMessage) { var existingTypeMetadata = typeNameToAssemblyMap[fullName]; Console.WriteLine($@" REPLACE '{fullName}' from '{existingTypeMetadata.AssemblyName}' (IsObsolete? {existingTypeMetadata.IsObsolete}) WITH '{strongAssemblyName}' (IsObsolete? {isTypeObsolete})"); } typeNameToAssemblyMap[fullName] = new TypeMetadata(strongAssemblyName, isTypeObsolete); } else if (printDebugMessage) { // Duplicate types found defined in different assemblies, and fall into one of the following conditions: // - both are obsolete // - both are not obsolete // - the existing type is not obsolete while the new one is obsolete var existingTypeMetadata = typeNameToAssemblyMap[fullName]; Console.WriteLine($@" DUPLICATE key '{fullName}' from '{strongAssemblyName}' (IsObsolete? {isTypeObsolete}). -- Already exist in '{existingTypeMetadata.AssemblyName}' (IsObsolete? {existingTypeMetadata.IsObsolete})"); } } } } WritePowerShellAssemblyLoadContextPartialClass(targetFilePath, typeNameToAssemblyMap); }
protected GenericParameterMetadata(TypeMetadata type, string name, GenericParameterAttributes attributes) { Name = name; Attributes = attributes; Type = type; }
public TreeViewType(TypeMetadata type) : base(GetFullName(type)) { this.Type = type; }
private static void AddReflectionParameterInfo(InstalledCmdletInfo cmdlet, Dictionary<string, MAMLReader.ParameterHelpInfo> parameters) { var typeMetadata = new TypeMetadata(cmdlet.Type); typeMetadata.Load(); foreach (var p in parameters) { ParameterMetadata metadata; if (typeMetadata.Parameters.TryGetValue(p.Key.ToLowerInvariant(), out metadata)) { p.Value.Aliases = metadata.Aliases.ToArray(); } } }
private object DeserializeSimpleObject( object obj, long id, out bool hasFixup ) { hasFixup = false; Type currentType = obj.GetType(); TypeMetadata tm = GetTypeMetadata(currentType); object[] data = new object[tm.MemberInfos.Length]; xmlReader.Read(); xmlReader.MoveToContent(); while (xmlReader.NodeType != XmlNodeType.EndElement) { if (xmlReader.NodeType != XmlNodeType.Element) { xmlReader.Skip(); continue; } object fieldObject; long fieldId, fieldHref; object indexob = tm.Indices [xmlReader.LocalName]; if (indexob == null) { throw new SerializationException("Field \"" + xmlReader.LocalName + "\" not found in class " + currentType.FullName); } int index = (int)indexob; FieldInfo fieldInfo = (tm.MemberInfos[index]) as FieldInfo; fieldObject = DeserializeComponent(fieldInfo.FieldType, out fieldId, out fieldHref, id, fieldInfo, null); data[index] = fieldObject; if (fieldHref != 0 && fieldObject == null) { RecordFixup(id, fieldHref, obj, null, null, fieldInfo, null); hasFixup = true; continue; } if (fieldObject != null && fieldObject.GetType().IsValueType&& fieldId != 0) { RecordFixup(id, fieldId, obj, null, null, fieldInfo, null); hasFixup = true; continue; } if (fieldId != 0) { RegisterObject(fieldId, fieldObject, null, id, fieldInfo, null); } } FormatterServices.PopulateObjectMembers(obj, tm.MemberInfos, data); return(obj); }
/// <summary> /// 创建对象输出信息对象。 /// </summary> /// <param name="metadata">类型元数据。</param> /// <param name="fields">字段索引集合。</param> public ObjectOutputInfo(TypeMetadata metadata, int[] fields) : base(metadata, fields) { }
public void DerivedClassTest() { TypeMetadata derivedClass = ReflectorTestClass.Reflector.MyNamespace.Types.Single(x => x.TypeName == "DerivedClass"); Assert.IsNotNull(derivedClass.BaseType); }
public TypeMetadataView(ILogger log, TypeMetadata typeMetadata) : base(log) { _typeMetaData = typeMetadata; }
/// <summary> /// Determine what kind of version bump should be applied to the common /// code library. We want to ensure that there were no breaking changes /// made to the common code to preserve backwards-compatibility. /// </summary> /// <returns>Version bump that should be applied to the common code library.</returns> public Version GetVersionBumpForCommonCode() { var outputModuleDirectory = _fileHelper.OutputModuleDirectory; var galleryModuleDirectory = _fileHelper.GalleryModuleDirectory; Console.WriteLine("Saving Az.Accounts from the PowerShell Gallery to check common code changes. This will take a few seconds."); Version versionBump = Version.PATCH; var issueLogger = _logger.CreateLogger <BreakingChangeIssue>("BreakingChangeIssues.csv"); IEnumerable <string> commonAssemblies = null; using (PowerShell powershell = PowerShell.Create()) { powershell.AddScript("Save-Module -Name Az.Accounts -Repository PSGallery -Path " + outputModuleDirectory); var cmdletResult = powershell.Invoke(); } var galleryModuleVersionDirectory = _fileHelper.GalleryModuleVersionDirectory; using (PowerShell powershell = PowerShell.Create()) { powershell.AddScript("$metadata = Test-ModuleManifest -Path " + Path.Combine(galleryModuleVersionDirectory, "Az.Accounts.psd1") + ";$metadata.RequiredAssemblies"); var cmdletResult = powershell.Invoke(); commonAssemblies = cmdletResult.Select(c => c.ToString().Substring(2)).Where(s => Regex.IsMatch(s, "Microsoft.*.Commands.*")); } try { foreach (var commonAssembly in commonAssemblies) { var fullAssemblyPath = Path.Combine(outputModuleDirectory, commonAssembly); var assemblyName = Path.GetFileName(commonAssembly); var oldAssemblyPath = Directory.GetFiles(galleryModuleDirectory, assemblyName, SearchOption.AllDirectories).FirstOrDefault(); if (oldAssemblyPath == null) { throw new Exception("Could not find assembly " + assemblyName + " in the folder saved from the PowerShell Gallery for Az.Accounts."); } var oldAssembly = Assembly.LoadFrom(oldAssemblyPath); CmdletLoader.ModuleMetadata = new ModuleMetadata(); var oldTypeMetadataDictionary = CmdletLoader.ModuleMetadata.TypeDictionary; foreach (var oldType in oldAssembly.GetTypes()) { if (oldType.Namespace == null) { // Sealed / private type continue; } if (oldType.FullName != null && oldType.FullName.Contains("+")) { oldTypeMetadataDictionary[oldType.ToString()] = new TypeMetadata() { Name = oldType.ToString() }; } if (!oldTypeMetadataDictionary.ContainsKey(oldType.ToString())) { var oldTypeMetadata = new TypeMetadata(oldType); oldTypeMetadataDictionary[oldType.ToString()] = oldTypeMetadata; } } var newAssembly = Assembly.LoadFrom(fullAssemblyPath); CmdletLoader.ModuleMetadata = new ModuleMetadata(); var newTypeMetadataDictionary = CmdletLoader.ModuleMetadata.TypeDictionary; foreach (var newType in newAssembly.GetTypes()) { if (newType.Namespace == null) { // Sealed / private type continue; } if (newType.FullName != null && newType.FullName.Contains("+")) { newTypeMetadataDictionary[newType.ToString()] = new TypeMetadata() { Name = newType.ToString() }; } if (!newTypeMetadataDictionary.ContainsKey(newType.ToString())) { var newTypeMetadata = new TypeMetadata(newType); newTypeMetadataDictionary[newType.ToString()] = newTypeMetadata; } } issueLogger.Decorator.AddDecorator(a => a.AssemblyFileName = Path.GetFileName(commonAssembly), "AssemblyFileName"); CheckBreakingChangesInTypes(oldTypeMetadataDictionary, newTypeMetadataDictionary, issueLogger); if (issueLogger.Records.Any()) { return(Version.MAJOR); } else { foreach (var type in oldTypeMetadataDictionary.Keys) { if (!newTypeMetadataDictionary.ContainsKey(type)) { continue; } var oldTypeMetadata = oldTypeMetadataDictionary[type]; var newTypeMetadata = newTypeMetadataDictionary[type]; if (!oldTypeMetadata.Equals(newTypeMetadata)) { versionBump = Version.MINOR; } } if (oldTypeMetadataDictionary.Keys.Count != newTypeMetadataDictionary.Keys.Count) { versionBump = Version.MINOR; } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { var directories = Directory.GetDirectories(outputModuleDirectory, "Az.Accounts", SearchOption.TopDirectoryOnly); foreach (var directory in directories) { try { Directory.Delete(directory, true); } catch (Exception ex) { var blank = ex.Message; } } } Console.WriteLine("Found " + versionBump + " version bump for common code changes."); return(versionBump); }
public void StructureTest() { TypeMetadata typeMetadata = new TypeMetadata(typeof(TestClass.StructureTest)); Assert.IsTrue(typeMetadata.TypeEnum == TypeTypesEnumMetadata.Structure); }
public void PrimitiveTest() { TypeMetadata typeMetadata = new TypeMetadata(typeof(long)); Assert.IsTrue(typeMetadata.TypeEnum == TypeTypesEnumMetadata.Primitive); }
public void EnumTest() { TypeMetadata typeMetadata = new TypeMetadata(typeof(TestClass.TestEnum)); Assert.IsTrue(typeMetadata.TypeEnum == TypeTypesEnumMetadata.Enum); }
public void InterfaceTest() { TypeMetadata typeMetadata = new TypeMetadata(typeof(ITestInterface)); Assert.IsTrue(typeMetadata.TypeEnum == TypeTypesEnumMetadata.Interface); }
public void DelegateTest() { TypeMetadata typeMetadata = new TypeMetadata(typeof(TestClass.TestDelegate)); Assert.IsTrue(typeMetadata.TypeEnum == TypeTypesEnumMetadata.Delegate); }
/// <summary> /// 创建对象输出信息对象。 /// </summary> /// <param name="reader">数据读取器。</param> /// <param name="metadata">类型元数据。</param> public ObjectOutputInfo(DbDataReader reader, TypeMetadata metadata) : base(reader, metadata) { }
/// <summary> /// 该构造由框架内部调用 /// </summary> /// <param name="typeName"></param> /// <param name="metadataCode"></param> /// <param name="qualifiedName"></param> internal AggregateRootDefine(string typeName, TypeMetadata metadata, string qualifiedName) : base(typeName, metadata, DomainObject.AggregateRootType, typeof(DynamicRoot), qualifiedName) { }
public void StaticClassTest() { TypeMetadata staticClass = ReflectorTestClass.Reflector.MyNamespace.Types.Single(x => x.TypeName == "StaticClass"); Assert.AreEqual(StaticEnum.Static.ToString(), staticClass.Methods.Single(x => x.Name == "StaticMethod1").Modifiers.Item3.ToString()); }
/// <summary> /// 创建集合输出信息对象。 /// </summary> /// <param name="reader">数据读取器。</param> /// <param name="metadata">类型元数据。</param> public CollectionOutputInfo(DbDataReader reader, TypeMetadata metadata) : base(reader, metadata) { }
private static void AddReflectionCmdletInfo(InstalledCmdletInfo cmdlet) { if (cmdlet.Info == null) { var typeMetadata = new TypeMetadata(cmdlet.Type); typeMetadata.Load(); cmdlet.Info = new MAMLReader.CommandHelpInfo { Name = cmdlet.CommandName, Keys = cmdlet.Keys }; if (typeMetadata.ParameterSets != null && typeMetadata.ParameterSets.Count > 0) { foreach (var pSet in typeMetadata.ParameterSets) { var psetInfo = new MAMLReader.ParameterSetHelpInfo(); cmdlet.Info.ParameterSets.Add(psetInfo); psetInfo.Parameters.AddRange(pSet.Parameters .Select(p => new MAMLReader.ParameterHelpInfo { Name = p.Name, Aliases = p.Aliases != null ? p.Aliases.ToArray() : null, IsMandatory = p.IsMandatory, Position = p.Position, Type = p.ParameterType.Name })); } } else { var psetInfo = new MAMLReader.ParameterSetHelpInfo(); cmdlet.Info.ParameterSets.Add(psetInfo); psetInfo.Parameters.AddRange(typeMetadata.Parameters.Values.Where(p => !p.IsBuiltin) .Select(p => new MAMLReader.ParameterHelpInfo { Name = p.Name, Aliases = p.Aliases != null ? p.Aliases.ToArray() : null, IsMandatory = p.IsMandatory(null), Position = p.Position(null), Type = p.ParameterType.Name })); } } }
/// <summary> /// 创建集合输出信息对象。 /// </summary> /// <param name="metadata">类型元数据。</param> /// <param name="fields">属性索引列表。</param> public CollectionOutputInfo(TypeMetadata metadata, int[] fields) : base(metadata, fields) { }
/// <summary> /// create the metadata for the type from a system.type /// </summary> /// <param name="type"></param> /// <returns></returns> public static TypeMetadata CreateTypeMetadata(Type type) { return(TypeMetadata.CreateTypeMetadata(GetSqlType(type))); }
public StructureViewModel(TypeMetadata type, string name) : base(type, name) { }
public ConcreteGenericParameterMetadata(TypeMetadata type, GenericParameterAttributes attributes) : base(type, type.Name, attributes) { }
public AzureTableDictionaryStorageClient() { typeMetadata = new TypeMetadata(typeof(T)); }
private MemberMetadata BuildMemberMetadata(PropertyInfo property, TypeCache cache) { TypeMetadata typeMetadata = BuildTypeMetadata(property.PropertyType.GetTypeInfo(), cache); return(new MemberMetadata(property.Name, typeMetadata)); }
/// <summary> /// 该构造由框架内部调用 /// </summary> /// <param name="typeName"></param> /// <param name="metadataCode"></param> /// <param name="qualifiedName"></param> internal EntityObjectDefine(string typeName, TypeMetadata metadata, string qualifiedName, bool closeMultiTenancy) : base(typeName, metadata, DomainObject.EntityObjectType, typeof(DynamicEntity), qualifiedName, closeMultiTenancy) { }
public static string GetFullName(TypeMetadata model) { return(model.GetFullName()); }
public ClassViewModel(TypeMetadata type, string name) : base(type, name) { }
private static ByRefTypeMetadata GetByRefMetadata(Type byRefType) { TypeMetadata underlyingType = FromType(byRefType.GetElementType()); return(new ByRefTypeMetadata(underlyingType)); }
/// <summary> /// Get the metadata for the properties of a type. /// </summary> /// <param name="type">the type to get the properties of.</param> /// <returns>a dictionary of properties on the type, keyed by name.</returns> private static (IImmutableList <IndexerMetadata>, IImmutableDictionary <string, PropertyMetadata>) GetPropertyMetadata(Type type) { var indexers = new List <IndexerMetadata>(); var properties = new Dictionary <string, PropertyMetadata>(); foreach (PropertyInfo property in type.GetProperties()) { if (property.Name == "Item") { MethodInfo idxGetter = property.GetGetMethod(); MethodInfo idxSetter = property.GetSetMethod(); var idxGetterMetadata = idxGetter == null ? null : new IndexerGetterMetadata( GetProtectionLevel(idxGetter.Attributes), idxGetter.IsStatic); var idxSetterMetadata = idxSetter == null ? null : new IndexerSetterMetadata( GetProtectionLevel(idxSetter.Attributes), idxSetter.IsStatic); var indexer = new IndexerMetadata(ProtectionLevel.Public, false) { CustomAttributes = GetCustomAttributes(property.CustomAttributes), Getter = idxGetterMetadata, Setter = idxSetterMetadata, Type = FromType(idxGetter?.ReturnType ?? idxSetter?.GetParameters()[1].ParameterType), IndexType = FromType(idxGetter?.GetParameters()[0].ParameterType ?? idxSetter?.GetParameters()[0].ParameterType) }; indexers.Add(indexer); } MethodInfo getter = property.GetGetMethod(); MethodInfo setter = property.GetSetMethod(); TypeMetadata propertyType = FromType(property.PropertyType); var getterMetadata = getter == null ? null : new PropertyGetterMetadata( property.Name, GetProtectionLevel(getter.Attributes), getter.IsStatic) { CustomAttributes = GetCustomAttributes(getter.GetCustomAttributesData()), ReturnType = propertyType }; var setterMetadata = setter == null ? null : new PropertySetterMetadata( property.Name, GetProtectionLevel(setter.Attributes), setter.IsStatic) { CustomAttributes = GetCustomAttributes(setter.GetCustomAttributesData()), ParameterTypes = new [] { propertyType }.ToImmutableArray() }; var propertyMetadata = new PropertyMetadata( property.Name, ProtectionLevel.Public, // TODO: Correct this later ReadPropertyIsStatic(getter, setter)) { CustomAttributes = GetCustomAttributes(property.GetCustomAttributesData()), Getter = getterMetadata, Setter = setterMetadata, Type = propertyType, GenericParameters = ImmutableArray <GenericParameterMetadata> .Empty }; properties.Add(property.Name, propertyMetadata); } return(indexers.ToImmutableArray(), properties.ToImmutableDictionary()); }
TypeMetadata GetTypeMetadata (Type type) { TypeMetadata tm = _fieldIndices[type] as TypeMetadata; if (tm != null) return tm; tm = new TypeMetadata (); tm.MemberInfos = FormatterServices.GetSerializableMembers (type, _context); tm.Indices = new Hashtable(); for(int i = 0; i < tm.MemberInfos.Length; i++) { SoapFieldAttribute at = (SoapFieldAttribute) InternalRemotingServices.GetCachedSoapAttribute (tm.MemberInfos[i]); tm.Indices [XmlConvert.EncodeLocalName (at.XmlElementName)] = i; } _fieldIndices[type] = tm; return tm; }
public Class(TypeMetadata metadata, IOutputTypeProvider provider) : base(metadata, provider) { }