As my forever quest for simple & reusable code keeps growing, I stumble across some bottlenecks once in a while.
Anyway, I have a simple class that is called "PopulateObjectFromFormRequest" and as descriptive as the name is, it does one simple yet helpful task. Given an object as a generic type I.e (user) and a web form as a parameter I.e (aspnetform), it will scan through all the controls of that web form and use reflection on the object and assign values to the object properties that matches controls from within the form.
How does this help me? Well if I my web page that has a registration form and I have a class or struct that needs to be populated with that data, I simply use that class. It prevents me from writing code that fills up an object with data from the web. Therefore, one less task to complete and 5000 less lines of code to write.
What's the problem now? Well, for starters, since I use reflection to determine the type, if the object properties is a nullable type, reflection.GetType() does not equate to typeof(Int32). Therefore, I need to determine if the type of what I'm reflecting is a generic type and nullable, and if it is, I need to drill further down to find the underlying type.
Using SubSonic or DatabaseFly, the datatype for a database column that is of a DateTime and Nullable is DateTime? - whoops, my cool class will fail to determine and assign to the appropriate property or field. Alright, straight to some code and enough talking.
#region [ TestUnderlyingTypes ]
internal class NullWeAre
{
// Create a direct none nullable type variable
public DateTime TodaysDate;
// Create a nullable type variable
public DateTime? DateOfBirth;
// Create another nullable type
public Int32? MyAge;
// Oh, what the heck, through in a string
public string Name = "Rydal Williams";
}
/// <summary>
/// Method: TestUnderlyingTypes
/// </summary>
public static void TestUnderlyingTypes()
{
// Test class
NullWeAre nwa = new NullWeAre();
// Ok, now lets see how we can get the underlying type
// Lets perform some reflection on our test class
//************************************************************************
System.Reflection.FieldInfo[] fieldsInfos = typeof(NullWeAre).GetFields();
foreach (System.Reflection.FieldInfo fi in fieldsInfos)
{
if (fi.FieldType.IsGenericType
&& fi.FieldType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
// We are dealing with a generic type that is nullable
Console.WriteLine("Name: {0}, Type: {1}", fi.Name, Nullable.GetUnderlyingType(fi.FieldType));
}
else
{
// Ok, its just one of those basic data types
Console.WriteLine("Name: {0}, Type: {1}", fi.Name, fi.FieldType);
}
}
}
#endregion