Take Control of .NET Using Custom Attributes

Take Control of .NET Using Custom Attributes

ET has more than 100 attributes that are used to control XML serialization, Web services, COM interoperability, and more. For example, XmlElementAttribute is used to control the element name and data type used when serializing a class to XML, and AssemblyVersionAttribute is used to assign a version number to an assembly.

But you aren’t limited to using the ones that Microsoft built. Custom attributes allow the developer to store meta-data against program elements, and that data can be accessed at runtime to control program actions. This article will show you how to create your own custom attributes in .NET and will give you a practical example of how to use them.

Creating Your Own Attributes
To create your own custom attribute class, simply create a new class that inherits System.Attribute. Add whatever properties you want (normally you will also add these to your attribute class constructor), and your custom attribute class is ready for use.

The next step is to determine what elements your attribute can be used on. By default, custom attributes can be applied to all program elements. But you can restrict which types of program elements your custom attribute can be applied to by using the AttributeUsage attribute. The constructor for AttributeUsage takes an enumeration argument of type AttributeTargets (this enumeration is a bit mask, so you can combine values with a bitwise or operation).

You can use the other arguments to AttributeUsage to control whether multiple instances of the same attribute are allowed, and whether derived classes inherit your custom attribute. For example, you could use these arguments to define a custom attribute that can be used with a property only, is inherited by derived classes, and can be used only once for each property use. The code to implement those conditions is shown:

< _    System.AttributeUsage( _      System.AttributeTargets.Property, _      AllowMultiple:=False, _      Inherited:=True) _  > _  Public Class ListDisplayAttribute    Inherits System.Attribute    ' Code goes here  End Class

Using Attributes in Code
Attributes can be applied to many elements in .NET code, including assemblies, classes, properties, events, and enumerations. This code demonstrates the same attribute, MonitoringDescription, applied to a class and to a property.

 _Public Class TestClass   _  Public ReadOnly Property TestProp() As String    Get    End Get  End PropertyEnd Class

By convention, classes that inherit from System. Attribute have an “Attribute” suffix added to their names, as in Diagnostics.MonitoringDescriptionAttribute, above. You can use the class name without the “Attribute” suffix when you use attributes in code. In the example above, I used MonitoringDescription on the class and MonitoringDescriptionAttribute on the property. Both are interpreted the same way. This can be a bit confusing because if you are looking for help in the .NET framework documentation, you have to use the “real” class name?that is, use MonitoringDescriptionAttribute when you search or you won’t find the help topic you are looking for.

Reading Custom Attributes at Runtime
To read the value of a custom attribute, call the GetCustomAttributes function of the MemberInfo class. (The MemberInfo class is inherited by EventInfo, FieldInfo, MethodBase, PropertyInfo, and System.Type, and is therefore available from most of the reflection objects).

The GetCustomAttributes function returns an array of Attribute objects. You should always check to make sure that at least one item is in the returned array. It is possible to define the same attribute multiple times on an element, and not all elements will have the attribute defined that you are searching for, so GetCustomAttributes can return an array with multiple results, or an empty array.

This code displays the assembly title of the executing assembly by reading the assembly’s AssemblyTitle attribute value.

Dim objAttrSet() As System.Reflection.AssemblyTitleAttributeobjAttrSet = _  Reflection.Assembly.GetExecutingAssembly.GetCustomAttributes( _  GetType(System.Reflection.AssemblyTitleAttribute), False)If objAttrSet.Length = 0 Then  MsgBox("No Assembly Title attribute was found!")Else  MsgBox(objAttrSet(0).Title)End If

This example reads a custom attribute of a class.

Dim objAttrSet() As System.Diagnostics.MonitoringDescriptionAttributeobjAttrSet = _  Me.GetType.GetCustomAttributes( _  GetType(System.Diagnostics.MonitoringDescriptionAttribute), False)If objAttrSet.Length = 0 Then  MsgBox("No MonitoringDescription attribute was found!")Else  MsgBox(objAttrSet(0).Title)End If

Implementation ideas?Automatic List View
The sample code for this article uses reflection and custom attributes to automatically populate a list view’s column headers for a specified object type. The code contains:

  1. A form containing an instance of our derived list view and some sample code to populate it.
  2. Our custom attribute class, ListDisplayAttribute.
  3. Our derived listview class. This class adds two methods, SetType(), which populates the list view’s column headers collection, and AddItem(), which adds a ListViewItem to the list view, automatically populating the subitems collection for that ListViewItem.
  4. A sample class for holding data called SampleContactObject. This class contains four properties: “name,” “password,” “email,” and “telephone.” This class contains examples of the use of the ListDisplay Attribute.

The ListDisplayAttribute class is pretty straightforward?it is derived from System.Attribute and contains three properties:

Display

true/false

Determines whether to display the property in a list view column

ColumnText

string

The text to place in the column header

DefaultWidth

integer

The width to assign to the column header

Our derived list view class has a GetProperties to get a PropertyInfo object that represents each property in the type.

Author’s Note: The code example has been simplified. Download the full version of the code by clicking the “download the code” link in the left column.)
' Loop through all the properties in the object  For Each prpObjectProperty In mtypListItemType.GetProperties    ' Add column headers    If prpObjectProperty.GetCustomAttributes( _      GetType(Devx.ListDisplayAttribute), True).Length = 0 Then      ' Set default properties    Else      ' Attribute found      attListAttribute = prpObjectProperty.GetCustomAttributes( _        GetType(Devx.ListDisplayAttribute), True)(0)      ' read values      blnShowColumn = attListAttribute.Display      intWidth = attListAttribute.DefaultWidth      ' The header text is not always specified, so we need       ' to use the property name if it is left blank.      strHeader = attListAttribute.ColumnText      If strHeader.Length = 0 Then        strHeader = prpObjectProperty.Name      End If    End If  Next

Inside the loop, I call GetCustomAttributes, check that it returns at least one result, and then read the Display, DefaultWidth, and ColumnText properties into variables used elsewhere in the code.

You can create generic code that uses “self-describing” program elements using reflection and custom attributes. I’ve used this technique to create generic classes that read and write themselves to database tables and am experimenting with self-documenting code, just to give a couple of examples. There are many uses for this technique, limited only by your requirements and imagination.

devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists