Reputation: 40245
I was wondering if anyone knows of a quick way or if anyone has written a reflection tool to tell which objects in a solution are not marked as serializable. I'm switching a site over to a StateServer and i need to have all objects marked as serializable. I don't want to miss any.
Also, second part do enums have to be serializable?
The website is an ASP.NET 1.1 site built with VS 2003
Upvotes: 2
Views: 1536
Reputation: 27127
Enums are inherently serialisable.
I wrote this helper for getting attributes off objects, you could add a line to the top of your application that calls the following code:
var assemblies = GetTheAssembliesFromYourApp();
foreach (var assembly in assemblies)
{
var types = assembly.GetTypes ();
foreach (var type in types)
{
if (AttributeHelper.GetAttrbiute<Serializable> (type) == null)
{
// Log somewhere - this type isn't serialisable...
}
}
}
static class AttributeHelper
{
#region Static public methods
#region GetAttribute
static public T GetAttribute<T> (object obj)
where T : Attribute
{
if (obj == null)
throw new ArgumentNullException ("obj");
// If the object is a member info then we can use it, otherwise it's an instance of 'something' so get it's type...
var member = (obj is System.Reflection.MemberInfo) ? (System.Reflection.MemberInfo)obj : obj.GetType ();
return GetAttributeImpl<T> (member);
}
#endregion GetAttribute
#endregion Static public methods
#region Static methods
#region GetAttributeImpl
static T GetAttributeImpl<T> (System.Reflection.MemberInfo member)
where T : Attribute
{
var attribs = member.GetCustomAttributes (typeof (T), false);
if (attribs == null || attribs.Length == 0)
return null;
return attribs[0] as T;
}
#endregion GetAttributeImpl
#endregion Static methods
}
Upvotes: 2
Reputation: 140923
Enum require to be serializable.
To find out what is not serializable, I do have unit test to these object that simply call a method to know if it's serializable. This method try to serialize, if fail, the object is not...
public static Stream serialize<T>(T objectToSerialize)
{
MemoryStream mem = new MemoryStream();
BinaryFormatter b = new BinaryFormatter();
b.Serialize(mem, objectToSerialize);
return mem;
}
In you unittest you need to call serialize(objectToCheck); if not serizlisable, an exception will raise.
Upvotes: 2