Tuesday, November 30, 2010

Disable XML Comment warning in Workflow auto-generated code in .NET Framework 4.0

In order to make sure our code is proper documented, it's a good practice to check the "XML documentation file" setting in the project's Build tab (with that setting turned on, all public, internal, protected classes, methods, properties inside the project are required to have XML Comment put in place) and turn on the "Treat Warning as Error" in the project. With this, it will force the developers to have their code commented properly at the early stage once it is introduced which in turns will help to reduce the maintenance effort in the later phase. Everything should be working fine until you need to work with the Workflow Activity in .NET Framework 4.0.

Normally, in auto-generated code (code generated by .NET Framework), proper warning disable statement is added inside the generated code to by pass the warnings. Unfortunately, there is an issue with the auto-generated code with the Workflow Activity in .NET Framework 4.0. The proper warning disable statement is not put in place. Hence, it causes the build to fail due to setting the option "Treat Warning as Error". It's even unfortunate to figure out that nothing you can interfere in the generated code (code inside the *.g.cs files) since those are created during the compilation phase. You will not see those code in your project and, therefore, you will not be able to manually enter the pragma disable statement into the code even if you want to go with this hideous way.

Fortunately, the feature "AfterTargets" introduced in MSBuild 4.0 comes to rescue. Delving into the investigation, it shows that the Workflow Activity auto-generated code (*.gs.c files) are created inside the build target "XamlMarkupCompilePass1". By leveraging the "AfterTargets", we can inject our code to disable those XML Comment warnings caused inside the generated code with the following target in the project file
  <Target Name="XamlGeneratedCodeWarningRemoved" AfterTargets="XamlMarkupCompilePass1">
    <Exec Command="for %%f in (@(XamlGeneratedCodeFiles)) do echo #pragma warning disable > %%f.temp" />
    <Exec Command="for %%f in (@(XamlGeneratedCodeFiles)) do type %%f >> %%f.temp" />
    <Exec Command="for %%f in (@(XamlGeneratedCodeFiles)) do copy /y %%f.temp %%f" />
    <Message Text="XamlGeneratedCodeWarningRemoved: @(XamlGeneratedCodeFiles)" />
  </Target>

The job of the above target is to insert the "#pragma warning disable" statement into the auto-generated code to by pass the XML Comment warnings (as well as other warnings in those generated code).

So, that's it. Problem solved!