Technology with opinion

Tuesday, November 25, 2008

Creating Custom StyleCop Rules in C#

Microsoft has released a new free static code analysis tool called StyleCop.  Named after the similar FxCop, this product is aimed to be more focused for cosmetic code consistency which can increase readability and maintainability.  StyleCop has built-in rules, which you can turn off, many of which are:
  • Ordering of members in a class from most visible to least visible
  • Order of Usings in alphabetical order, with System namespaces on top
  • Proper camel casing and pascal casing
  • Proper whitespace
I like about 3/4 of these rules so I think it's definitely worth considering using, even consider integrating into your automated build process using NAnt, CruiseControl or TFS.  That being said many will likely want to extend these rules to create your own.  Doing so is fairly simple but not documented very well at this time.  I created the following rule to make sure that all instance variables (private & protected class level variables) are prefixed with an underscore.  I realize not everybody follows this convention, but I like it because it's more concise than prefixing your instance variables with 'm_' or 'this' which is often needed to prevent name collisions.

First I created a C# Class assembly project and referenced "Microsoft.StyleCop" and "Microsoft.StyleCop.CSharp".  Next I added the following class, which implements my custom rule:

using Microsoft.StyleCop;
using Microsoft.StyleCop.CSharp;

namespace DotNetExtensions.StyleCop.Rules
{
    /// <summary>
    /// This StyleCop Rule makes sure that instance variables are prefixed with an underscore.
    /// </summary>
    [SourceAnalyzer(typeof(CsParser))]
    public class InstanceVariablesUnderscorePrefix : SourceAnalyzer
    {
        
        public override void AnalyzeDocument(CodeDocument document)
        {
            CsDocument csdocument  = (CsDocument) document;
            if (csdocument.RootElement != null && !csdocument.RootElement.Generated)
                csdocument.WalkDocument(new CodeWalkerElementVisitor<object>(this.VisitElement), null, null);
        }

        private bool VisitElement(CsElement element, CsElement parentElement, object context)
        {
            // Flag a violation if the instance variables are not prefixed with an underscore.
            if (!element.Generated && element.ElementType == ElementType.Field && element.ActualAccess != AccessModifierType.Public && 
                element.ActualAccess != AccessModifierType.Internal && element.Declaration.Name.ToCharArray()[0] != '_')
            {
                AddViolation(element, "InstanceVariablesUnderscorePrefix");
            }
            return true;
        }
    }
}

The VisitElement function handles the main logic for this rule.  First it makes sure that the member isn't Generated code, which you have no control over so no sense in applying rules to.  Secondly it's making sure that the member's visibility isn't Public or Internal.  Finally we make sure that the instance variable starts with an underscore prefix..

Next we need to provide metadata so that StyleCop can categorize and describe our rule.  Add an XML file to your project, then change it's Build Action to 'Embedded Resource'

<?xml version="1.0" encoding="utf-8" ?>
<SourceAnalyzer Name="Extensions">
  <Description>
    These custom rules provide extensions to the ones provided with StyleCop.
  </Description>
  <Rules>
    <Rule Name="InstanceVariablesUnderscorePrefix" CheckId="EX1001">
      <Context>Instance variables should be prefixed by underscore.</Context>
      <Description>Instance variables are easier to distinguish when prefixed with an underscore.</Description>
    </Rule>
  </Rules>
</SourceAnalyzer>

At the root level you are naming the main category for the rules in this file.  Next you describe your suite of rules.  Then in the Rules section you can add all the rules (note: you can use RuleGroup element to further categorize your rules).  Finally you name your rule and give it a unique CheckId.  The CheckId is what you can search for your rule by in the StyleCop Project Settings.  Important: for StyleCop to correlate your class to your metadata your class and xml file need to be named exactly the same.

Finally build your project and drop your new assembly's dll into the StyleCop directory (C:\Program Files\Microsoft StyleCop 4.3).  Now double-click your Settings.StyleCop to see your rule in the list.  It should look something like the following:



Now you can open your solutions/projects in Visual Studio and click Tools -> Run StyleCop and you should see warnings for your new rule.

StyleCop is a nice little accent to any C# project.  I'd like to see Microsoft make the following changes:
  • StyleCop should be OSS (open source software) - why not Microsoft, there really can't be any proprietary business technology in an application that is basically is performing string  parsing
  • StyleCop's documentation needs to be improved - Microsoft provides to help documents for StyleCop, a user manual and an SDK manual.  Both of them lack details and some of the examples simply do not even compile.  For instance the CodeWalkerElementVisitor delegate in a boolean, in their samples they do not even return a boolean value which will not allow their samples to compile.  They do not even document the purpose of this boolean.  Through trial and error I think that if you return a false that it will stop walking (parsing) the document for this rule.
  • Custom rules should be able to be categorized within the existing main ones: Naming Rules, Ordering Rules, etc.
  • Easier to create custom rules by using regex within an XML file.  This would eliminate having to create custom assemblies and classes.
  • Command-line interface should be available for testing or scripting purposes.

43 comments:

Walker said...

I need the rule to you implement for using underscore prefix for private or protected instance level variables for SyleCop.

More thanks for help me.

My email es: walkeraguilar@gmail.com

Anonymous said...

Many institutions limit access to their online information. Making this information available will be an asset to all.
Custom Paper Writing

Unknown said...

Hi,

I have a problem.

When I open the settings file via visual studio (right-click a project and click StyleCop Settings) my custom rules appear. All good there. However if I open the same file by double-clicking it in windows explorer my custom rules don't show up. Any idea why?

Thanks
Neil

Sharepoint said...

In your Article there is mentioned that "Proper camel casing and pascal casing" in build function in StyleCop, but i am unable to find that rule. Can you help me


Satish
Email:- satishbhargav4u@gmail.com

Unknown said...

@samuraix

I posted the code to Google Code.

@neil

If you modify the stylecop settings file in the Program Files location then it will make the settings global to Visual Studio unless a projects settings override the default.

Unknown said...

I followed your guide (actually I just copy and pasted your code), but I can't get Microsoft StyleCop to pick the rule up. I'm using .NET framework 2.0 and Visual Studio 2005. The dll is getting picked up because I can't edit or delete it. I've made sure that the file names match. Any help would be appreciated

Jackson...!!! said...

Hi,
My issue is same as what Ivan had told in his comment, i also but created same project, which got compiled without errors, but I can't get Microsoft StyleCop to pick the rule. Is there any other setting to integrate our custom rule in StypeCop?

Thanks,
Jackson C.

Zeor said...

If anyone should come by this; The project is now opensource and by looking it up I found out that the assembly should be build with .NET 3.5. If using another version, then the assembly will not be picked up and you can not see your own rules.

EnThu said...

I need to count lines of code in a method in c#. Can i add my custom rule for the same. Please help.
Thanks in advance for help.

EnThu said...

Hwy i am not able to see my custom created rule in the setting.stylecop. Can anyone help my assembly is 3.5 built my name of the XML file is same as name of class.
Please help.

D. Maymone said...

I have exactly the same problem as En Thu.
I am not able to see my custom created rule in the setting.stylecop. My assembly is 3.5. Same name to XML and class file. But I don't see the "Extensions" entry in the setting file.
Please help.

graydo64 said...

I had the same problem as EnThu and D. Maymone. I'd followed your post to the letter, checked it against the SDK but couldn't get my custom rule to load. I had used the nuget package in my project to get the references for StyleCop and StyleCop.CSharp. I found that removing the nuget package and referenced the dlls in %programfiles%\StyleCop 4.7 instead fixed the problem.

D. Maymone said...

I am not able yet to see my custom created rule in the setting.stylecop. My assembly is 3.5. Same name to XML and class file. But I don't see the "Extensions" entry in the setting file.
When I double click the Settings file this error is displayed:
---------------------------
StyleCop
---------------------------
An exception occurred while loading one of the StyleCop add-ins: System.IO.FileLoadException,
Could not load file or assembly 'StyleCop, Version=4.7.6.0, Culture=neutral,
PublicKeyToken=f904653c63bc2738' or one of its dependencies.
The located assembly's manifest definition does not match the assembly reference. (
Exception from HRESULT: 0x80131040)
Thanks

Allan said...

Custom software development specialists explore exactly what it is a company does - what the necessities of the company are on a day to day basis and what they need from their IT system in order to operate to their optimum. In order to perform efficient functionality, a company would ideally need its software to do exactly what they want it to.

Unknown said...
This comment has been removed by the author.
Unknown said...

Hi,
I can able to create my own custom rule in stylecop.When I open the settings file via visual studio my custom rules appear in separate Rule Group.I need to add it with stylecop rule ( e.g Documentation Rule ).Any idea?

yosabrams0918 said...

?I used to be very happy to search out this net-site.I needed to thanks for your time for this wonderful read!! I undoubtedly enjoying every little little bit of it and I have you bookmarked to check out new stuff you blog post. usa online casino

Catabatic Technology said...

What is the Creating Custom StyleCop Rules in C#. I have no idea but after reading this post i have this rule. thanks for sharing this info.

Travel Software Development Solution India | Travel Portal Development | Software Development Solutions

Best Digital Marketing Agency said...

Great Post Thanks for sharing with us and it is very helpful for us. Check this link also here: Software Development Company India

Prachi Kalra said...

Highly Commendable blog! Keep up the great work

SRDV Technologies | Web Development | Mobile App Development said...

what is fantastic post? this is so chock full of useful information I cannot wait to dig deep and start utilizing the resource give me.your exuberance is refreshing.
Software Development Travel portal development Travel white label Travel Portal Solution B2C Travel Portal B2B Travel Portal Flight Booking API System Flight api integration

DedicatedHosting4u said...

We will certainly see your enthusiasm in the work you have written. Incredible post. Articles that have important and well-informed notes are also enjoyable. Beautiful piece of article.

DedicatedHosting4u.com

Pankaj Singh said...

Nice blog. OGEN Infosystem is leading Web Designing Company in Delhi, India, visit our website for web designing and SEO Services.
SEO Service in Delhi

Pradeep Appslure said...

Appslure is Best app development company in mumbai and you can get website development service at a very affordable price.
App development company in mumbai

keylinesnet said...

I am really impressed with your blog article, such great & useful knowledge you mentioned here. Your post is very informative. Also check out the best web development company in Kolkata | web hosting company in Kolkata | hotel management colleges in Kolkata

jeewangarg said...

Jeewangarg is a Leading Digital Marketing Company which is helping your brand to cut through the Digital Clutter with its best SEO Company in Delhi. Our range of Services includes SEO Services, PPC Company in Delhi, Website Designing Services and Social Media Marketing Services. Being a Google Partner in India, we provide our client with 100% satisfaction in every aspect of their marketing goals. So, what are you waiting for Connect to the team of best SEO Expert in India, Google Ads Experts, Website Designing Experts, Social Media Experts & more to boost your Digital Presence today with the high quality Digital Marketing Services.

Servo said...

Servo Stabilizer Manufacturer in India, Servo Star offers a wide range of single phase to three-phase Servo Voltage Stabilizer units to suit various types of domestic and industrial applications such as metal processing equipment, production lines, construction devices, elevators, medical equipment, air-conditioners, etc. Call us on 9250809090 to get the best quote for Servo Stabilizer Price & Transformer Price in India.

Video Production Company said...

TVH, Best Video & Film Production Houses/Company in Delhi Ncr. we Provides Corporate Films, Documentary Films, Short Makers, Explainer Videos, & promotional video services in delhi ncr. Call us @ 8178662477. Best Video & Film Production Houses/company in Delhi NCR Visit Us: film production companies in india, corporate video production company

Arrowaircraft said...

Arrow Aircraft is one of the reliable private jet india. We offer Aircraft Charter Services in Delhi, Mumbai as well as all over the World.

Kedarnath Yatra by Helicopter
Chardham Yatra by Helicopter
Book Helicopter for Wedding Price

Appslure said...

Great information shared through this post. It helps me in many ways.Thanks for posting this again. We are top Mobile App Development | Mobile App Development Company in India | Website Development Company in Delhi | Website Designing Company in Gurgaon.

pankaj shukla said...

Thanks for sharing useful information. We are leading mobile app development companies in dubai.

Video Production Company said...

Well I definitely enjoyed reading it. This tip procured by you is very constructive for correct planning.

event management companies
event management companies in delhi

chouaih mohammed said...


i am browsing this website dailly and get nice facts from here all the time

Servomax Ltd said...

Servo Stabilizers, Servomax offers a wide range of Servo Voltage Stabilizer units to suit various types of domestic and industrial applications such as metal processing equipment, production lines, construction devices, elevators, medical equipment, etc. Call us on +91 9111234567 to get the best quote for Servo Stabilizer Price.

Jordan said...

You can create backlinks to your website from these links…...Most beautiful places in the world  | bordeaux France  | things to do in bordeaux | beautiful places in Pakistan | Bali Indonesia | Explore Worldwide | lake Tahoe attractions | Kumrat Valley |

Kettysmith said...

Towing Elite is the best service providers for towing cars, trucks and more. We are offering our services in multiple locations and in best charges. Call us to get more information.
Towing Services in Beaverton
Tow Truck Company near Mt St Helens
Towing Services near Cougar
Tow Truck Company in Portland
Tow Truck Company in Gresham
Tow Truck Company in Tigard

Village Talkies said...

Best Corporate Video Production Company in Bangalore and top Explainer Video Company in Bangalore , 3d, 2d Animation Video Makers in Chennai.
Great tips! But one more thing we would like to add here i.e Browser compatibility is also a must.

SEO said...

Move a step forward and connect with your audience with our PPC Experts India


Thinking PPC advertising? Think Us. Get in touch with our team and coordinate with the experts around. We will help you take your business a step forward and build your customers regularly. Our comprehensive approach and dedication make us a company one can rely on for PPC services in India. Share your thoughts and ideas with us and we will make sure that each and every one of them gets fulfilled in no time professionally.

Home Refurbishment in London said...

Hiring The Equitable Local Builders In London For Home Improvements Services

It is always said that people often desire to be in a house that could give them a desired luxury and comfort and that could only be done with some efforts. Although some manage to furnish their home by themselves, at times this can be tedious to them and also time taking.

Kettysmith said...

Nearest Facility Maintenance Company based in USA and offering it services in multiple locations. We are helping in parking lot repairing, roof repairing, home repairing and more. Call us to get more information.
Nearest Facility Maintenance
Nearest General Contractor Company
Nearest Construction Facility
Nearest Fencing Company
Home Maintenance Services
Nearest Parking Lot Signs Company

Tech said...

Microsoft Office suite has become a must-have not only for large corporations but for individual users as well. The latter face the necessity to download Office programs once they understand that apps integrated into their OS are too basic and can’t satisfy their needs.
Microsoft Office Torrent

davidclauses said...

Now you can move to various location safely with Taipan Express Movers. Shift your high value items, pets, kids and more with us in genuine charges.
Packers and Movers in Malaysia
International Movers in Malaysia
Packers & Movers Near Me
International relocation services
Furniture Storage Solutions
Moving with Kids
Moving with Pets
Moving High Value Items

Test Marketing said...

The number of people looking for Microsoft Office torrent is growing every day. The tendency is obvious since this package of programs has long become popular among millions of users all over the globe, supplying them with all the necessary tools for work with text, spreadsheets and presentations.

Microsoft office torrent