Menu

#10 Populate Fields on controllers

open
None
5
2005-02-09
2005-01-01
No

Currently, only properties get populated with values
from Request.Params. The following changes allow
population of public fields:

Util\PropertyPopulator.cs:58
if (property!=null)
{
SetValue(target, property, val);
}
else
{
FieldInfo field = members[0] as FieldInfo;
SetValue(target, field, val);
}

Util\PropertyPopulator.cs:113
/// <summary>
/// Sets the value of a field in the object target to
the value val.
/// </summary>
/// <param name="target">The instance to set the
field on.</param>
/// <param name="property">The field to
set.</param>
/// <param name="val">The new value for the
property.</param>
protected void SetValue(object target, FieldInfo
field, object val)
{
if (val.GetType().IsPrimitive)
{
//not sure why this is necessary
but it seems to be.
//if the type of the property is an
sbyte and val is an int
//an exception is thrown--hence
the catch.
try
{
field.SetValue(target,
val);
return;
}
catch (Exception)
{
val = val.ToString();
}
}

if (typeof(string).IsInstanceOfType(val))
{
string sval = val as string;
Type ptype = field.FieldType;
val = ParseValue(sval, ptype);
field.SetValue(target, val);
}
else
{
//just try and set it--maybe a
cast will work,
//otherwise an exception will be
thrown
field.SetValue(target, val);
}
}

It would be nice to see this get included into the
code.

Regards, Alexander Gräf

Discussion

  • Cort Schaefer

    Cort Schaefer - 2005-02-09

    Logged In: YES
    user_id=541173

    Is this really a good idea? It is not generally considered
    good OO design to expose public fields.

     
  • Cort Schaefer

    Cort Schaefer - 2005-02-09
    • assigned_to: nobody --> corts
     
  • Alexander Graef

    Alexander Graef - 2005-02-09

    Logged In: YES
    user_id=1030440

    The only thing I can think of would be the security
    vulnerability because public properties could be overwritten
    by accident.

    What about making it an option, that defaults to false to
    avoid breaking existing implementations? People should
    decide, theirself what is good OOP design in every case
    where it is used.

    Regards, Alex

     

Log in to post a comment.