This morning I started on what I thought would be a quick exercise to use custom field attributes. Having tried a lot of things and looking for a lot of examples (most of which are associated with class attributes, not with a field), I am officially stuck.
My code is below. One feature is that the class is built in FileHelpers using the class. My various partially successful attempts managed to get field names from this class, so I believe that part works fine.
What I want to do (for a comment in the code): a) Run through the fields, b) for each, see if the DBDataTypeAttribute attribute exists, and c) It seems the hardest part is getting the values from the attribute (FieldType String and AllowNulls bool).
Any comments appreciated!
Mark
class Program
{
static void Main(string[] args)
{
// Desired output:
System.Type userType = null;
userType = ClassBuilder.ClassFromString(@"
public class ExpenseReport
{
[FieldQuoted('""', QuoteMode.OptionalForRead, MultilineMode.AllowForRead)]
[DBDataTypeAttribute(FieldType = ""varchar(1000)"", AllowNulls = true)]
public String UniqueID;
[FieldQuoted('""', QuoteMode.OptionalForRead, MultilineMode.AllowForRead)]
public String ERNum;
}");
object[] attributes;
attributes = userType.GetCustomAttributes(typeof(DBDataTypeAttribute), true);
foreach (Object attribute in attributes)
{
// Would like to be able to ID for each field whether the DBDataTypeAttribute is present, and get the FieldType and AllowNulls Values
DBDataTypeAttribute a = (DBDataTypeAttribute)attribute;
Console.WriteLine("Attribute: ", a.FieldType);
Console.ReadLine();
}
}
}
[AttributeUsage(AttributeTargets.Field)]
public class DBDataTypeAttribute : System.Attribute
{
private string fieldtype;
public string FieldType
{
get { return fieldtype; }
}
private string allownulls;
public string AllowNulls
{
get { return allownulls; }
}
}
source
share