Obtaining classes from a namespace - c#

I'm trying to get the Class and Methods from a assembly, it works when the assembly is the same where the class is, but when it does not work when the assembly is in other project. I already add the reference from the project I want to obtain the Class and Methods but the var theList returns null. I want get the class and methods from one proyect to another , the 2 proyects are in the same solution. I need some help
class Program
{
static void Main(string[] args)
{
var theList = Assembly.GetExecutingAssembly().GetTypes().ToList().Where(t => t.Namespace == "____mvc4.Models").ToList();
Console.WriteLine("--List of Classes with his respective namescpace : ");
foreach (var item in theList)
{
Console.WriteLine(item);
}
Console.WriteLine("------List of classes: ");
foreach (var item in theList)
{
Console.WriteLine("*****************" + item.Name + "*****************");
MemberInfo[] memberInfo = item.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Instance);
for (int i = 0; i < memberInfo.Length; i++)
{
if (!(memberInfo[i].Name.Contains("get_") || memberInfo[i].Name.Contains("set_")))
{
Console.WriteLine("{0}", memberInfo[i].Name);
}
}
}
Console.ReadLine();
}
the asembly where are the classes that I want obtain does not appear in AppDomain.CurrentDomain.GetAssemblies().ToList();

Here...
var theList = Assembly.GetExecutingAssembly().GetTypes()...etc
you are referring to the current ("executing") assembly. If you want to get types from another assembly, you need to get a reference to that assembly. A simple way to do so is to reference some type from that referenced assembly:
var otherAssembly = typeof(SomeTypeDefinedInAReferencedAssembly).Assembly;
var theList = otherAssembly.GetTypes()...etc

If you want to do it dynamically, then you need to get all the assemblies in the current domain or iterate the /bin/ directory. The domain will get you all kinds of assemblies, including your standard ones, like System. /bin/ will restrict you to just your custom stuff.
Here's a utility method I use. You pass in the evaluation -- i.e. the filter -- and it spits back a list of Types.
public static List<Type> GetClassesWhere(Func<Type, bool> evaluator)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
var types = new List<Type>();
foreach(var assembly in assemblies)
{
try
{
types.AddRange(assembly.GetTypes().Where(evaluator).ToList());
}
catch
{
}
}
return types;
}
I try/catch each assembly individually because I found that sometimes I get some weird permission denied errors, especially in shared environments such as Azure and AppHarbor. It was always on assemblies I didn't care about anyway, so that's why I take no action on catch. For my custom assemblies, it always works for me.
In your example, you'd use it thusly (assuming you put it in a static class called Utilities)
var types = Utilities.GetClassesWhere(t => t.Namespace == "____mvc4.Models");

If you're trying to do this generically as possible, without knowing or caring which assemblies contain this namespaces, you need to check the loaded modules:
var theList = new List<Type>();
BuildManager.GetReferencedAssemblies();
var modules = Assembly.GetExecutingAssembly().GetLoadedModules();
theList.AddRange(modules.SelectMany(x => x.Assembly.GetTypes().Where(t => t.Namespace == "____mvc4.Models")));

AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(am => am.GetTypes())
.Select(a => a.Namespace == "Name of your namespace")
.Distinct();

Related

Nuget Library to get all types that implement an interface in all assemblies and referenced assemblies

I am struggling to find a good answer on this.
I need to scan all the classes that implement an interface IDomainEvent.
The problem is that those types are in projects that are not necessarily loaded. For example, if my main assembly is WebApi, there is a dependency on Application, which depends on Domain, which depends on DomainEvents
therefore, I don't have an "easy" way to get all the types that implement IDomainEvent and are in *DomainEvents.csproj projects
Is there any nuget library that can dynamically navigate through all referenced projects/assemblies and its subdependencies and is able to retrieve all types implementing an interface?
It happens at startup once, so I'm not too concerned about performance.
PS: The following method returns 0, as expected, because the assemblies are not loaded
var allDomainEventTypes =
AppDomain
.CurrentDomain
.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(t => t.IsAssignableTo(typeof(IDomainEvent)) && !t.IsInterface)
.ToList();
You could possible try something along this lines
var definitions = typeof(YourTypeInsideAssembly).Assembly.GetImplementationsOf(typeof(IYourInterfaceType));
foreach (var definition in definitions)
{
//Do you thing with definition.
}
This would require to specify YourTypeInsideAssembly for each implementation of the interface. E.G if you have one project which has 3 classes implementing the interface and another which has 4. You would need to specify two classes one for each project.
I think this way you are forcing to load the assembly as well.
P.S
This worked for me previously as well:
var allAssemblies = Assembly
.GetEntryAssembly()
.GetReferencedAssemblies()
.Select(Assembly.Load)
.ToArray();
I haven't found anything nice.
I've got the following workaround (thanks to this great article)
public static class AssemblyExtensions
{
public static IEnumerable<Assembly> GetAllAssemblies(this Assembly rootAssembly)
{
var returnAssemblies = new List<Assembly>();
var loadedAssemblies = new HashSet<string>();
var assembliesToCheck = new Queue<Assembly>();
assembliesToCheck.Enqueue(rootAssembly);
while (assembliesToCheck.Any())
{
var assemblyToCheck = assembliesToCheck.Dequeue();
foreach (var reference in assemblyToCheck.GetReferencedAssemblies())
{
var fullName = reference.FullName;
if (!loadedAssemblies.Contains(fullName))
{
var assembly = Assembly.Load(reference);
assembliesToCheck.Enqueue(assembly);
loadedAssemblies.Add(fullName);
returnAssemblies.Add(assembly);
}
}
}
return returnAssemblies;
}
}
It works well as it's capable of "recursively" loading referenced assemblies and therefore I can retrieve all types implementing the given interface.
However, notice that referencing a project does not necessarily mean that the assembly will be referenced if no class from that project is used.
var domainEventTypes =
typeof(Startup)
.Assembly
.GetAllAssemblies()
.SelectMany(x => x.GetTypes())
.Where(t => t.IsAssignableTo(typeof(IDomainEvent)))
.ToList();

How do I determine if a property is a user-defined type in C#?

How do I determine if a property is a user-defined type? I tried to use IsClass as shown below but its value was true for String properties (and who knows what else).
foreach (var property in type.GetProperties()) {
if (property.PropertyType.IsClass) {
// do something with property
}
}
* Updated for more clarity *
I am trying to traverse a given type's definition and if the given type or any of its public properties are defined within the assembly, I am searching for an embedded JavaScript document. I just don't want to waste processing resources and time on native .NET types.
#Bobson made a really good point:
"...Unlike some other languages, C# does not make any actual
distinction between "user-defined" and "standard" types."
Technically, #Bobson gave the answer; there is no distinguishing difference between a user-defined type and one defined in the .NET Framework or any other assembly for that matter.
However, I found a couple useful ways to determine if a type is user-defined.
To search for all types defined within the given type's assembly, this works great:
foreach (var property in type.GetProperties()) {
if (property.PropertyType.IsClass
&& property.PropertyType.Assembly.FullName == type.Assembly.FullName) {
// do something with property
}
}
If the types can be defined in various assemblies, excluding the System namespace works in most cases:
foreach (var property in type.GetProperties()) {
if (property.PropertyType.IsClass
&& !property.PropertyType.FullName.StartsWith("System.")) {
// do something with property
}
}
If by "user-defined" you mean that it is not part of the standard assembly (mscorlib) then you can do something along the lines of this:
if(typeof(SomeType).Assembly.GetName().Name != "mscorlib") {
// user-defined!
}
However this will also consider types from external assemblies (aka: libraries) to be considered "user-defined". If you only want those in your current assembly then you can use
typeof(SomeType).Assembly == Assembly.GetExecutingAssembly()
I wrote a generic populator for unit testing that assigns predictable values to my objects and came across this kind of problem. In my case I wanted to know which of my properties were objects so that I could recursively populate those object properties, again with predictable values.
It seemed to me that introducing an interface implemented only by the classes that I was interested in traversing was the best way to do this. You can then test to see if your property is an object of interest:
public static bool IsMyInterface(this Type propertyType)
{
return propertyType.GetInterface("MyInterfaceName") != null;
}
Say your project is named "Foobar" and everything you make is under that namespace. You can test to see if you've written it by the following method:
typeof(SomeType).Namespace.Contains("Foobar");
I struggled with this as well when creating a log when updating the database. I did not want the classes to be shown in the log as they never == between data and dto.
foreach (PropertyType item in properties)
{
if((item.PropertyType.IsClass && item.PropertyType.FullName.StartsWith("System.")) || !item.PropertyType.IsClass)
{
//...do stuff
}
}
This allowed me to deal with strings and the likes which are flagged as classes.
If by "user-defined" type you mean type that was declared in your executing assembly then you can obtain list of that types like in this sample c# console application:
class Program
{
static void Main( string[] args )
{
var currentAssembly = Assembly.GetExecutingAssembly();
var localTypes = currentAssembly.GetTypes();
}
}
UPDATE:
If you want to obtain list of types from all referenced assemblies:
class Program
{
static void Main( string[] args )
{
var currentAssembly = Assembly.GetExecutingAssembly();
var referencedAssemblies = currentAssembly.GetReferencedAssemblies();
var typesFromReferencedAssemblies = referencedAssemblies.Select( assemblyName => Assembly.ReflectionOnlyLoad( assemblyName.FullName ) ).SelectMany( assembly => assembly.GetTypes() );
}
}
Just be aware that Program type will also be in that list. Is this sufficient answer to your problem?

Getting a list of all available namespaces in an AppDomain

I need to 'scan' the active AppDomain for all loaded assemblies at run time and get a list of unique namespaces available in those assemblies, does .NET support that?
The code must execute during the run time, so that the code is dynamic.
I just started coding in C# , so I'm a bit unsure about where to get started, so any help will be appreciated.
Start from an AppDomain (AppDomain.CurrentDomain perhaps) and call GetAssemblies. On each assembly iterate over the types it defines, keeping track of which namespace each one is in.
As an example of how easy it is to do this with LINQ consider this:
var namespaces = AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(a => a.GetTypes())
.Select(t => t.Namespace)
.Distinct()
// optionally .OrderBy(ns => ns) here to get sorted results
.ToList();
As a matter of fact I wrote some code that lets you do that a couple of days ago.
Use this class:
public class NSScanner
{
public static List<Type> GetLoadedTypes(AppDomain appDomain)
{
return _getLoadedTypes(appDomain);
}
public static List<Type> GetPublicLoadedTypes(AppDomain appDomain)
{
return _getLoadedTypes(appDomain, true);
}
public static List<string> GetUniqueNamespaces(IEnumerable<Type> types)
{
var uniqueNamespaces = new ConcurrentBag<string>();
Parallel.ForEach(types, type =>
{
if (!uniqueNamespaces.Contains(type.Namespace) && !string.IsNullOrEmpty(type.Namespace))
uniqueNamespaces.Add(type.Namespace);
});
var sortedList = uniqueNamespaces.OrderBy(o => o).ToList();
return sortedList;
}
private static List<Type> _getLoadedTypes(AppDomain appDomain, bool onlyPublicTypes = false)
{
var loadedAssemblies = appDomain.GetAssemblies();
var loadedTypes = new List<Type>();
Parallel.ForEach(loadedAssemblies, asm =>
{
Type[] asmTypes;
if (onlyPublicTypes)
asmTypes = asm.GetExportedTypes();
else
asmTypes = asm.GetTypes();
loadedTypes.AddRange(asmTypes);
});
return loadedTypes;
}
}
Usage:
var publicLoadedTypes = NSScanner.GetPublicLoadedTypes(AppDomain.CurrentDomain);
var namespaces = NSScanner.GetUniqueNamespaces(publicLoadedTypes);
Enjoy!

How enumerate all classes with custom class attribute?

Question based on MSDN example.
Let's say we have some C# classes with HelpAttribute in standalone desktop application. Is it possible to enumerate all classes with such attribute? Does it make sense to recognize classes this way? Custom attribute would be used to list possible menu options, selecting item will bring to screen instance of such class. Number of classes/items will grow slowly, but this way we can avoid enumerating them all elsewhere, I think.
Yes, absolutely. Using Reflection:
static IEnumerable<Type> GetTypesWithHelpAttribute(Assembly assembly) {
foreach(Type type in assembly.GetTypes()) {
if (type.GetCustomAttributes(typeof(HelpAttribute), true).Length > 0) {
yield return type;
}
}
}
Well, you would have to enumerate through all the classes in all the assemblies that are loaded into the current app domain. To do that, you would call the GetAssemblies method on the AppDomain instance for the current app domain.
From there, you would call GetExportedTypes (if you only want public types) or GetTypes on each Assembly to get the types that are contained in the assembly.
Then, you would call the GetCustomAttributes extension method on each Type instance, passing the type of the attribute you wish to find.
You can use LINQ to simplify this for you:
var typesWithMyAttribute =
from a in AppDomain.CurrentDomain.GetAssemblies()
from t in a.GetTypes()
let attributes = t.GetCustomAttributes(typeof(HelpAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<HelpAttribute>() };
The above query will get you each type with your attribute applied to it, along with the instance of the attribute(s) assigned to it.
Note that if you have a large number of assemblies loaded into your application domain, that operation could be expensive. You can use Parallel LINQ to reduce the time of the operation (at the cost of CPU cycles), like so:
var typesWithMyAttribute =
// Note the AsParallel here, this will parallelize everything after.
from a in AppDomain.CurrentDomain.GetAssemblies().AsParallel()
from t in a.GetTypes()
let attributes = t.GetCustomAttributes(typeof(HelpAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<HelpAttribute>() };
Filtering it on a specific Assembly is simple:
Assembly assembly = ...;
var typesWithMyAttribute =
from t in assembly.GetTypes()
let attributes = t.GetCustomAttributes(typeof(HelpAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<HelpAttribute>() };
And if the assembly has a large number of types in it, then you can use Parallel LINQ again:
Assembly assembly = ...;
var typesWithMyAttribute =
// Partition on the type list initially.
from t in assembly.GetTypes().AsParallel()
let attributes = t.GetCustomAttributes(typeof(HelpAttribute), true)
where attributes != null && attributes.Length > 0
select new { Type = t, Attributes = attributes.Cast<HelpAttribute>() };
Other answers reference GetCustomAttributes. Adding this one as an example of using IsDefined
Assembly assembly = ...
var typesWithHelpAttribute =
from type in assembly.GetTypes()
where type.IsDefined(typeof(HelpAttribute), false)
select type;
As already stated, reflection is the way to go. If you are going to call this frequently, I highly suggest caching the results, as reflection, especially enumerating through every class, can be quite slow.
This is a snippet of my code that runs through all the types in all loaded assemblies:
// this is making the assumption that all assemblies we need are already loaded.
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
foreach (Type type in assembly.GetTypes())
{
var attribs = type.GetCustomAttributes(typeof(MyCustomAttribute), false);
if (attribs != null && attribs.Length > 0)
{
// add to a cache.
}
}
}
This is a performance enhancement on top of the accepted solution. Iterating though all classes can be slow because there are so many. Sometimes you can filter out an entire assembly without looking at any of its types.
For example if you are looking for an attribute that you declared yourself, you don't expect any of the system DLLs to contain any types with that attribute. The Assembly.GlobalAssemblyCache property is a quick way to check for system DLLs. When I tried this on a real program I found I could skip 30,101 types and I only have to check 1,983 types.
Another way to filter is to use Assembly.ReferencedAssemblies. Presumably if you want classes with a specific attribute, and that attribute is defined in a specific assembly, then you only care about that assembly and other assemblies that reference it. In my tests this helped slightly more than checking the GlobalAssemblyCache property.
I combined both of these and got it even faster. The code below includes both filters.
string definedIn = typeof(XmlDecoderAttribute).Assembly.GetName().Name;
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
// Note that we have to call GetName().Name. Just GetName() will not work. The following
// if statement never ran when I tried to compare the results of GetName().
if ((!assembly.GlobalAssemblyCache) && ((assembly.GetName().Name == definedIn) || assembly.GetReferencedAssemblies().Any(a => a.Name == definedIn)))
foreach (Type type in assembly.GetTypes())
if (type.GetCustomAttributes(typeof(XmlDecoderAttribute), true).Length > 0)
In case of the Portable .NET limitations, the following code should work:
public static IEnumerable<TypeInfo> GetAtributedTypes( Assembly[] assemblies,
Type attributeType )
{
var typesAttributed =
from assembly in assemblies
from type in assembly.DefinedTypes
where type.IsDefined(attributeType, false)
select type;
return typesAttributed;
}
or for a large number of assemblies using loop-state based yield return:
public static IEnumerable<TypeInfo> GetAtributedTypes( Assembly[] assemblies,
Type attributeType )
{
foreach (var assembly in assemblies)
{
foreach (var typeInfo in assembly.DefinedTypes)
{
if (typeInfo.IsDefined(attributeType, false))
{
yield return typeInfo;
}
}
}
}
This is another version of the code provided by Trade-Ideas philip,
I've condensed the code to linq, plugged it into a nice static function which you can just drop in the project.
Original:
https://stackoverflow.com/a/41411243/4122889
I've also added AsParallel() - on my machine with enough cores etc, and with a 'normally' sized project (which is completely subjective), this was the fastest/
Without AsParallel() this took 1,5 seconds for about 200 results, and with it, it took about a couple milliseconds - therefore this seems the fastest to me.
Note that this skips the assemblies in the GAC.
private static IEnumerable<IEnumerable<T>> GetAllAttributesInAppDomain<T>()
{
var definedIn = typeof(T).Assembly.GetName().Name;
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var res = assemblies.AsParallel()
.Where(assembly => (!assembly.GlobalAssemblyCache) && ((assembly.GetName().Name == definedIn) ||
assembly.GetReferencedAssemblies()
.Any(a => a.Name == definedIn))
)
.SelectMany(c => c.GetTypes())
.Select(type => type.GetCustomAttributes(typeof(T), true)
.Cast<T>()
)
.Where(c => c.Any());
return res;
}
Usage:
var allAttributesInAppDomain = GetAllAttributesInAppDomain<ExportViewAttribute>();
Note if you have only 1 attribute per class, so not multiple, its easier to flatten the result from IEnumerable<IEnumerable<T>> to IEnumerable<T> like so:
var allAttributesInAppDomainFlattened = allAttributesInAppDomain.SelectMany(c => c);
Remember, this uses IEnumerable so call ToList() to actually run the function.
We can improve on Andrew's answer and convert the whole thing into one LINQ query.
public static IEnumerable<Type> GetTypesWithHelpAttribute(Assembly assembly)
{
return assembly.GetTypes().Where(type => type.GetCustomAttributes(typeof(HelpAttribute), true).Length > 0);
}

How to find all the classes which implement a given interface?

Under a given namespace, I have a set of classes which implement an interface. Let's call it ISomething. I have another class (let's call it CClass) which knows about ISomething but doesn't know about the classes which implement that interface.
I would like that CClass to look for all the implementation of ISomething, instantiate an instance of it and execute the method.
Does anybody have an idea on how to do that with C# 3.5?
A working code-sample:
var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterfaces().Contains(typeof(ISomething))
&& t.GetConstructor(Type.EmptyTypes) != null
select Activator.CreateInstance(t) as ISomething;
foreach (var instance in instances)
{
instance.Foo(); // where Foo is a method of ISomething
}
Edit Added a check for a parameterless constructor so that the call to CreateInstance will succeed.
You can get a list of loaded assemblies by using this:
Assembly assembly = System.Reflection.AppDomain.CurrentDomain.GetAssemblies()
From there, you can get a list of types in the assembly (assuming public types):
Type[] types = assembly.GetExportedTypes();
Then you can ask each type whether it supports that interface by finding that interface on the object:
Type interfaceType = type.GetInterface("ISomething");
Not sure if there is a more efficient way of doing this with reflection.
A example using Linq:
var types =
myAssembly.GetTypes()
.Where(m => m.IsClass && m.GetInterface("IMyInterface") != null);
foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
{
if (t.GetInterface("ITheInterface") != null)
{
ITheInterface executor = Activator.CreateInstance(t) as ITheInterface;
executor.PerformSomething();
}
}
You could use something like the following and tailor it to your needs.
var _interfaceType = typeof(ISomething);
var currentAssembly = System.Reflection.Assembly.GetExecutingAssembly();
var types = GetType().GetNestedTypes();
foreach (var type in types)
{
if (_interfaceType.IsAssignableFrom(type) && type.IsPublic && !type.IsInterface)
{
ISomething something = (ISomething)currentAssembly.CreateInstance(type.FullName, false);
something.TheMethod();
}
}
This code could use some performance enhancements but it's a start.
Maybe we should go this way
foreach ( var instance in Assembly.GetExecutingAssembly().GetTypes().Where(a => a.GetConstructor(Type.EmptyTypes) != null).Select(Activator.CreateInstance).OfType<ISomething>() )
instance.Execute();

Categories

Resources