Microsoft MVP성태의 닷넷 이야기
VS.NET IDE: 56. C#에서 아쉬운 __DATE__, __TIME__ 매크로 [링크 복사], [링크+제목 복사],
조회: 28330
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)


C#에서 아쉬운 __DATE__, __TIME__ 매크로


C/C++ 매크로 기능을 .NET에서 구현하는 첫 번째 사례에 대해서는 다음의 토픽에서 말씀드렸지요.

XML/XSLT로 구현하는 매크로 확장
; https://www.sysnet.pe.kr/2/0/542

그래도, 모든 경우의 매크로 기능을 XML/XSLT 확장으로 처리하기에는 무리가 있긴 합니다.

고객으로부터 요청 사항이 들어왔습니다. 배포된 응용 프로그램의 정확한 팀 빌드 버전을 알고 싶다는 것인데, 물론 소스 코드가 수정이 되고 AssemblyVersion을 같이 변경해 주면 추적이 되는데도 불구하고 실제로 개발자들이 그와 같은 변경을 자주 잊어버리기 때문에, 예전의 C/C++에서 제공되던 __DATE__, __TIME__으로 주어지는 문자열을 프로그램 정보창에 띄워달라는 것이었습니다.

일면... 타당하기도 하고,,, ^^

어쨌든, 이를 해결하기 위한 방법으로는 MSBuild 외에는 딱히 떠오르지를 않습니다. 게다가 소스 코드 파일을 직접 수정하는 것은 버전 제어 시스템과의 연계 면에서 과히 좋은 생각이 아니기 때문에 별도의 파일에 컴파일 정보를 담아 놓는 것으로 결정했습니다.

우선, 프로젝트에 "output.txt"라는 파일을 추가하고 빌드 유형을 "Embedded Resource"로 변경합니다. 그다음, "프로젝트" 파일을 메모장 등에서 편집을 합니다.

대강, 아래와 같은 내용으로 편집해 주면 됩니다.

<Target Name="BeforeBuild">
    <Exec Command="Date /T &gt; output.txt" />
    <Exec Command="Time /T &gt;&gt; output.txt" />
</Target>

아쉽게도, 기본 제공되는 MSBuild Task에는 현재 시간을 구하는 속성이 없었습니다. 물론, 현재 시간을 반환해주는 사용자 정의 Task를 만들 수도 있지만 - 경험상, 고객 사이트에 이런 설치 요소를 늘리는 것은 바람직 하지 않기 때문에 - 간단하게 목적을 달성할 수 있는 도스 명령어의 "Date", "Time"을 이용했습니다.

그런데, 소스 컨트롤에 올렸더니 "Access Denied" 문제가 발생합니다. 이런 경우는 굳이 Check In/Out 정보를 남길 필요가 없기 때문에 단순히 파일 속성의 읽기 전용 속성만 풀어주는 것으로 해결할 수 있습니다.

<Target Name="BeforeBuild">
    <Exec Command="attrib -R output.txt" />
    <Exec Command="Date /T &gt; output.txt" />
    <Exec Command="Time /T &gt;&gt; output.txt" />
    <Exec Command="attrib +R output.txt" />
</Target>

해당 프로젝트의 바이너리들이 팀 빌드를 통해서 배포된다면, 팀 빌드 버전 기록이 보여지는 것이 오히려 정상일 수 있습니다. 이를 위해 "$(BuildNumber)"가 팀 빌드 시에는 제공이 되지만, 로컬 빌드에서는 없기 때문에 2가지 상황을 고려해 줘야 합니다. 결국, 아래와 같이 마무리를 하게 됩니다.

<PropertyGroup>
    <BeforeBuildDependsOn>
      RemoteTFSBuild;
      LocalProjectBuild;
    </BeforeBuildDependsOn>
</PropertyGroup>

<Target Name="BeforeBuild" DependsOnTargets="$(BeforeBuildDependsOn)" Outputs="$(TargetPath)">
</Target>

<Target Name="RemoteTFSBuild" Condition="$(BuildNumber) != ''">
    <Exec Command="attrib -R output.txt" />
    <Exec Command="echo $(BuildNumber) &gt; output.txt" />
    <Exec Command="attrib +R output.txt" />
</Target>

<Target Name="LocalProjectBuild" Condition="$(BuildNumber) == ''">
    <Exec Command="attrib -R output.txt" />
    <Exec Command="Date /T &gt; output.txt" />
    <Exec Command="Time /T &gt;&gt; output.txt" />
    <Exec Command="attrib +R output.txt" />
</Target>

이렇게 포함된 내용은 다음과 같은 코드로 가져와서 메시지 박스에 보여주면 끝.

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Assembly asm = this.GetType().Assembly;
            
            using (System.IO.Stream stream 
                = asm.GetManifestResourceStream("WindowsApplication1.output.txt"))
            {
                byte[] bufffer = new byte[stream.Length];
                stream.Read(bufffer, 0, (int)stream.Length);
                this.Text = Encoding.UTF8.GetString(bufffer);
            }
        }
    }
}

더 좋은 의견 있으신 분??? ^^



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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/8/2021]

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

비밀번호

댓글 작성자
 



2008-06-10 03시34분
[konanya] 좋은 아이디어시네요. ^^ 잘 배우구 갑니다.
[guest]
2008-11-30 10시36분
TeamBuild ClickOnce - Auto Incrementing Your Version Information
; http://myramserialize.blogspot.com/search/label/Team%20Build
kevin25

... 61  [62]  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12424정성태11/24/202019585VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202019586.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/202017075.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/202016188.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/202016768오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/202017023VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202019180오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/202017650오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/202018771오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202018311.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202021079VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202019759.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202021773.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202018319오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202019187디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202020858.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202035869도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202020936.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202021876.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202020376.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202020979.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202019049.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202021301.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202020628VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202016625오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202019736.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
... 61  [62]  63  64  65  66  67  68  69  70  71  72  73  74  75  ...