Friday, April 29, 2011

How to add #pragma warning disable 1591 using CodeDom

A portion of our app uses code generated using CodeDom. This code does not need Xml Comments and so we would like to add a

#pragma warning disable 1591

to those generated files. Is this possible with CodeDom and if not, then are there other suggestions on how to accomplish this?

From stackoverflow
  • Looking through all the reflector code, nothing pops up as the "right" way. However, there might be a way if you are willing to do some post-generation processing. Using the RegionDirective, place a special token in the RegionText value. Then, once your code is generated, go back and do a string replace.

    Since I didn't see anything in the code that enforces matching code regions, you could have a single start code region at the end to enable warnings again.

    For example. your tokens could be "#PRAGMA1591" and "#ENABLEWARNINGS." Therefore, after the code is generated you would have

    #region #PRAGMA1591
    
    ...
    
    #region #WARNINGRESTORE
    #endregion
    

    You would then do a string replace to yield this:

    #region Disable Warning 1591
    #pragma warning disable 1591
    
    ...
    
    #pragma warning restore
    #endregion
    

    Your strings expand like this:

    • #PRAGMA1591 -> Ignore Lack of XML Documentation \n #pragma warning disable 1591
    • #region #WARNINGSRESTORE -> #pragma warning restore
  • provider.GenerateCodeFromCompileUnit(
        new CodeSnippetCompileUnit("#pragma warning disable 1591"),
        sourceWriter, options);
    provider.GenerateCodeFromCompileUnit(targetUnit, sourceWriter, options);
    provider.GenerateCodeFromCompileUnit(
        new CodeSnippetCompileUnit("#pragma warning restore 1591"),
        sourceWriter, options);
    

    Doesn't translate well (at all) to other languages. YMMV -Ian

0 comments:

Post a Comment