<p>Following on from my recent question on <a href="https://stackoverflow.com/questions/17725/large-complex-objects-as-a-web-service-result">Large, Complex Objects as a Web Service Result</a>. I have been thinking about how I can ensure all future child classes are serializable to XML.</p>
<p>Now, obviously I could implement the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx" rel="noreferrer">IXmlSerializable</a> interface and then chuck a reader/writer to it but I would like to avoid that since it then means I need to instantiate a reader/writer whenever I want to do it, and 99.99% of the time I am going to be working with a <em>string</em> so I may just write my own.</p>
<p>However, to serialize to XML, I am simply decorating the class and its members with the <em>Xml???</em> attributes ( <em>XmlRoot</em> , <em>XmlElement</em> etc.) and then passing it to the <em>XmlSerializer</em> and a <em>StringWriter</em> to get the string. Which is all good. I intend to put the method to return the string into a generic utility method so I don't need to worry about type etc.</p>
<p>The this that concerns me is this: If I do not decorate the class(es) with the required attributes an error is not thrown until run time.</p>
<p><strong>Is there any way to enforce attribute decoration? Can this be done with FxCop?</strong> (I have not used FxCop yet)</p>
<h3>UPDATE:</h3>
<p>Sorry for the delay in getting this close off guys, lots to do!</p>
<p>Definitely like the idea of using reflection to do it in a test case rather than resorting to FxCop (like to keep everything together).. <a href="https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods#19455">Fredrik Kalseth's answer</a> was fantastic, thanks for including the code as it probably would have taken me a bit of digging to figure out how to do it myself!</p>
<p>+1 to the other guys for similar suggestions :)</p>

[{'answer_id': 19455, 'author': 'Fredrik Kalseth', 'author_id': 1710, 'author_profile': 'https://Stackoverflow.com/users/1710', 'pm_score': 5, 'selected': True, 'text': '<p>I\'d write a unit/integration test that verifies that any class matching some given criteria (ie subclassing X) is decorated appropriately. If you set up your build to run with tests, you can have the build fail when this test fails.</p>\n\n<p>UPDATE: You said, "Looks like I will just have to roll my sleeves up and make sure that the unit tests are collectively maintained" - you don\'t have to. Just write a general test class that uses reflection to find all classes that needs to be asserted. Something like this:</p>\n\n<pre><code>[TestClass]\npublic class When_type_inherits_MyObject\n{\n    private readonly List&lt;Type&gt; _types = new List&lt;Type&gt;();\n\n    public When_type_inherits_MyObject()\n    {\n        // lets find all types that inherit from MyObject, directly or indirectly\n        foreach(Type type in typeof(MyObject).Assembly.GetTypes())\n        {\n            if(type.IsClass &amp;&amp; typeof(MyObject).IsAssignableFrom(type))\n            {\n                _types.Add(type);\n            }\n        }\n    }\n\n    [TestMethod]\n    public void Properties_have_XmlElement_attribute\n    {\n        foreach(Type type in _types)\n        {\n            foreach(PropertyInfo property in type.GetProperties())\n            {\n                object[] attribs = property.GetCustomAttributes(typeof(XmlElementAttribute), false);\n                Assert.IsTrue(attribs.Count &gt; 0, "Missing XmlElementAttribute on property " + property.Name + " in type " + type.FullName);\n            }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 19473, 'author': 'samjudson', 'author_id': 1908, 'author_profile': 'https://Stackoverflow.com/users/1908', 'pm_score': 1, 'selected': False, 'text': "<p>You can write unit tests to check for this kind of thing - it basically uses reflection.</p>\n\n<p>Given the fact this is possible I guess it would also be possible to write a FxCop rule, but I've never done such a thing.</p>\n"}, {'answer_id': 19570, 'author': 'Mark Cidade', 'author_id': 1659, 'author_profile': 'https://Stackoverflow.com/users/1659', 'pm_score': 1, 'selected': False, 'text': "<p>You can write an FxCop rule or even check for the attributes by calling GetType() in the base class's constructor and reflecting over the returned type.</p>\n"}, {'answer_id': 169087, 'author': 'Larry Silverman', 'author_id': 7752, 'author_profile': 'https://Stackoverflow.com/users/7752', 'pm_score': 0, 'selected': False, 'text': "<p>A good FXCop rule (and one which I am finding I need right now) would be to check that all objects that are being added to the ASP.NET Session have the Serializable attribute.  I'm trying to move from InProc session state to SQL Server.  First time I requested a page, my site blew up on me because non-serializable objects were being stored in Session.  Then came the task of hunting through all the source code looking for every instance where an object is set in the Session...  FXCop would be a nice solution.  Something to work on...</p>\n"}, {'answer_id': 617732, 'author': 'Professional Sounding Name', 'author_id': 70160, 'author_profile': 'https://Stackoverflow.com/users/70160', 'pm_score': 0, 'selected': False, 'text': '<p>You can also use this concept/post-processor to enforce relationships between attributes and use similar login to enforce relationships between classes and attributes at compile time:</p>\n\n<p><a href="http://www.st.informatik.tu-darmstadt.de/database/publications/data/cepa-mezini-gpce04.pdf?id=92" rel="nofollow noreferrer">http://www.st.informatik.tu-darmstadt.de/database/publications/data/cepa-mezini-gpce04.pdf?id=92</a></p>\n'}]
['https://Stackoverflow.com/questions/19454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/832/']