C#代码检查工具:stylecop
微软的StyleCop作为一款代码分析插件,集成到Visual Studio 2008和Visual Studio 2010之中,可以帮助开发人员迅速地理清编程规范问题。对确保软件质量,确保软件开发效率而言,意义非凡。与同样出自微软的另一款代码分析工具fxcop通过分析程序集来检查各类编程规范错误不同的是,StyleCop是针对C#源代码的分析工具。有点类似java的checkstyle。
StyleCop可以检查代码中的各类静态编程规范错误,从代码注释,代码布局,可维护性,命名规范,可读性等各方面对代码规范性进行检查。重要的是,其规则可以自定义,可以屏蔽掉不适用于特定项目的规则,甚至可以自定义开发适用于各自项目的规则。
安装StyleCop以后,在解决方案视图中右键点击项目,在弹出菜单选择“Run StyleCop”即可运行代码检查,结果默认将被输出至“Warnings”清单。也可以修改通过配置项,将其输出至“Errors”清单。开发人员可以方便地定位并修改编程规范问题。
StyleCop可以与MSBuild进行集成。这样当开发人员点击“生成”项目时,将自动运行StyleCop检查,无须选择“Run StyleCop”菜单。而且,通过使用SVNStyleCop插件,可以方便地在SVN库上进行代码check in检查,对不符合代码规范的check in动作进行回滚。
以下步骤介绍如何集成StyleCop至MSBuild,即让开发人员直接点击“生成”项目就可以进行代码检查:
1,安装MSBuild集成文件。默认情况下,安装StyleCop不会选中安装“MSBuild files”,因此在安装时,进行到如下步骤时,确保选中“MSBuild files”进行安装。
2,在项目文件中增加Import配置节。要使得某个项目可以集成到MSBuild,需要使用诸如NotePad之类的编辑器打开项目文件(.csproj),添加如下红色字体部分,并保存项目文件:
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
...Contents Removed...
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(ProgramFiles)\MSBuild\Microsoft\StyleCop\v4.3\Microsoft.StyleCop.targets" />
...Contents Removed...
</Project>
重新加载项目之后,该项目即可集成到MSBuild当中了。
StyleCop还可以很方便地集成到团队开发和构建环境,如CI中。
StyleCop已经开源:http://stylecop.codeplex.com/
SVNStyleCop请参见:http://svnstylecop.codeplex.com/
1styleCop安装,2和VS集成,3使用在项目中使用stylecop和把警告改为错误5规则的应用顺序
1styleCop安装
2和VS集成
要和vs集成一定要在安装时把MSBuild files那个选项选中的,否则安装后是不会和VS集成集成的。
3styleCop使用
4在项目中使用stylecop和把警告改为错误
在后缀为.csproj的文件添加如下一行,就可以使用styleCop主动检测项目了,但默认不符合规则的都是警告,注意需要在安装styleCop时选择与VS集成的那一部分,此部分默认是不安装的,否则这个项目用VS打开就会有问题,会提示不能识别某一节,不能打开。
- <Import Project="$(ProgramFiles)\MSBuild\Microsoft\StyleCop\v4.3\Microsoft.StyleCop.targets" />
styleCop把检测出来的问题默认设置为警告,如果要改为错误需要使用记事本之类的工具打开项目文件,也就是后缀为.csproj的文件,添加如下代码。请参考如下,
- <PropertyGroup>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
- <ProductVersion>8.0.50727</ProductVersion>
- <SchemaVersion>2.0</SchemaVersion>
- <ProjectGuid>{4B4DB6AA-A021-4F95-92B7-B88B5B360228}</ProjectGuid>
- <OutputType>WinExe</OutputType>
- <AppDesignerFolder>Properties</AppDesignerFolder>
- <RootNamespace>SampleProject</RootNamespace>
- <AssemblyName>SampleProject</AssemblyName>
- <StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>
- </PropertyGroup>
目前发现RootNamespace,AssemblyName 两节的值,没理解到底应该替换为什么,只是参考其他的PropertyGroup的节改写了一下就可以了 。
或者使用更简单的方法,在文件中的第一个 PropertyGroup节中添加如下代码 ,其实和上边的方法基本一样,只是没有添加PropertyGroup,而是在已有的第一个PropertyGroup节中添加如下一行代码罢了。
- <StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>
注意:如果需要把警告改为错误,则必须添加如下一行,否则以上两种方法都没作用。
- <Import Project="$(ProgramFiles)\MSBuild\Microsoft\StyleCop\v4.3\Microsoft.StyleCop.targets" />
5规则的应用顺序
据说是首先是项目下的规则文件,然后是styleCop安装目录下的规则文件,还有一个MSBuild\Microsoft\StyleCop\下的规则文件不知道什么顺序,我个人也不是很清楚,也没有找到相关文档,希望知道的朋友告诉一声。
Setting Up StyleCop MSBuild Integration
Hands-On Labs StyleCop and Code Analysis
1Fxcop配置文件简介,2命令行介绍,3项目中使用Fxcop,4Fxcop与VS集成
1Fxcop配置文件简介
Fxcop配置文件也就是Fxcop工程文件,也即是后缀为FxCop的文件
文件内容和简单,例如:
- <?xml version="1.0" encoding="utf-8"?>
- <FxCopProject Version="1.36" Name="My FxCop Project">
- <ProjectOptions>
- <SharedProject>True</SharedProject>
- <Stylesheet Apply="False">c:\program files\microsoft fxcop 1.36\Xml\FxCopReport.xsl</Stylesheet>
- <SaveMessages>
- <Project Status="Active, Excluded" NewOnly="False" />
- <Report Status="Active" NewOnly="False" />
- </SaveMessages>
- <ProjectFile Compress="True" DefaultTargetCheck="True" DefaultRuleCheck="True" SaveByRuleGroup="" Deterministic="True" />
- <EnableMultithreadedLoad>True</EnableMultithreadedLoad>
- <EnableMultithreadedAnalysis>True</EnableMultithreadedAnalysis>
- <SourceLookup>True</SourceLookup>
- <AnalysisExceptionsThreshold>10</AnalysisExceptionsThreshold>
- <RuleExceptionsThreshold>1</RuleExceptionsThreshold>
- <Spelling Locale="en-US" />
- <OverrideRuleVisibilities>False</OverrideRuleVisibilities>
- <CustomDictionaries SearchFxCopDir="True" SearchUserProfile="True" SearchProjectDir="True" />
- <SearchGlobalAssemblyCache>False</SearchGlobalAssemblyCache>
- <DeadlockDetectionTimeout>120</DeadlockDetectionTimeout>
- <IgnoreGeneratedCode>False</IgnoreGeneratedCode>
- </ProjectOptions>
- <Targets>
- <AssemblyReferenceDirectories>
- <Directory>C:/Windows/Microsoft.NET/Framework/v2.0.50727/</Directory>
- <Directory>C:/Windows/Microsoft.NET/Framework/v4.0.30319/WPF/</Directory>
- </AssemblyReferenceDirectories>
- <Target Name="$(ProjectDir)/bin/Debug/DataContract.dll" Analyze="True" AnalyzeAllChildren="True" />
- <Target Name="$(ProjectDir)/bin/Debug/DebugLogger.dll" Analyze="True" AnalyzeAllChildren="True" />
- </Targets>
- <Rules>
- <RuleFiles>
- <RuleFile Name="$(FxCopDir)\Rules\DesignRules.dll" Enabled="False" AllRulesEnabled="False">
- <Rule Name="AbstractTypesShouldNotHaveConstructors" Enabled="True" />
- </RuleFile>
- <RuleFile Name="$(FxCopDir)\Rules\GlobalizationRules.dll" Enabled="False" AllRulesEnabled="False" />
- <RuleFile Name="$(FxCopDir)\Rules\InteroperabilityRules.dll" Enabled="False" AllRulesEnabled="False" />
- <RuleFile Name="$(FxCopDir)\Rules\MobilityRules.dll" Enabled="False" AllRulesEnabled="False" />
- </RuleFiles>
- <Groups />
- <Settings />
- </Rules>
- </FxCopProject>
<AssemblyReferenceDirectories>一节包含查找引用程序集的目录,使用Fxcop时,经常遇到引用的程序集找不到的情况,可以使用Fxcop界面添加程序集,或者手动在这一节中添加目录,尤其是在个人电脑共有程序集路径不同的情况下。
<Target>包含需要检测的程序集,
RuleFile 包含检测规则文件所在的路径,以及是否检测。
<SearchGlobalAssemblyCache>False</SearchGlobalAssemblyCache>
如果为True,则当需要检测的程序集引用的程序集找不到时,会到系统全局程序集中找,否则不会在系统全局程序集中找,直接会报找不到程序集的错误,所以建议设置为True,默认是False。
需要注意的是Fxcop配置文件好像只能识别$(ProjectDir),其他和项目相关的路径好像都不识别,例如TargetDir。尤其是在开发机和服务器TargetDir目录相对于项目不一致时,很容易出现路径不一致的问题。
现在理解了$(ProjectDir)的含义,它是指Fxcop工程文件,也即是后缀为FxCop的文件的目录,而不是源代码解决方案的目录,自然没有TargetDir之类的东西了
2命令行介绍
3项目中使用Fxcop
可以在项目的属性中的build event中调用Fxcop进行检测例如:FxCopCmd.exe /c /p:"$(SolutionDir)SampleSolution.FxCop"
检测出来不符合要求的默认是警告,不是错误。如果要把警告改成错误,有几种思路。
思路一这种很复杂,我自己也没有看懂。
思路二这种看起来简单多了,但自己没试,不知道能不能用。
思路三就得自己写个小程序,把Fxcop的警告输出到特定文件,然后分析这个文件。
4Fxcop与VS集成
Pre-build Event/Post-build Event参考
Visual Studio build event command line 使用方法
Adding FxCopCmd to Your Build Process
Setting Up StyleCop MSBuild Integration
This article explains how to integrate the StyleCop tool into an MSBuild based build environment, for StyleCop 4.3 and above. If you are using SourceAnalysis 4.2, please see the following article:http://blogs.msdn.com/sourceanalysis/pages/stylecop-4-2-msbuild-integration.aspx.
MSBuild integration will cause the tool to run automatically whenever the code is built, and StyleCop violations will show up alongside compiler errors in the build output.
It is possible to set up the build integration so that StyleCop violations will appear as build warnings, or as build errors if so desired.
Installing MSBuild Files
To enable build integration, first be sure to select the MSBuild option when installing the tool, as shown in the image below:
This will cause the StyleCop binaries and supporting MSBuild targets files to be installed under the {Program Files}\MSBuild\Microsoft\StyleCop folder.
Adding the Import Tag
Once the StyleCop MSBuild files are installed, the next step is to import the StyleCop targets file into your C# projects. This is done by adding an Import tag to each C# project file.
For example, to integrate StyleCop to the project SampleProject, open the project file SampleProject.csproj within your favorite text editor. Scroll down to the bottom of the file and add a new tag to import the Microsoft.StyleCop.targets file. This import tag should be added just below the import of Microsoft.CSharp.targets:
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
...Contents Removed...
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(ProgramFiles)\MSBuild\Microsoft\StyleCop\v4.3\Microsoft.StyleCop.targets" />
...Contents Removed...
</Project>
Save the modified .csproj file. The next time you build this project either within Visual Studio or on the command line, StyleCop will run automatically against all of the C# source files within the project.
Build Warnings Vs Errors
By default, StyleCop violations will show up as build warnings. To turn StyleCop violations into build errors, the flag StyleCopTreatErrorsAsWarnings must be set to false. This flag can be set as an environment variable on the machine, or within the build environment command window. Setting the flag this way will cause StyleCop violations to appear as build errors automatically for all projects where StyleCop build integration is enabled.
Alternately, this flag can be set within the project file for a particular project. Open the .csproj file for your project again, and find the first PropertyGroup section within the file. Add a new tag to set theStyleCopTreatErrorsAsWarnings flag to false. For example:
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{4B4DB6AA-A021-4F95-92B7-B88B5B360228}</ProjectGuid>
<OutputType>WinExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SampleProject</RootNamespace>
<AssemblyName>SampleProject</AssemblyName>
<StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings>
</PropertyGroup>
Team Development
The configuration described above will suffice to enable StyleCop build integration on an individual development machine. However, development teams working within a well-defined development environment can set up the build integration in a more global way, so that each developer does not have to manually install StyleCop on his machine.
To do this, copy all of the files from {Program Files}\MSBuild\Microsoft\StyleCop into a custom folder within your build environment, and check all of these files into your source control system. Next, define an environment variable within your development environment which points to the location of the StyleCop targets file. For example:
set StyleCopTargets=%enlistmentroot%\ExternalTools\StyleCop\v4.3\Microsoft.StyleCop.targets
With this configuration in place, it is simply a matter of adding the following import tag to each .csproj file within your development environment:
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(StyleCopTargets)" />
StyleCop will automatically run each time this project is built, no matter who is building the project. There is no need for each developer to install StyleCop manually, since the StyleCop binaries are checked directly into your source control system and are centrally integrated into your build environment.