Custom rules not running

May 23, 2012 at 6:08 PM

Hi,

 

I'm trying to write some custom rules for StyleCop, and am having problems getting the code to do anything.  Some details:

1. Here's the code in full:


namespace StyleCop
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    [SourceAnalyzer(typeof(StyleCop.CSharp.CsParser))]
    public class UnusedCodeAnalyzer : SourceAnalyzer
    {
        public override void AnalyzeDocument(CodeDocument document)
        {
            this.AddViolation(
                document.DocumentContents,
                "MY1000",
                "Ouch!");
        }
    }
}

2. The metadata is in a file called UnusedCodeAnalyzer.xml in the root folder of the project. The build action is set to Embedded Resource, copy to output directory is set to Do Not Copy. The metadata is literally exactly the example given in the SDK docs, starting as follows:

<SourceAnalyzer Name="My Custom Rules">
  <Description>
    Custom rules enforcing blah blah blah.

(And so on).

3. I compile in Visual C# 2010 Express, and copy only the DLL (called StyleCopUnusedCode.dll) to the StyleCop directory. Permissions are set to Everyone having Full Control.

4. I then start a new instance of VSEand open a new project which has StyleCop enabled. I rebuild the project. StyleCop produces plenty of warnings (so I know StyleCop is actually running), but none of them are MY1000.

5. The version of StyleCop being used is 4.7.11.0 (that's the version listed in the properties of StyleCop.dll).

 

Any suggestions would be gratefully received!

 

Thanks in advance,

 

Chris Owens.

May 27, 2012 at 1:11 AM

1. First make sure your project is .NET 3.5.

2. Your xml file name needs to be the same as your class name and in the same directory. Its very odd that these need to match but thats how stylecop hooks them up apparently.

May 27, 2012 at 9:29 AM

Fixed: it was because it was a .Net 4.0 project, it appears.

Thanks very much indeed for the help!

 

Chris Owens.

May 28, 2012 at 4:31 AM

I've tried the same and still don't see the custom rules show up in the rules settings. Are there any other specifications that need to be followed?

May 28, 2012 at 10:48 AM

Hi Chrono,

Just to confirm that, now that my code works, the rules do indeed show up in the rule settings so that they can be enabled / disabled (i.e. it seems that if the rules are actually executed by StyleCop, they will show up in the rule settings).

Do you have any more details of your problem?

One thing to note: if the class of the source analyzer is Fred, in namespace Jane, the xml file should be called Fred.xml (the namespace shouldn't be in the filename). It's also easy to overlook setting the Build Action to Embedded Resource (NOT Resource).

Chris. 

May 28, 2012 at 11:07 PM

Chris,

One thing I'm totally unclear about. Should the XML be outside of the assembly or included in the assembly?

Thanks!