Custom Attributes not working.

J

Jared

My goal is to provide some additional functionallity inside the
database wrapper if the current object has the LongRunningAttribute
attribute applied. The attribute is never being instantiated by the
framework. What am I doing wrong?
TIA,
Jared


[LongRunning()]
private DatabaseWrapper _database = new DatabaseWrapper();
private void button2_Click(object sender, EventArgs e)
{
_database.ExecuteCommandMethod("some command", 30);
}

[AttributeUsage(AttributeTargets.Field)]
public class LongRunningAttribute : Attribute
{
public LongRunningAttribute(): base()
{
System.Diagnostics.Debug.Write(this.ToString());
}
}
public class DatabaseWrapper
{
private string _test = string.Empty;
public DatabaseWrapper()
{
this._test = "blah";
}
public object ExecuteCommandMethod(string commandText, int
commandTimeout)
{
return null;
}
}

TIA,
Jared
 
N

Nicholas Paldino [.NET/C# MVP]

Jared,

What do you mean it is never being instantiated? It absolutely is. The
runtime creates an instance of it and applies it to the type the first time
it is used.
 
J

Jared

Nichalos,
First thanks for your reply.

Shouldn't I be able to set a breakpoint in the contstructor of my
attribute class and/or does the diagnostic message display in your
output window?
Neither of these work for me!


Also, when I try to extract the attributes from my current assembly
using the following statement my LongRunning attribute is not contained
within the array.
This I will admit could be due to user error. If I'm trying to extract
the attribute in an incorrect manner please point me in the right
direction.

System.Attribute[] customAttributes =
System.Attribute.GetCustomAttributes(this.GetType().Assembly);

Jared
 
J

Jared

Sorry...before you critique my code for enumerating the attributes the
database wrapper class has a test attribute set up like the LongRunning
attribute.

[Test()]
public class DatabaseWrapper
{
}
 
N

Nicholas Paldino [.NET/C# MVP]

Jared,

Your call for the custom attributes should be like this:

Attribute[] customAttributes =
this.GetType().GetCustomAttributes(typeof(LongRunningAttribute), true);
 
J

Jared

Sorry (again)! I didn't post the right code.
customAttributes =
(System.Attribute[])System.Reflection.Assembly.GetExecutingAssembly().GetType().GetCustomAttributes(typeof(LongRunningAttribute),
false);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top