Random thoughts of wisdom - the personal blog of Michael Holm Andersen

ASP.NET Viewstate Viewer add-on

If you’re a ASP.NET (WebForm) web developer and you worry about Viewstate (which you should!) – you might find this Firefox add-on very useful:

The add-on displays the viewstate of the current ASP.NET page in the statusbar – very handy when trying to limit the Viewstate size.

Clean copy of LinqToSQL Entity object

Often you need to make a copy of a LinqToSQL (Entity) Object with all the values intact. For some reason the .NET framework does not have a method for this.

However the below code will make a “clean copy” of a LinqToSQL object.

// Instanciate new object and copy all properties from old Bill ("clean" copy)
Bill billNew = (Bill)Entity.Copy(billOld, new Bill());

And the method actually doing the work, looks like this:

public static class Entity
    /// <summary>
    /// Copies an LinqToSQL entity object ("clean" copy)
    /// </summary>
    /// <param name="source">Source Entity object</param>
    /// <param name="destination">Destination Entity object</param>
    /// <returns>Destination Entity object with all properties copied from Source object</returns>
    public static object Copy(object source, object destination)
        System.Reflection.PropertyInfo[] sourceProps = source.GetType().GetProperties();
        System.Reflection.PropertyInfo[] destinationProps = destination.GetType().GetProperties();
        foreach (System.Reflection.PropertyInfo sourceProp in sourceProps)
            ColumnAttribute column = Attribute.GetCustomAttribute(sourceProp, typeof(ColumnAttribute)) as ColumnAttribute;
            if (column != null && !column.IsPrimaryKey)
                foreach (System.Reflection.PropertyInfo destinationProp in destinationProps)
                    if (sourceProp.Name == destinationProp.Name && destinationProp.CanWrite)
                        destinationProp.SetValue(destination, sourceProp.GetValue(source, null), null);
        return destination;