Question

My application has the following classes:

public class Widget {        
    public virtual int Id { get; set; }
    public virtual WidgetType Type { get; set; }
    public virtual string Parameters { get; set; }
}

public class WidgetType {        
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string ParametersAssembly { get; set; }
    public virtual string ParametersClass { get; set; }
}

Now if i'd like to update the Parameters for a particular widget i would say something like:

// Get the widget
var widget = GetWidget(1);

// Create an instance of the type parameters class
var parameters = Activator.CreateInstance(Assembly.LoadFrom(Server.MapPath("~/bin/"
    + widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass));

... Code here to update the parameters

widget.Parameters = new XmlSerializer(parameters.GetType()).Serialize(parameters);

I have to do the reverse when i wish to get the parameters. You can imagine this becomes quite tedious. I was wondering if it was possibly to automatically do this?

I've been looking at the IUserType interface. I found an article which is kind of similar. However my problem is a little more complicated as my type changes based on the type of the widget.

I'd appreciate it if someone could let me know if this is possible and possibly how it could be achieved. Thanks

Was it helpful?

Solution

an easy way

public class Widget
{
    public virtual int Id { get; set; }
    public virtual WidgetType Type { get; set; }

    private string _serializedParameters;
    private virtual string SerializedParameters {
        get
        {
            return new XmlSerializer(Parameters.GetType()).Serialize(Parameters);
        }
        set
        {
            _serializedParameters = value;
            // code to deserialize the Parameters and set to Parameters
            var ptype = Assembly.LoadFrom(Server.MapPath("~/bin/" + widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass);
            Parameters = Activator.CreateInstance(ptype);
        }
    }
    private object _parameters;
    public virtual object Parameters
    {
        get
        {
            if (_parameters == null)
                _parameters = Activator.CreateInstance(Assembly.LoadFrom(Server.MapPath("~/bin/" + widget.Type.ParametersAssembly + ".dll")).GetType(widget.Type.ParametersClass));
            return _parameters;
        }
        set { _parameters = value; }
    }
}

it can't be in the Parameters property because then you have to get -> alter -> set instead of get -> alter. But you are right that building the parameters object should go in the getter of Parameters because only there we can be sure to have the WidgetType loaded

it is essentially the same as a UserType except that we know that WidgetType is there

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top