Friday, May 3, 2013
Using Custom Attributes and Reflecting on it
I found myself using a Custom attribute in C# to implement a task assigned to me while supporting an online ordering business application. The line of business had so far received only CSV files from its customers to generate Purchase Order documents after parsing them and running them through some business rules. Once the Purchase Orders are set up with the rules specific to the Customer(and generic rules too), the Customer could order as many Purchase Orders as they liked through the Online Ordering ASP.NET web application.
One of the customers informed that they can only send XML files to create the Purchase Orders and not in the CSV format. So we set out to use the XML file from the customer and convert it to CSV, so the business can feed the POs to the normal Order processing pipeline.
The task was broken down into 3 steps.
1) Using the XML document, create an XSD file to be used for validation and generating C# Class objects.
2) Use the .NET xsd.exe tool to generate the C# classes and deserialize the XML data into .NET objects.
3) Once the XML data is deserialized to the C# objects, serialize them to CSV files
Certain rules would govern how the XML data is converted to CSV.
1) There would be key fields comprising some XML elements in a particular sequence, specifically, the PO, SKU and Sizes.
2) Each unique value for the keys should create a line item ( row) in the csv file
3) All the fields in the csv file created should naturally follow a correct sequencing
To get the field positions for each property in the generated C# class, I decided to use custom attributes to add some meta-data to the properties, that I can query against later to serialize the data to the csv file using the desired field positions.
Now there are essentially 3 steps to creating custom attributes.
1. Declare an attribute - derives from System.Attribute and marked with AttributeUsage attribute.
2. Associate the attribute with a progarm element ( another class, property or method).
3. Access the attribute through Reflection to query its existence and value for any meaningful use of the attribute.
By itself decorating a class or method etc by an attribute does nothing other than adding some metadata.
In other words, you have write code using Reflection to query the attributes at runtime and use them for whatever purpose it was designed for.
You can use the GetCustomeAttributes method of the System.Reflection.MemberInfo class to query the attributes that are decorated to a class as a whole. If the attribute is decorated to a property or properties, you can use the GetCustomAttributes of the System.Reflection.PropertyInfo class. Likewise the MethodInfo class to get the custom attributes on the method level.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment