Monday, May 21, 2007

Custom Attributes

What is a Custom Attribute?
A custom Attribute is simply a special class that must comply with these two specification:
· A custom attribute must derive from System.Attribute
· The Constructors for an attribute may only contain types that can be resolved at compile time – such as strings and integers.

The invented Attributes are:
· TestCaseAttribute à Links the code used to test a class to the class itself
· BugFixAttribute à Records who altered what and when within the source code
· DatabaseTableAttribute and DataBaseColumn Attribute à shows how to produce database schemas from .NET classes

What are the steps to create a custom attribute?
· Create a class derived from System.Attribute
· Create the constructor(s) and public properties as required
· Attribute the class to define where it is valid to use your custom attribute.

Explain the TestCaseAttribute?
When unit-testing s/w it is common to define a set of test classes that exercise your classes to ensure that they perform as expected. This is especially true in regressing testing, where you want to ensure that by fixing a bug or adding extra functionality, you have not broken something else.

Note: When working with the regulated customers (under strict controls from govt agencies), it is necessary to provide the cross-references between code and tests. The TestCaseAttribute presented here can help to trace between a class and its test class.

All you need to do here is create a class derived from System.Attribute:
Public class TestCaseAttribute: Attribute
{
}

Explain the BugFixAttribute?
The BugFix attribute constructor takes a bug number and a comment string and is marked with AllowMultiple=true to indicate that it can be used as follows:
[BugFix(“101”,”Created some methods”)]
public class MyBuggyCode
{
}

Explain the DatabaseTableAttribute?
The attribute consists of a constructor that accepts the name of the Table as a string and is marked with the Inherited=false and AllowMultiple=false modifiers. Within the attribute class, you store the name of the table as a field rather than a property.

Explain the DatabaseColumnAttribute?
This attribute is designed to be placed on public properties of the DataRow class and is used to define the name of the column that the property will link to, together with such things as whether the column can contain the null value.

No comments: