Exemplo n.º 1
2
        public Type[] Execute(System.Reflection.Assembly assembly)
        {
            var targetNamespaces = new HashSet<string>();
            var resourceNames = assembly.GetManifestResourceNames().Where(n => n.EndsWith("VenusIoc.config"));
            foreach (var resourceName in resourceNames)
            {
                var xmlDoc = new XmlDocument();
                using (var sr = new StreamReader(assembly.GetManifestResourceStream(resourceName)))
                {
                    xmlDoc.Load(sr);
                    foreach (var node in xmlDoc.DocumentElement.SelectNodes("components/assemblyScan/namespace"))
                    {
                        var name = ((XmlElement)node).GetAttribute("name");
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            targetNamespaces.Add(name.Trim());
                        }
                    }
                }
            }

            var types = new List<Type>();
            foreach (var type in assembly.GetTypes())
            {
                if (targetNamespaces.Contains(type.Namespace) && !type.IsAbstract && type.IsDefined(typeof(NamedAttribute), false))
                {
                    types.Add(type);
                }
            }

            return types.ToArray();
        }
Exemplo n.º 2
0
        internal static void FindTasksAndConditionsInAssembly(System.Reflection.Assembly assembly,
			Dictionary<string, Type> updateTasks, Dictionary<string, Type> updateConditions)
        {
            foreach (Type t in assembly.GetTypes())
            {
                if (typeof(IUpdateTask).IsAssignableFrom(t))
                {
                    updateTasks.Add(t.Name, t);
                    UpdateTaskAliasAttribute[] tasksAliases = (UpdateTaskAliasAttribute[])t.GetCustomAttributes(typeof(UpdateTaskAliasAttribute), false);
                    foreach (UpdateTaskAliasAttribute alias in tasksAliases)
                    {
                        updateTasks.Add(alias.Alias, t);
                    }
                }
                else if (typeof(IUpdateCondition).IsAssignableFrom(t))
                {
                    updateConditions.Add(t.Name, t);
                    UpdateConditionAliasAttribute[] tasksAliases = (UpdateConditionAliasAttribute[])t.GetCustomAttributes(typeof(UpdateConditionAliasAttribute), false);
                    foreach (UpdateConditionAliasAttribute alias in tasksAliases)
                    {
                        updateConditions.Add(alias.Alias, t);
                    }
                }
            }
        }
Exemplo n.º 3
0
 public static IEnumerable<Type> GetTypesAssignableFrom(System.Reflection.Assembly assemb, System.Type rootType)
 {
     foreach (var tp in assemb.GetTypes())
     {
         if (rootType.IsAssignableFrom(tp) && rootType != tp) yield return tp;
     }
 }
Exemplo n.º 4
0
        public void AddAssembly( System.Reflection.Assembly assembly )
        {
            Details details = new Details();

            details.Assembly = assembly;

            foreach( Type type in assembly.GetTypes() )
            {
                List<Type> types;

                if( details.TypeMap.ContainsKey( type.Name ) )
                {
                    types = details.TypeMap[type.Name];
                }
                else
                {
                    types = new List<Type>();
                    details.TypeMap[type.Name] = types;
                }

                types.Add( type );
            }

            _details.Add( details );
        }
        public static PlayerAction[] GetAllPlayerActions(System.Reflection.Assembly assembly)
        {
            var result = new List<PlayerAction>();

            foreach (Type innerType in assembly.GetTypes())
            {
                if (!innerType.IsClass)
                    continue;

                if (innerType.Namespace != "Strategies")
                    continue;

                System.Reflection.MethodInfo playerMethodInfo = innerType.GetMethod("Player", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
                if (playerMethodInfo == null)
                    continue;

                if (playerMethodInfo.ContainsGenericParameters)
                    continue;

                if (playerMethodInfo.GetParameters().Length > 0)
                {
                    continue;
                }

                PlayerAction playerAction = playerMethodInfo.Invoke(null, new object[0]) as PlayerAction;
                if (playerAction == null)
                    continue;

                result.Add(playerAction);
            }

            return result.ToArray();
        }
Exemplo n.º 6
0
        public bool Start(
            System.Reflection.Assembly DatabaseAssembly, 
            Action<String> Output)
        {
            GameInfo gameInfo = null;
            foreach (var type in DatabaseAssembly.GetTypes())
                if (type.IsSubclassOf(typeof(GameInfo)))
                    gameInfo = Activator.CreateInstance(type) as GameInfo;

            if (gameInfo == null) throw new InvalidOperationException("No GameInfo defined in game assembly.");

            var assemblies = new List<ModuleAssembly>();
            assemblies.Add(new ModuleAssembly(DatabaseAssembly, new ModuleInfo { BaseNameSpace = gameInfo.DatabaseNameSpace }));
            foreach (var module in gameInfo.Modules)
                assemblies.Add(new ModuleAssembly(module));

            if (RMUD.Core.Start(StartupFlags.Silent,
                new RMUD.SinglePlayer.CompiledDatabase(DatabaseAssembly, gameInfo.DatabaseNameSpace),
                assemblies.ToArray()))
            {
                Player = RMUD.MudObject.GetObject<RMUD.Player>(RMUD.Core.SettingsObject.PlayerBaseObject);
                Player.CommandHandler = RMUD.Core.ParserCommandHandler;
                Client = new DummyClient(Output);
                RMUD.Core.TiePlayerToClient(Client, Player);
                Player.Rank = 500;

                DetectAndAssignDriver(DatabaseAssembly);
                Core.GlobalRules.ConsiderPerformRule("singleplayer game started", Player);

                return true;
            }

            return false;
        }
        public void buildTreeFromAssembly(System.Reflection.Assembly CurrentAsm)
        {
            //code from Platt's example
            TreeNode BaseNode;
            BaseNode = treeViewAssembly.Nodes.Add("Assy:" + CurrentAsm.GetName().ToString());
            BaseNode.Tag = CurrentAsm;

            // Enumerate each type contained in the assembly

            foreach (System.Type ThisType in CurrentAsm.GetTypes())
            {
                TreeNode MyNode;
                MyNode = BaseNode.Nodes.Add(ThisType.ToString() + " : " + ThisType.BaseType.ToString());
                MyNode.Tag = ThisType;

                // Enumerate all the members of this type
                // Add each member to the tree

                foreach (System.Reflection.MemberInfo Member in
                    ThisType.GetMembers(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static))
                {
                    TreeNode typenode = MyNode.Nodes.Add(Member.MemberType.ToString() + " : " + Member.Name);
                    typenode.Tag = Member;
                }
            }
        }
Exemplo n.º 8
0
        public AssemblyInfo(System.Reflection.Assembly assembly, bool structure)
        {
            Classes = new List<TypeInfo>();
            Interfaces = new List<InterfaceInfo>();
            Enumerations = new List<EnumInfo>();
            Exceptions = new List<ExceptionInfo>();
            Attributes = new List<AttributeInfo>();
            Structures = new List<StructureInfo>();
            try
            {
                foreach (Type type in assembly.GetTypes())
                    if (type.IsSubclassOf(typeof(System.Exception)))
                        Exceptions.Add(new ExceptionInfo(type));
                    else if (type.IsSubclassOf(typeof(System.Attribute)))
                        Attributes.Add(new AttributeInfo(type));
                    else if (type.IsClass)
                        Classes.Add(new TypeInfo(type));
                    else if (type.IsInterface)
                        Interfaces.Add(new InterfaceInfo(type));
                    else if (type.IsEnum)
                        Enumerations.Add(new EnumInfo(type));
            }
            catch (Exception ex)
            {

            }

            if (!structure)
                return;

            Structure = NamespaceInfo.CreateStructureByAssembly(this);
        }
Exemplo n.º 9
0
 internal void AddByAssembly(System.Reflection.Assembly assembly)
 {
     var commands = assembly.GetTypes().Where(t => typeof(ICommand) == t.BaseType);
     foreach (var type in commands)
     {
        // this.Add(type);
     }
 }
Exemplo n.º 10
0
 public static void Register(System.Reflection.Assembly assembly)
 {
     foreach (Type type in assembly.GetTypes())
     {
         if(!type.IsAbstract && !type.IsInterface && type.GetCustomAttributes(typeof(ProtoContractAttribute),false).Length>0)
             mTables[type.Name]=type;
     }
 }
 public ServerRepo(string prefix, System.Reflection.Assembly typesAsm)
 {
     _subscriptions = new Dictionary<string, Subscription>();
     _types = new List<Type>(typesAsm.GetTypes());
     _server = new Server (this, prefix);
     _handlersByClientId = new Dictionary<string, ClientHandler> ();
     _queryInfos = new Dictionary<string, Dictionary<SqlQuery, QueryInfo>> ();
 }
Exemplo n.º 12
0
 public static void Register(System.Reflection.Assembly assembly)
 {
     foreach (Type type in assembly.GetTypes())
     {
         if(!type.IsAbstract && !type.IsInterface)
             mTables[type.FullName]=type;
     }
 }
Exemplo n.º 13
0
 static void DiscoverHardware(System.Reflection.Assembly Assembly)
 {
     foreach (var type in Assembly.GetTypes())
     {
         var attr = type.GetCustomAttributes(false).FirstOrDefault(a => a is HardwareAttribute) as HardwareAttribute;
         if (attr != null && !HardwareTypes.ContainsKey(attr.ID))
                 HardwareTypes.Add(attr.ID, type);
     }
 }
Exemplo n.º 14
0
        public static void DiscoverClasses(System.Reflection.Assembly assembly)
        {
            var collection = GetMarkedTypes(assembly.GetTypes().AsParallel(), typeof(ContextClassAttribute));

            foreach (var type in collection)
            {
                RegisterSystemType(type);
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// Get all the DTOs/classes that will be stored in our data storage
 /// </summary>
 /// <param name="assembly"></param>
 /// <returns></returns>
 public static IEnumerable<Type> GetTableClasses(System.Reflection.Assembly assembly)
 {
     foreach (Type type in assembly.GetTypes())
     {
         if (type.GetCustomAttributes(typeof(TableAttribute), true).Length > 0)
         {
             yield return type;
         }
     }
 }
Exemplo n.º 16
0
        public static object FindInterface(System.Reflection.Assembly DLL, string InterfaceName)
        {
            // Loop through types looking for one that implements the given interface
            foreach (Type t in DLL.GetTypes())
            {
                if (t.GetInterface(InterfaceName, true) != null)
                    return DLL.CreateInstance(t.FullName);
            }

            return null;
        }
Exemplo n.º 17
0
 /// <summary>
 /// Get Extension Methods
 /// </summary>
 /// <param name="assembly">Assembly to check (this)</param>
 /// <param name="extendedType">Class</param>
 /// <returns></returns>
 public static IEnumerable<System.Reflection.MethodInfo> GetExtensionMethods(System.Reflection.Assembly assembly, Type extendedType)
 {
     var query = from type in assembly.GetTypes()
                 where type.IsSealed && !type.IsGenericType && !type.IsNested
                 from method in type.GetMethods(System.Reflection.BindingFlags.Static
                     | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)
                 where method.IsDefined(typeof(System.Runtime.CompilerServices.ExtensionAttribute), false)
                 where method.GetParameters()[0].ParameterType == extendedType
                 select method;
     return query;
 }
Exemplo n.º 18
0
 /// <summary>
 /// Gets the amendments defined in the specified <see cref="Assembly"/>.
 /// </summary>
 /// <param name="assembly"></param>
 /// <returns></returns>
 public static IEnumerable<ITypeAmendment> GetAmendments(System.Reflection.Assembly assembly)
 {
     foreach (var type in assembly.GetTypes())
     {
         foreach (var amendment in type.GetCustomAttributes(true).OfType<IAmendmentAttribute>().SelectMany(attr => attr.GetAmendments(type)))
         {
             if (amendment is Amendment)
                 ((Amendment)amendment).Initialize();
             yield return amendment;
         }
     }
 }
Exemplo n.º 19
0
 /// <summary>
 /// Runs all tests in the given assembly.
 /// </summary>
 /// <param name="assembly">The assembly to process.</param>
 /// <remarks>
 /// <para>Finds all classes in assembly that have the <see cref="TestFixture"/> attribute.
 /// For each test fixture, finds all methods with the <see cref="Test"/> attribute.  For
 /// each test method, instantiates the fixture object, calls all methods with the
 /// <see cref="SetUp"/> attribute, then calls the test method.</para>
 /// <para>Assumes that tests throw uncaught exceptions to indicate failure.</para>
 /// </remarks>
 public static void RunTestsInAssembly(System.Reflection.Assembly assembly)
 {
     int numTestsPassed = 0;
     foreach (Type fixture in assembly.GetTypes())
     {
         if (TestFixture.IsOn(fixture))
         {
             foreach (System.Reflection.MethodInfo testMethod in fixture.GetMethods())
             {
                 if (Test.IsOn(testMethod))
                 {
                     Console.WriteLine("Running Test {0}.{1}...",
                         fixture.FullName, testMethod.Name);
                     Type[] noTypes = { };
                     object instance = fixture.GetConstructor(noTypes).Invoke(null);
                     foreach (System.Reflection.MethodInfo setupMethod in
                         fixture.GetMethods())
                     {
                         if (SetUp.IsOn(setupMethod))
                         {
                             try
                             {
                                 setupMethod.Invoke(instance, null);
                             }
                             catch (System.Reflection.TargetInvocationException te)
                             {
                                 PrintFailure(String.Format(
                                     "setup method {0} for test {1} on fixture {2}",
                                     setupMethod.Name, testMethod.Name, fixture.FullName),
                                     te.InnerException);
                                 return;
                             }
                         }
                     }
                     try
                     {
                         testMethod.Invoke(instance, null);
                     }
                     catch (System.Reflection.TargetInvocationException te)
                     {
                         PrintFailure(String.Format("test {0} on fixture {1}",
                             testMethod.Name, fixture.FullName), te.InnerException);
                         return;
                     }
                     Console.WriteLine("Passed.");
                     numTestsPassed++;
                 }
             }
         }
     }
     Console.WriteLine("All {0} tests passed.", numTestsPassed);
 }
Exemplo n.º 20
0
        public static void DiscoverGlobalContexts(RuntimeEnvironment environment, System.Reflection.Assembly assembly)
        {
            var allTypes = assembly.GetTypes();
            var enums = GetMarkedTypes(allTypes.AsParallel(), typeof(SystemEnumAttribute));
            foreach (var item in enums)
            {
                RegisterSystemEnum(item, environment);
            }

            var contexts = GetMarkedTypes(allTypes.AsParallel(), typeof(GlobalContextAttribute));
            foreach (var item in contexts)
            {
                RegisterGlobalContext(item, environment);
            }
        }
		internal void AddAssembly (System.Reflection.Assembly asm, bool force = false)
		{
			if (!force) {
				var assemblyName = asm.GetName ().Name;
				if (assemblyName == "MonoDevelop.AspNet" ||
				    assemblyName == "Microsoft.CodeAnalysis.CSharp" ||
				    assemblyName.Contains ("FSharpBinding")  ||
					assemblyName != "RefactoringEssentials" &&
					!(asm.GetReferencedAssemblies ().Any (a => a.Name == diagnosticAnalyzerAssembly) && asm.GetReferencedAssemblies ().Any (a => a.Name == "MonoDevelop.Ide")))
					return;
			}
			foreach (var type in asm.GetTypes ()) {
				var notPortedYetAttribute = (NotPortedYetAttribute)type.GetCustomAttributes (typeof(NotPortedYetAttribute), false).FirstOrDefault ();
				if (notPortedYetAttribute!= null) {
					continue;
				}
				var analyzerAttr = (DiagnosticAnalyzerAttribute)type.GetCustomAttributes (typeof(DiagnosticAnalyzerAttribute), false).FirstOrDefault ();
				if (analyzerAttr != null) {
					var analyzer = (DiagnosticAnalyzer)Activator.CreateInstance (type);
					foreach (var diag in analyzer.SupportedDiagnostics) {
						try {
							Analyzers.Add (new CodeDiagnosticDescriptor (diag, analyzerAttr.Languages, type));
						} catch (Exception e) {
							LoggingService.LogError ("error while adding diagnostic analyzer: " + diag.Id + " from assembly " + asm.FullName, e);
						}
					}
				}

				var codeFixAttr = (ExportCodeFixProviderAttribute)type.GetCustomAttributes (typeof(ExportCodeFixProviderAttribute), false).FirstOrDefault ();
				if (codeFixAttr != null) {
					Fixes.Add (new CodeDiagnosticFixDescriptor (type, codeFixAttr));
				}

				var exportAttr = type.GetCustomAttributes (typeof(ExportCodeRefactoringProviderAttribute), false).FirstOrDefault () as ExportCodeRefactoringProviderAttribute;
				if (exportAttr != null) {
					Refactorings.Add (new CodeRefactoringDescriptor (type, exportAttr)); 
				}
			}
		}
Exemplo n.º 22
0
        /// <summary>
        /// Registers the device drivers.
        /// </summary>
        /// <param name="assemblyInfo">The assembly info.</param>
        public void RegisterDeviceDrivers(System.Reflection.Assembly assemblyInfo)
        {
            System.Type[] types = assemblyInfo.GetTypes();

            foreach (System.Type type in types)
            {
                object[] attributes = type.GetCustomAttributes(typeof(IDeviceDriver), false);

                foreach (object attribute in attributes)
                    if (((attribute as IDeviceDriver).Platforms & platformArchitecture) != 0)
                    {
                        DeviceDriver deviceDriver = new DeviceDriver(attribute as IDeviceDriver, type);

                        object[] memAttributes = type.GetCustomAttributes(typeof(DeviceDriverPhysicalMemoryAttribute), false);

                        foreach (object memAttribute in memAttributes)
                            deviceDriver.Add(memAttribute as DeviceDriverPhysicalMemoryAttribute);

                        deviceDrivers.Add(deviceDriver);
                    }
            }
        }
Exemplo n.º 23
0
 private void DetectAndAssignDriver(System.Reflection.Assembly Assembly)
 {
     foreach (var type in Assembly.GetTypes().Where(t => t.Name == "Game"))
     {
         try
         {
             var property = type.GetProperty("Driver");
             if (property != null && property.PropertyType == typeof(Driver) && property.CanWrite)
                 property.SetValue(null, this);
         }
         catch (Exception e) { }
     }
 }
 /// <summary>
 /// 遍历所有的 protobuf 消息类,将类型及类名存入字典
 /// </summary>
 /// <param name="assembly"></param>
 private void InitProtobufTypes( System.Reflection.Assembly assembly )
 {
     foreach ( System.Type t in assembly.GetTypes() ) {
             ProtoBuf.ProtoContractAttribute[] pc = (ProtoBuf.ProtoContractAttribute[])t.GetCustomAttributes( typeof( ProtoBuf.ProtoContractAttribute ), false );
             if ( pc.Length > 0 ) {
                 mProtobufType.Add( t.Name, t );
             }
         }
 }
Exemplo n.º 25
0
		private int DoLoadRules(System.Reflection.Assembly assembly, AssemblyCache cache, Severity severity, bool ignoreBreaks)
		{			
			int count = 0;
			TargetRuntime runtime = cache.Assembly.Runtime;
			
#if DEBUG
			m_checkIDs.Add("C1004");			// rule failed rule
#endif

			Type[] types = assembly.GetTypes();
			foreach (Type t in types)
			{
				if (t.IsClass && !t.IsAbstract && typeof(Rule).IsAssignableFrom(t))
				{
					try
					{
						object o = Activator.CreateInstance(t, new object[]{cache, this});
						Rule rule = (Rule) o;
						
						if (rule.Runtime <= runtime)
						{
							if (DoRuleRequiresCheck(rule.CheckID, severity, ignoreBreaks))
							{
								rule.Register(m_dispatcher);
								m_rules.Add(rule);
							}
						}
						++count;
#if DEBUG
						m_checkIDs.Add(rule.CheckID);
#endif

					}
					catch (Exception e)
					{
						Console.Error.WriteLine("Couldn't instantiate {0}", t);
						Console.Error.WriteLine(e.Message);
						Log.ErrorLine(this, e.StackTrace);
					}
				}
			}
			
			return count;
		}
Exemplo n.º 26
0
 IEnumerable<Type> LoadPluginAssembly(System.Reflection.Assembly asm)
 {
     try {
     var res = asm.GetTypes()
     .Where(type => type.GetCustomAttributes(typeof(PluginAttribute), true).Length>0)
     .Where(type => type.GetInterfaces().Contains(typeof(IPlugin)))
     .OrderBy(type => ((PluginAttribute)(type.GetCustomAttributes(typeof(PluginAttribute), true)[0])).Priority);
     foreach (var settingtype in asm.GetTypes().Where(type => type.GetCustomAttributes(typeof(PecaSettingsAttribute), true).Length>0)) {
       PecaSettings.RegisterType(settingtype);
     }
     return res;
       }
       catch (System.Reflection.ReflectionTypeLoadException) {
     return Enumerable.Empty<Type>();
       }
 }
 private Type FindServiceLocatorAccessorType(System.Reflection.Assembly assembly)
 {
     var accessorInterfaceType = typeof(ISharePointServiceLocatorAccessor);
     return assembly.GetTypes().Where(someType => accessorInterfaceType.IsAssignableFrom(someType) && !someType.IsInterface).FirstOrDefault();
 }
Exemplo n.º 28
0
        public Type[] Execute(System.Reflection.Assembly assembly)
        {
            var targetNamespaces = NamespaceList.Create();
            var resourceNames = assembly.GetManifestResourceNames().Where(n => n.EndsWith("VenusIoc.config"));
            foreach (var resourceName in resourceNames)
            {
                var xmlDoc = new XmlDocument();
                using (var sr = new StreamReader(assembly.GetManifestResourceStream(resourceName)))
                {
                    xmlDoc.Load(sr);
                    foreach (var node in xmlDoc.DocumentElement.SelectNodes("components/assemblyScan/namespace"))
                    {
                        var name = ((XmlElement)node).GetAttribute("name");
                        if (!string.IsNullOrWhiteSpace(name))
                        {
                            targetNamespaces.Add(name.Split('.'));
                        }
                    }
                }
            }

            if (targetNamespaces.Count == 0)
                return new Type[0];

            var types = new List<Type>();
            var checkList = new HashSet<string>();
            var ignoreList = new HashSet<string>();
            foreach (var type in assembly.GetTypes())
            {
                bool toCheck = false;
                if (!ignoreList.Contains(type.Namespace) && type.Namespace != null)
                {
                    if (checkList.Contains(type.Namespace))
                    {
                        toCheck = true;
                    }
                    else
                    {
                        if (targetNamespaces.Include(type.Namespace.Split('.')))
                        {
                            checkList.Add(type.Namespace);
                            toCheck = true;
                        }
                        else
                        {
                            ignoreList.Add(type.Namespace);
                        }
                    }
                }

                if (toCheck)
                {
                    if (!type.IsAbstract && type.IsDefined(typeof(NamedAttribute), false))
                    {
                        types.Add(type);
                    }
                }
            }

            return types.ToArray();
        }
Exemplo n.º 29
0
        /// <summary> Writes the mapping of all mapped classes of the specified assembly in the specified stream. </summary>
        /// <param name="stream">Where the xml is written.</param>
        /// <param name="assembly">Assembly used to extract user-defined types containing a valid attribute (can be [Class] or [xSubclass]).</param>
        public virtual void Serialize(System.IO.Stream stream, System.Reflection.Assembly assembly)
        {
            if(stream == null)
                throw new System.ArgumentNullException("stream");
            if(assembly == null)
                throw new System.ArgumentNullException("assembly");

            System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter( stream, System.Text.Encoding.UTF8 );
            writer.Formatting = System.Xml.Formatting.Indented;
            writer.WriteStartDocument();
            if(WriteDateComment)
                writer.WriteComment( string.Format( "Generated from NHibernate.Mapping.Attributes on {0}.", System.DateTime.Now.ToString("u") ) );
            WriteHibernateMapping(writer, null);

            // Write imports (classes decorated with the [ImportAttribute])
            foreach(System.Type type in assembly.GetTypes())
            {
                object[] imports = type.GetCustomAttributes(typeof(ImportAttribute), false);
                foreach(ImportAttribute import in imports)
                {
                    writer.WriteStartElement("import");
                    if(import.Class != null && import.Class != string.Empty)
                        writer.WriteAttributeString("class", import.Class);
                    else // Assume that it is the current type that must be imported
                        writer.WriteAttributeString("class", HbmWriterHelper.GetNameWithAssembly(type));
                    if(import.Rename != null && import.Rename != string.Empty)
                        writer.WriteAttributeString("rename", import.Rename);
                    writer.WriteEndElement();
                }
            }

            // Write classes and x-subclasses (classes must come first if inherited by "external" subclasses)
            int classCount = 0;
            System.Collections.ArrayList mappedClassesNames = new System.Collections.ArrayList();
            foreach(System.Type type in assembly.GetTypes())
            {
                if( ! IsClass(type) )
                    continue;
                HbmWriter.WriteClass(writer, type);
                mappedClassesNames.Add(HbmWriterHelper.GetNameWithAssembly(type));
                classCount++;
            }

            System.Collections.ArrayList subclasses = new System.Collections.ArrayList();
            System.Collections.Specialized.StringCollection extendedClassesNames = new System.Collections.Specialized.StringCollection();
            foreach(System.Type type in assembly.GetTypes())
            {
                if( ! IsSubclass(type) )
                    continue;
                bool map = true;
                System.Type t = type;
                while( (t=t.DeclaringType) != null )
                    if (IsClass(t) || AreSameSubclass(type, t)) // If a base class is also mapped... (Note: A x-subclass can only contain x-subclasses of the same family)
                    {
                        map = false; // This class's mapping is already included in the mapping of the base class
                        break;
                    }
                if(map)
                {
                    subclasses.Add(type);
                    if( IsSubclass(type, typeof(SubclassAttribute)) )
                        extendedClassesNames.Add((type.GetCustomAttributes(typeof(SubclassAttribute), false)[0] as SubclassAttribute).Extends);
                    else if( IsSubclass(type, typeof(JoinedSubclassAttribute)) )
                        extendedClassesNames.Add((type.GetCustomAttributes(typeof(JoinedSubclassAttribute), false)[0] as JoinedSubclassAttribute).Extends);
                    else if( IsSubclass(type, typeof(UnionSubclassAttribute)) )
                        extendedClassesNames.Add((type.GetCustomAttributes(typeof(UnionSubclassAttribute), false)[0] as UnionSubclassAttribute).Extends);
                }
            }
            classCount += subclasses.Count;
            MapSubclasses(subclasses, extendedClassesNames, mappedClassesNames, writer);

            writer.WriteEndElement(); // </hibernate-mapping>
            writer.WriteEndDocument();
            writer.Flush();

            if(classCount == 0)
                throw new MappingException("The following assembly contains no mapped classes: " + assembly.FullName);
            if( ! Validate )
                return;

            // Validate the generated XML stream
            try
            {
                writer.BaseStream.Position = 0;
                System.Xml.XmlTextReader tr = new System.Xml.XmlTextReader(writer.BaseStream);
                System.Xml.XmlValidatingReader vr = new System.Xml.XmlValidatingReader(tr);

                // Open the Schema
                System.IO.Stream schema = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("NHibernate.Mapping.Attributes.nhibernate-mapping.xsd");
                vr.Schemas.Add("urn:nhibernate-mapping-2.2", new System.Xml.XmlTextReader(schema));
                vr.ValidationType = System.Xml.ValidationType.Schema;
                vr.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(XmlValidationHandler);

                _stop = false;
                while(vr.Read() && !_stop) // Read to validate (stop at the first error)
                    ;
            }
            catch(System.Exception ex)
            {
                Error.Append(ex.ToString()).Append(System.Environment.NewLine + System.Environment.NewLine);
            }
        }
Exemplo n.º 30
0
        /// <summary> Writes a hbm.xml file in the specified directory for each mapped class in the specified assembly. </summary>
        /// <param name="directory">Directory where each serialized hbm.xml file will be written.</param>
        /// <param name="assembly">Assembly used to extract user-defined types containing a valid attribute (can be [Class] or [xSubclass]).</param>
        public virtual void Serialize(string directory, System.Reflection.Assembly assembly)
        {
            if(assembly == null)
                throw new System.ArgumentNullException("assembly");

            foreach(System.Type type in assembly.GetTypes())
            {
                if( type.IsNestedFamORAssem || type.IsNestedPrivate || type.IsNestedPublic )
                    continue; // will be include in its container mapping file
                if( IsClass(type) || IsSubclass(type) )
                    Serialize( System.IO.Path.Combine(directory, type.Name+".hbm.xml"), type );
            }
        }