reflection

  • Thread starter Thread starter frazer
  • Start date Start date
F

frazer

hi,
I have an assembly with many classes in it.
and some of the methods in those classes have this attribute StoredProcedure
before them, which takes different values . (i basically use it to store
storedprocedure names that this function calls.)

[MyCompany1.Data.StoredProcedure("spGetCustomers")]
[MyCompany1.Data.StoredProcedure("spGetSales")]
public void GetCustomers()
{
....
}


[MyCompany1.Data.StoredProcedure("spGetTotalSales")]
public void GetTotalSales()
{
....
}

etc.


what i want to do is iterate all those methods that have this attribute
StoredProcedure
and find out the value (eg: spGetCustomers and spGetSales in the first
case.)

how do i do this.

I havent figured out how do iterate all the classes
and
how do i find out if a method uses that attribute.


//This simply lists all the methods.
Type type = (typeof(MyCompany1.Dal.DataAccessClass1));
MethodInfo[] methodInfo = type.GetMethods();
for(int i =0;i< methodInfo.Length; i++)
{
Console.WriteLine("Name = " + methodInfo.ToString());

}

am i on the right track?
thnx
 
Check out the Assembly class You can use the Static Load,
GetExcecutingAssembly, GetCallingAssembly/etc methods to get a reference to
an assembly object, then you can use the GetTypes method to return Type
objects representing all of the classes in the assembly.

The MethodInfo objects (that your code below is already getting) have a
method called GetCustomAttributes that should return your attributes.
 
hi,
thanx that works fine.
just one little problem.
i have a class library project that has many classes in it.
how do i iterate the class library to see all the classes it has?
the class library is in the namespace "MyCompany1.Data"

currently i am just testing teh application for 1 class.
Assembly assembly = Assembly.GetAssembly(typeof(MyCompany1.Data.Class1));
but i need access to class2 and all others.

thnx
 
currently i am just testing teh application for 1 class.
Assembly assembly = Assembly.GetAssembly(typeof(MyCompany1.Data.Class1));
but i need access to class2 and all others.

You can obtain the list of types in an assembly with the GetTypes() method.
eg:

public void ScanTypes()
{
Assembly assembly = typeof( MyCompany1.Data.Class1 ).Assembly;

foreach ( Type type in assembly.GetTypes() )
{
Console.WriteLine( "Scanning type " + type.FullName + "." );

// Do something with 'type'...
}
}

n!
 
Back
Top