Daniel Fisher (lennybacon.com)

SOA, DATA & THE WEB

BusinessObjects: filling "this" and classes or structs optionally as single object or object collection

That was in short what was on my requirement list.
I had a few difficulties solving the problem of filling "this" and classes that fill them self in the constructor, but i finally figured it out.


public void Fill(ref object[] objCollection ...)
{
    ...
    System.Type type = objCollection[0].GetType();
    ArrayList arr = new ArrayList();
    ...
    object baseObject;

    // struct or struct[]
    if(type.IsValueType) 
    {
        baseObject = type.Assembly.CreateInstance(type.FullName);
    }
    // this or non serializable class
    else if(arr.Count==0)
    {
        baseObject = objCollection[0];
    }
    // class or class[]
    else if(type.IsSerializable) 
    {
        Stream _stream;
        BinaryFormatter _formatter = new BinaryFormatter();
        try
        {
            _stream = File.Open("Empdata.bin",
             FileMode.Create, FileAccess.Write);
            _formatter.Serialize(_stream, objCollection[0]);
            _stream.Close();

             _stream = File.Open("Empdata.bin",
              FileMode.Open, FileAccess.Read);
             object _desObj = _formatter.Deserialize(_stream);
             baseObject = Convert.ChangeType(_desObj, type);
             _stream.Close();
        }
        catch(Exception e)
        {
            throw new Exception(type.ToString() +
             " could not be serialized.", e);
        }
    }
    else
    {
        throw new NotImplementedException(type.ToString() +
         " is no value type and don't implements the" +
         "ISerializable interface.");
    }
    ...
    arr.Add(baseObject);
    ...
}

Comments

Write a comment