Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

Visual Studio - 사용자 정의 정적 분석 규칙 만드는 방법

그동안 한 번쯤 사용자 정의 정적 분석 Rule을 만들어 봐야지... 생각만 하다가 마침 다음의 질문도 있고,

Visual Studio 2013에서 Rule Set 에 Custom Rule을 추가 할 수 있나요?
; http://social.msdn.microsoft.com/Forums/ko-KR/04376215-5abc-4bee-8d1f-a9b70ce82659/visual-studio-2013-rule-set-custom-rule-?forum=vsko

해서 그냥 한글 자료를 남긴다는 의미에서 단순 따라하기 식으로 실습해 보았습니다. 물론, 위의 질문에 포함된 글을 참조했습니다.

How to write custom static code analysis rules and integrate them into Visual Studio 2010
; http://blogs.msdn.com/b/codeanalysis/archive/2010/03/26/how-to-write-custom-static-code-analysis-rules-and-integrate-them-into-visual-studio-2010.aspx

우선, .NET 4.0 대상으로 클래스 라이브러리 유형의 C# 프로젝트를 하나 만들고 "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Team Tools\Static Analysis Tools\FxCop" 폴더에 위치한 FxCopSdk.dll, Microsoft.Cci.dll 파일을 참조 추가합니다. (32비트 운영체제의 경우 "C:\Program Files\Microsoft Visual Studio 12.0\Team Tools\Static Analysis Tools\FxCop" 폴더 참조)

물론 이렇게 되면 참조 경로가 하드 코딩 식으로 되는데요. 이런 경우 제가 자주 써먹는 방식이 하나 있는데, 다음 화면에서 보는 것처럼 라이브러리만 별도로 모아놓는 폴더를 하나 만들고 거기에 외부 DLL을 몰아넣은 다음 프로젝트 참조를 그쪽으로 걸어주면 관리가 좀 편해집니다. (소스 컨트롤 시에도 공유하기 편합니다. ^^)

static_analysis_rule_1.png

그다음 프로젝트에 (임의의 이름으로, 여기서는) "RuleMetadata.xml" 이름의 XML 파일을 추가하고 내용을 다음과 같이 채워줍니다. (물론, FriendlyName의 값도 임의의 원하는 문자열로 채워넣을 수 있습니다.)

<?xml version="1.0" encoding="utf-8" ?>
<Rules FriendlyName="My Custom FxCop Rules">
</Rules>

이제 해당 XML 파일을 아래의 화면과 같이 "Embedded Resource" 유형으로 설정합니다. (캡처 화면에 보이는 BaseFxCopRule.cs, EnforceHungarianNotation.cs 파일은 아직 작업 전이므로 무시하세요. ^^)

static_analysis_rule_2.png

그럼, 본격적으로 룰을 위한 코딩으로 들어가 볼까요? ^^ "How to write custom static code analysis rules and integrate them into Visual Studio 2010" 예제에서 만드는 룰은 private/internal 접근 제한자를 가진 클래스의 필드 이름이 헝가리안 표기법을 따르는가를 체크하는 것입니다.

일단 이에 대한 Base 클래스를 하나 만들어야 하는데,

using Microsoft.FxCop.Sdk;

namespace MyCustomRule
{
    internal abstract class BaseFxCopRule : BaseIntrospectionRule
    {
        protected BaseFxCopRule(string ruleName)
            : base(ruleName, "MyCustomRule.RuleMetadata",
                   typeof(BaseFxCopRule).Assembly)
        {
        }
    }
}

위에서 "MyCustomRule.RuleMetadata" 이름은 이전에 "Embedded Resource" 유형으로 추가했던 "RuleMetadata.xml" 자원에 대한 경로입니다. (따라서 여러분들의 프로젝트에서는 그에 맞게 이름을 변경해 주면 됩니다. 대개의 경우 "[default namespace].[resource file name]" 형식입니다.)

한번 더 C# 파일을 추가하고 Rule에 대응되는 실제 코딩을 담은 클래스를 작성합니다. (자세한 내용은 생략합니다.)

using Microsoft.FxCop.Sdk;
using System;

namespace MyCustomRule
{
    internal sealed class EnforceHungarianNotation : BaseFxCopRule
    {
        public EnforceHungarianNotation()
            : base("EnforceHungarianNotation")
        { }

        private const string s_staticFieldPrefix = "s_";
        private const string s_nonStaticFieldPrefix = "m_";

        public override TargetVisibilities TargetVisibility
        {
            get
            {
                return TargetVisibilities.NotExternallyVisible;
            }
        }

        public override ProblemCollection Check(Member member)
        {

            Field field = member as Field;
            if (field == null)
            {
                return null;
            }

            if (field.IsStatic)
            {
                CheckFieldName(field, s_staticFieldPrefix);
            }
            else
            {
                CheckFieldName(field, s_nonStaticFieldPrefix);
            }

            return Problems;
        }

        private void CheckFieldName(Field field, string expectedPrefix)
        {
            if (!field.Name.Name.StartsWith(expectedPrefix, StringComparison.Ordinal))
            {
                Resolution resolution = GetResolution(
                  field,  // Field {0} is not in Hungarian notation.
                  expectedPrefix  // Field name should be prefixed with {1}.
                  );
                Problem problem = new Problem(resolution);
                Problems.Add(problem);
            }
        }
    }
}

마지막으로 이렇게 작성한 룰을 Rulemetadata.xml 파일에 반영해야 하는데요. 다음과 같이 만들 수 있습니다.

<?xml version="1.0" encoding="utf-8" ?>
<Rules FriendlyName="My Custom FxCop Rules">
 <Rule TypeName="EnforceHungarianNotation" Category="MyRules" CheckId="CR1000">
   <Name>Enforce Hungarian Notation</Name>
   <Description>Checks fields for compliance with Hungarian notation.</Description>
   <Resolution>Field {0} is not in Hungarian notation. Field name should be prefixed with '{1}'.</Resolution>
   <MessageLevel Certainty="100">Warning</MessageLevel>
   <FixCategories>NonBreaking</FixCategories>
   <Url />
    <Owner />
    <Email />
  </Rule>
</Rules>

여기서 중요한 것은 /Rules/Rule[@TypeName] 속성의 값이 반드시 우리가 작성한 룰 클래스의 타입명을 담아야 하는 정도입니다. 그 외 필드의 자세한 설명은 역시 생략하지만 보시면 직관적으로 알 수 있는 내용입니다. ^^

빌드하면 MyCustomRule.dll이 생성되고 이제 해당 DLL을 Visual Studio가 인식하도록 설치 작업만 해주면 됩니다.




"How to write custom static code analysis rules and integrate them into Visual Studio 2010" 글에서는 작성된 룰에 대한 디버깅 방법도 소개해 주고 있습니다. 즉, 프로젝트 속성 창에서 FxCopCmd.exe를 지정해 룰을 돌려볼 수 있게 하는 것입니다.

static_analysis_rule_3.png

Start external program: C:\Program Files (x86)\Microsoft Visual Studio 12.0\Team Tools\Static Analysis Tools\FxCop\FxCopCmd.exe

Command line arguments: /out:"results.xml" /file:"MyCustomRule.dll" /rule:"MyCustomRule.dll" /D:"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Team Tools\Static Analysis Tools\FxCop"

"How to write custom static code analysis rules and integrate them into Visual Studio 2010" 글에는 "Working directory"까지 설정하고 있지만 제가 해보니 아무런 의미가 없었습니다. 그에 상관없이 무조건 우리가 만든 룰을 포함한 DLL을 "C:\program files (x86)\microsoft visual studio 12.0\team tools\static analysis tools\fxcop\Rules"에서 찾았습니다. 따라서 MyCustomRule.dll 파일을 해당 폴더에 복사해 주어야 합니다.

여기까지 작업하고 Visual Studio에서 CheckFileName 메서드에 BP(Breakpoint)를 걸은 후 F5(Start Debugging) 키를 누르면 정상적으로 디버그 모드에서 BP가 걸리는 것을 확인할 수 있습니다. 이것으로 모든 작업은 사실상 끝이 납니다.




현재 "C:\program files (x86)\microsoft visual studio 12.0\team tools\static analysis tools\fxcop\Rules" 폴더에 우리가 만든 MyCustomRule.dll 파일을 배포했으니 Visual Studio에서 곧바로 써 먹을 수 있습니다.

테스트를 위해 새롭게 Visual Studio를 띄워 테스트용 C# 프로젝트를 하나 만듭니다. 그리고 프로젝트 속성의 "Code Analysis" 탭에서 "Open" 버튼을 누르고,

static_analysis_rule_4.png

새롭게 뜬 ".ruleset" 편집 화면의 상단에 화살표 키가 아래를 향하는 아이콘(Show rules that are not enabled)을 누르면 현재 등록된 모든 룰을 보여줍니다. 거기서 우리가 만든 Rule을 선택해 주면 됩니다.

static_analysis_rule_5.png

이렇게 하고 저장을 하면 새로운 RuleSet 이름을 묻는데 아무 이름이나 지정하고 저장을 누르면 됩니다. 새로운 룰셋 파일이 저장되는 경로는 솔루션 파일이 있는 폴더로 지정하는 것이 권장됩니다.

그런 다음 이제 다시 프로젝트 설정 창으로 가서 방금 저장한 룰셋을 지정해 줍니다.

static_analysis_rule_6.png

물론, "Enable Code Analysis on Build" 옵션도 켜줘야 겠지요. 최종적으로 다음과 같이 선택된 화면 구성이 됩니다.

static_analysis_rule_7.png

이제 다음과 같이 룰을 위반하는 코드가 있다면,

namespace TestApp
{
    public class Class1
    {
        private static int m_Foo;
    }
}

빌드 시 출력(Output) 창에 이런 경고가 뜨는 것을 확인할 수 있습니다.

1>  Running Code Analysis...
1>MSBUILD : warning CR1000: MyRules : Field 'Class1.m_Foo' is not in Hungarian notation. Field name should be prefixed with 's_'.

또는 빌드 폴더(예: /bin/Debug)에 [프로젝트명].[확장자].CodeAnalysisLog.xml 파일이 생성되어 정적 분석 결과가 담기게 됩니다.

(첨부 파일은 위의 테스트를 진행한 2개의 프로젝트를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 11/25/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2014-07-08 12시30분
[오레오뽀또] 안녕하세요. MSDN포럼 질문글 질문자 입니다. 알기쉽게 정리해 주셔서 감사합니다~!
베이스 클래스에 참조되는 XML파일 이름이 달라서 규칙 표시가 안된거였네요. ㅠ ㅠ

C#용 규칙 말고 C/C++ 용 규칙도 만들 수 있을까요?
[guest]
2014-07-08 12시18분
딱히 관련 자료가 없는 걸로 봐서는 C/C++용 규칙을 외부에서 만들 수는 없는 것 같습니다.
정성태
2023-11-25 09시23분
정적 분석과 함께, 이제는 실행 시 성능 분석까지 (비록 Azure 서비스로 제공하지만) 할 수 있게 되었군요. ^^

Learn how to improve .NET application performance leveraging Azure Code Optimizations|.NET Conf 2023
; https://youtu.be/9AGaqvKL6jk
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13602정성태4/20/2024220닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024257닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024298닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024442닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024436닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024504닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024854닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024985닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241033닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241052닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241209C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241169닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241073Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241143닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241197닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241157오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241304Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241096Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241050개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241158Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241421Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241589개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241138닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241494오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241631닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...