views:

117

answers:

1
+2  Q: 

Query assembly

I have a .NET assembly that has tens of classes and methods which are unit testing methods. I want to generate a report with all the method marked with attribute Ignore, do you know a simple way to do that?

+6  A: 

You want the get Custom Attributes method

Assembly ass = Assembly.Load("yourassembly.dll");
object[] attributes = ass.GetCustomAttributes(typeof(IgnoreAttribute), false));

This method also exists on the method object, so you can iterate through all the types in your assembly and iterate through all their methods, and call the same method.

foreach(Type type in ass.GetTypes()) {
    foreach(MethodInfo method in type.GetMethods()) {
       method.GetCustomAttributes(typeof(IgnoreAttribute), true));
    }
}

Edit, Here is some help with the powershell syntax, although I must say, I am NOT powershell fluent. I am sure someone can do this way better than the crap I have below.

$types = [System.Reflection.Assembly]::LoadFile("C:\dll.dll").GetTypes()
$attribute = [System.Type]::GetType("IgnoreAttribute")
foreach ($type in $types) { 
    $methods = $type.GetMethods()
    foreach ($method in $methods) { 
    if ($method .GetCustomAttributes($attribute).Length -gt 0) { 
        $method.Name
    }
}
Bob
Thanks a lot That was helpfull, but can I do it in Powershell?I am trying to translate the syntax above to powershell
gkar
I've updated my answer to include something which should work in powershell. I think it can be done better, but my powershell isn't up to par
Bob
I wouldn't use Write-Host in this case. While you can see the result on the screen, you can't capture the result to a variable. Just eliminate the Write-Host and the $method.Name will automatically be output.
Keith Hill
For stuff like this, always use [System.Reflection.Assembly]::LoadFrom ... not LoadFile
Jaykul
@Jaykul, why does this matter? We aren't interested in loading any dependencies, we just want to know about the classes in that assembly.
Bob