2014年5月20日

客製化Stylecop簽入規則 Custom Stylecop Check-in Policy

上一篇中介紹如何在Stylecop中新增自定義規則,這一篇要講解如何自定義規則

主要幾個步驟
1. 新增 .Netframework 3.5專案 並選擇 類別庫



2. 加入參考StyleCop.dll 及 StyleCop.CSharp.dll

    在本機端的Stylecop 則到
    C:\Program Files (x86)\StyleCop 4.7

    在TFS上的Stylecop 則到
    C:\Users\Administrator\AppData\Local\Microsoft\VisualStudio\12.0\Extensions\目前使用者名稱




 3. 新增.cs檔加入以下的code




using StyleCop;
using StyleCop.CSharp;

namespace MyCustomRules
{
 /// <summary>
 /// Custom analyzer for demo purposes.
 /// </summary>
 [SourceAnalyzer(typeof(CsParser))]
 public class MyCustomRule : SourceAnalyzer
 {
  /// <summary>
  /// Extremely simple analyzer for demo purposes.
  /// </summary>
  public override void AnalyzeDocument(CodeDocument document)
  {
   CsDocument doc = (CsDocument)document;

   // skipping wrong or auto-generated documents
   if (doc.RootElement == null || doc.RootElement.Generated)
    return;

   // check all class entries
   doc.WalkDocument(CheckClasses);
  }

  /// <summary>
  /// Checks whether specified element conforms custom rule CR0001.
  /// </summary>
  private bool CheckClasses(
   CsElement element,
   CsElement parentElement,
   object context)
  {
   // if current element is not a class then continue walking
   if (element.ElementType != ElementType.Class)
    return true;

   // check whether class name contains "a" letter
   Class classElement = (Class)element;
   if (classElement.Declaration.Name.Contains("a"))
   {
    // add violation
    // (note how custom message arguments could be used)
    AddViolation(
     classElement,
     classElement.Location,
     "AvoidUsingAInClassNames",
     classElement.FriendlyTypeText);
   }

   // continue walking in order to find all classes in file
   return true;
  }
 }
}


4. 新增xml檔 - 新增的Xml檔案必須跟.cs檔的檔名一模一樣

xml內容
<?xml version="1.0" encoding="utf-8" ?>
<SourceAnalyzer Name="My Custom Rule">
 <Description>
  Custom rule for demo purposes.
 </Description>
 <Rules>
  <Rule Name="AvoidUsingAInClassNames" CheckId="CR0001">
   <Context>Do not use 'a' letter in {0} names.</Context>
   <Description>Fires when 'a' letter is used in class name.</Description>
  </Rule>
 </Rules>
</SourceAnalyzer>




5. 在xml檔案上按右鍵選擇屬性,將"建置動作"改為"內嵌資源(Embedded Resource )"




最後一個步驟就是將產生出來的dll檔放入Stylecop資料夾中

使用不同Stylecop放置dll的位置會不同

本機Stylecop C:\Program Files (x86)\StyleCop 4.7
TFS Stylecop C:\Users\Administrator\AppData\Local\Microsoft\VisualStudio\12.0\Extensions\目前使用者名稱

沒錯! 就是剛剛複製dll的位置

最後再打開Stylecop規則設定時,就會看到自己寫的新增規則


 

Reference:
http://stylecopplus.codeplex.com/wikipage?title=How%20to%20Create%20StyleCop%20Custom%20Rule

<Javascript> How to uncompressed GZIP at front-end using Javascript

It's been a while I haven't share my coding work. In this article I would like to share how to receive a Gzip file via stream, unzip...