How to determine if all objects are serializable in a given namespace?

Some background: we require all our DTO objects to be serializable so that they can be stored in the session or cached.

As you can imagine, this is very annoying and error prone ... is there any automated way (ideally as part of the build process) using Visual Studio 2010 to ensure that all classes in the namespace are marked with [Serializable]?

+3
serialization build-process
Jul 15 '10 at 15:16
source share
2 answers

You cannot find all the possible classes in the namespace, but you can find all the classes in this assembly that have the specified namespace and check them.

string dtoNamespace = ...; Assembly assembly = ...; var badClasses = assembly.GetTypes() .Where(t => t.Namespace == dtoNamespace) .Where(t => t.IsPublic) // You might want this .Where(t => !t.IsDefined(typeof(SerializableAttribute), false); 

Make sure badClasses empty in any way :)

EDIT: As mentioned in the comments, the IsSerializable property is useful here :)

+4
Jul 15 '10 at 15:21
source share

One tool you might think of that integrates seamlessly into your build is NDepend . This allows you to run various code metrics that you can then use to warn / fail builds.

In CQL (the built-in query language in NDepend) you should write something like:

 WARN IF Count > 0 IN SELECT TYPES FROM NAMESPACES "namespace" WHERE !IsSerializable 

Obviously, this will only find namespaces for the types that are included in the assemblies in your solution, but I assume that you mean it.

NDepend can start automatically as part of your build in VS or on a separate build server. It can also be run as a standalone application.

+5
Jul 15 2018-10-15T00:
source share



All Articles