Extracting Attributes Using Reflection
You can discover and respond to attribute information programmatically using reflection. Chapter 6, "Reflection," provides an example demonstrating how to use reflection to extract attributes programmatically. Many of the reflection capabilities for managing attributes are also covered in Chapter 6. In this section I have included a brief example that demonstrates how to extract the URN associated with entities that use the HelpAttribute introduced earlier in this chapter.
Suppose you elected to extract Help attributes programmatically to facilitate displaying help information from a central repository. You could write generic code that read HelpAttribute URNs on demand and displayed the content referenced by the URN. Listing 12.10 demonstrates how to use reflection to extract the URN and Topic infor-mation programmatically.
Listing 12.10 Using reflection to extract attribute information
1: Private Overloads Sub DisplayAttribute(ByVal Obj As Object) 2: Dim TypeInfo As Type = Obj.GetType 3: Dim Attributes() As Object = _ 4: TypeInfo.GetCustomAttributes(GetType(HelpAttribute), False) 5: 6: If (Attributes.Length > 0) Then 7: Dim Help As HelpAttribute = _ 8: CType(Attributes(0), HelpAttribute) 9: DisplayContent(Help.Urn) 10: End If 11: End Sub 12: 13: Private Sub DisplayContent(ByVal URN As String) 14: AxWebBrowser1.Navigate2(URN) 15: End Sub
The code is an excerpt from HelpAttributeDemo.sln located on this book's Web site. The code is written to take a generic Object as a parameter to the DisplayAttribute method. DisplayAttribute retrieves type information for the Obj on line 2. From the TypeInfo object we are able to retrieve an array of attributes by calling GetCustomAttribute. Because this code was written to extract only HelpAttribute information, the type of attribute is expressed literally on line 4. If there are any attributesline 6the first generic attribute object returned by the GetCustomAttributes is typecast to a HelpAttribute object. When we have a HelpAttribute object, we can access the Urn property. (The example employs the Internet Explorer ActiveX control defined in the shdocvw.dll. Yes, this is a COM control.)
The two methods extract a URN added using a custom attribute and navigate to a Web document in 15 lines of code. Assuming that the application is on a LAN, the user is connected to the Internet, or the Help content ships with your application, you could use this technique to integrate help content into code that is not made up of components , just as VS .NET does. Tools like RoboHelp make it very easy to create rich HTML help content, but you could use a word processor such as Word or WordPerfect, or an HTML editing program such as FrontPage or Dreamweaver.