How to Suppress Code Analysis in Template-Generated Code

by Larry Spencer Wednesday, June 1, 2011 10:52 AM

When using the Entity Framework or other template-based code generators, Code Analysis will emit many spurious warning messages like these:

  • CA1033 : Microsoft.Design : Make '...' sealed (a breaking change if this class has previously shipped), implement the method non-explicitly, or implement a new method that exposes the functionality of 'INotifyPropertyChanged.PropertyChanged.add(PropertyChangedEventHandler)' and is visible to derived classes.
  • CA1819 : Microsoft.Performance : Change ...' to return a collection or make it a method.
  • CA2238 : Microsoft.Usage : Because ...' is marked with OnSerializing, OnSerialized, OnDeserializing, or OnDeserialized, change its accessibility to private.
  • ...and others

To avoid those messages, you must do two things:

  1. Tell Visual Studio not to run Code Analysis on generated code.
  2. Decorate the generated classes with the GeneratedCode attribute.

 

Avoiding Code Analysis on Generated Code

 

This step may not be necessary, as it just selects the default behavior.

  1. In Visual Studio 2010, go to the Properties page for your project.
  2. Select the Code Analysis tab.
  3. Make sure the Suppress results from generated code box is checked.

 

Adding the GeneratedCode Attribute

 

Since the code that needs this attribute is generated (duh), you don’t want to modify it directly. Instead, you’ll have to modify the template.

Open the .TT file and add the attribute in the relevant places.  For example, if you’re working with the Entity Framework, search for all occurrences of class and enum. In the line that precedes each of those, add the attribute, as shown here.

[global::System.CodeDom.Compiler.GeneratedCode("Visual Studio 2010 EDMX Tool", "10.0")]
<#=Accessibility.ForType(complex)#> partial class <#=code.Escape(complex)#> : INotifyComplexPropertyChanging, INotifyPropertyChanged
[global::System.CodeDom.Compiler.GeneratedCode("Visual Studio 2010 EDMX Tool", "10.0")]
public enum ObjectState

When you save the template, your classes will be regenerated. Check them if you wish to make sure the GeneratedCode attribute is present.

Next time you build your project, the Code Analysis warnings should not appear.  You'll get the benefits of Code Analysis on the code you wrote without being swamped with warnings for code that you did not write.

Tags: , ,

All

About the Author

Larry Spencer

Larry Spencer develops software with the Microsoft .NET Framework for ScerIS, a document-management company in Sudbury, MA.