Microsoft MVP성태의 닷넷 이야기
VS.NET IDE: 85. T4를 이용한 INotifyPropertyChanged 코드 자동 생성 [링크 복사], [링크+제목 복사]
조회: 19937
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

T4를 이용한 INotifyPropertyChanged 코드 자동 생성

INotifyPropertyChanged 관련 코드야말로 '자동 생성'하기 딱 좋은 분야일 것입니다.

제 경우에 예전에는 "XmlCodeGenerator"로 그것을 해결했었는데요. ^^

Visual Studio 확장으로 XmlCodeGenerator 제작하는 방법
; https://www.sysnet.pe.kr/2/0/1518

XmlCodeGenerator 1.0.0.4 업데이트
; https://www.sysnet.pe.kr/2/0/760

XmlCodeGenerator를 C/C++ 코드 생성에 적용
; https://www.sysnet.pe.kr/2/0/775

이번에는, 그동안 미뤄왔던 T4(Text Template Transformation Toolkit: 'T' 글자가 4개여서 T4 ^^)에 대한 공부를 할 겸 INotifyPropertyChanged 자동 생성 코드를 가지고 실습을 해보았습니다.

참고로, "MSDN Magazine"에서 이에 대한 것을 다루고 있기 때문에 그것을 보셔도 무방합니다. ^^

Lowering the Barriers to Code Generation with T4
; https://learn.microsoft.com/en-us/archive/msdn-magazine/2012/april/t4-templates-lowering-the-barriers-to-code-generation-with-t4




체험을 한번 해보는 것이 가장 빠르니 ^^ 실습으로 바로 들어가 보겠습니다.

INotifyPropertyChanged 코드에 대한 테스트를 위해 간단하게 WPF 프로젝트를 하나 만들고, "Text Template"을 하나 추가합니다.

t4_sample_1.png

위에 보시면 "Preprocessed Text Template"과 "Text Template" 이 있는데요. 차이점은 다음의 글에서 잘 설명해 주고 있습니다.

Understanding T4: Preprocessed Text Templates
; http://www.olegsych.com/2009/09/t4-preprocessed-text-templates/

Visual Studio에 대한 의존성없이 T4를 이용해 소스코드를 생성하는 것이 "Preprocessed Text Template"인 반면, Visual Studio 내에서 동작하는 것이 "Text Template"의 주요 차이점입니다. 이번 단계에서는 "Text Template"만을 추가해 줍니다. 그럼, 다음과 같이 .tt 확장자를 가진 파일과 그 하위에 자동 소스코드 생성 파일인 .txt가 위치하는 것을 볼 수 있습니다.

t4_sample_2.png

우리가 할 일은 C# 소스코드를 출력하는 것이므로 우선 .tt 파일의 내용 중에 extension을 .cs로 바꿔줍니다.

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>

이제 나머지는 .aspx 파일처럼 작성하시면 됩니다. 단지 .aspx에서는 HTML 태그를 출력했던 반면 .tt에서는 C# 코드를 출력한다는 차이점이 있다는 정도인데요. 간단하게 실습삼아 WPF 프로젝트의 Window 객체에 대한 모든 속성(property)을 const 문자열로 나열해 주는 C# 코드를 다음과 같이 만들 수 있습니다.

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>

<#@ assembly name="System.Xaml" #>
<#@ assembly name="PresentationCore" #>
<#@ assembly name="PresentationFramework" #>

<#@ Import Namespace="System.Windows" #>

public partial class PropertyList
{
<#
    Type type = typeof(System.Windows.Window);
    foreach (var item in type.GetProperties())
    {
#>
        public const string <#=item.Name#> = "<#=item.Name#>";
<#
    }
#>
}

위와 같이 .tt 파일을 작성한 후 저장하면 하위 .cs 파일에 다음과 같은 내용이 자동으로 채워집니다.

public partial class PropertyList
{
        public const string TaskbarItemInfo = "TaskbarItemInfo";
        public const string AllowsTransparency = "AllowsTransparency";
        public const string Title = "Title";
        public const string Icon = "Icon";
        ...[생략]...
        public const string TouchesOver = "TouchesOver";
        public const string TouchesDirectlyOver = "TouchesDirectlyOver";
        public const string DependencyObjectType = "DependencyObjectType";
        public const string IsSealed = "IsSealed";
        public const string Dispatcher = "Dispatcher";
}

이 정도면 T4를 어떻게 사용할 수 있는지 대강 아셨죠? ^^




원래 이야기로 돌아가서 WPF의 INotifyPropertyChanged 소스코드를 T4로 처리하는 방법을 다뤄보겠습니다. 우선, T4 도움없이 예전처럼 MainWindow에 데이터바인딩이 가능한 string MyText 공용 속성을 정의해 연동하는 소스코드를 작성해 보겠습니다.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <TextBox FontSize="20" Text="{Binding Path=MyText, UpdateSourceTrigger=PropertyChanged}" />
        <TextBlock FontSize="20" Text="{Binding Path=MyText}" Grid.Row="1" />
    </Grid>
</Window>

위와 같이 바인딩할 수 있는 MyText를 정의하기 위해 이제 부수적인 코드를 MainWindow에 추가해야 합니다.

using System.ComponentModel;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        string _myText;
        public string MyText
        {
            get { return this._myText; }

            set
            {
                if (this._myText == value)
                {
                    return;
                }

                this._myText = value;
                OnPropertyChanged("MyText");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged == null)
            {
                return;
            }

            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

보시는 바와 같이 MainWindow 코드가 매우 번잡해집니다. 문제는 데이터바인딩이 필요한 클래스마다 매번 이런 식으로 정의를 해야 한다는 점과, 속성이 추가될 때마다 set 구문에 OnPropertyChanged 처리를 해줘야 하는 귀찮음이 있습니다.

자... 그럼 이것을 T4를 이용해 해결해 볼까요? 방식은 확장성을 고려해 XmlCodeGenerator처럼 정의할 수 있도록 해보겠습니다.

그럼 일단 WPFAux.xml 이름으로 XML 파일을 추가하고 T4에서 소스코드를 자동 생성할 수 있는 값들을 임의로 정합니다.

<?xml version="1.0" encoding="utf-8" ?>
<module namespace="WpfApplication1">

    <clrnamespace>
        <item>System.Data</item>
        <item>System</item>

        <item>System.Collections.Generic</item>
        <item>System.Text</item>
        <item>System.IO</item>
        <item>System.Diagnostics</item>
        <item>System.Configuration</item>
        <item>System.Runtime.InteropServices</item>
        <item>System.ComponentModel</item>
        <item>System.Runtime.CompilerServices</item>
        <item>System.Runtime.Serialization</item>
        <item>System.Collections.ObjectModel</item>
        <item>System.Windows.Media.Imaging</item>
    </clrnamespace>

    <type name="MainWindow" observable="true" bindingImplement="true" skipCtor="true">
        <properties>
            <property name="MyText" type="string" />
        </properties>
    </type>

</module>

이 정보를 바탕으로 데이터바인딩이 가능한 소스코드를 생성하는 tt 소스 코드는 다음과 같습니다.

<#@ template language="C#" Hostspecific="True" #>

<#@ assembly name="System.Xml.dll" #>

<#@ Import Namespace="System.Xml" #>
<#@ Import Namespace="System.Collections" #>

<#
    string XmlPath = "WPFAux.xml";

    if (string.IsNullOrEmpty(XmlPath) == true)
    {
        return null;
    }
    
    XmlDocument xml = new XmlDocument();
    xml.Load(Host.ResolvePath(XmlPath));

    XmlNode moduleNode = xml.SelectSingleNode("module");

    string nsText = moduleNode.Attributes.GetNamedItem("namespace").InnerText;
    XmlNodeList clrNamespaces = moduleNode.SelectNodes("clrnamespace/item");

    XmlNodeList typeList = moduleNode.SelectNodes("type");

#>

namespace <#= nsText #>
{
<#
    this.PushIndent("    ");
    foreach (XmlNode item in clrNamespaces)
    {
#>
using <#=  item.InnerText #>;
<#
    }
    
    foreach (XmlNode type in typeList)
    {
        var xmlAttr = type.Attributes;
        string typeName = xmlAttr.GetNamedItem("name").InnerText;
        bool observable = bool.Parse(xmlAttr.GetNamedItem("observable").InnerText);
        bool bindingImplement = bool.Parse(xmlAttr.GetNamedItem("bindingImplement").InnerText);
        bool skipCtor = bool.Parse(xmlAttr.GetNamedItem("skipCtor").InnerText);
#>

public partial class <#= typeName #>
<#
        if (bindingImplement == true)
        {
            #>
            : INotifyPropertyChanged
            <#
        }
#>       
{
    public class Properties
    {
<#
        var dpList = type.SelectNodes("properties/property");
        foreach (XmlNode dpItem in dpList)
        {
            var dpAttr = dpItem.Attributes;
            string dpName = dpAttr.GetNamedItem("name").InnerText;
#>
        public const string <#= dpName #> = " <#= dpName #>";
<#
        }
#>
    }
    
<#
        dpList = type.SelectNodes("properties/property");
        foreach (XmlNode dpItem in dpList)
        {
            var dpAttr = dpItem.Attributes;
            string dpName = dpAttr.GetNamedItem("name").InnerText;
            string dpTypeName = dpAttr.GetNamedItem("type").InnerText;
            string dpPrivateName = dpName;
            if (char.IsUpper(dpName[0]) == true)
            {
                char ch = (char)(dpName[0] + 32);
                dpPrivateName = ch.ToString() + dpName.Substring(1);
            }
            
            bool hasDefaultValue = dpAttr.GetNamedItem("defaultValue") != null;         
            string defaultValueText = string.Empty;
            if (hasDefaultValue == true)
            {
                defaultValueText = " = " + dpAttr.GetNamedItem("defaultValue").InnerText;
            }
            
            bool hasPostCode = dpItem.SelectSingleNode("postCode") != null;
            string postCodeText = string.Empty;
            if (hasPostCode == true)
            {
                postCodeText = dpItem.SelectSingleNode("postCode").InnerText;
            }
            // string dpDefaultValue = dpAttr.GetNamedItem("defaultValue").InnerText;
            
            bool isCollection = dpAttr.GetNamedItem("isCollection") != null;
            if (isCollection == true)
            {
                isCollection = bool.Parse(dpAttr.GetNamedItem("isCollection").InnerText);
            }
            
            if (isCollection == true)
            {
                dpTypeName = "List<" + dpTypeName + ">";
            }
            
#>
    <#= dpTypeName #> _<#= dpPrivateName #><#= defaultValueText #>;
    /// <exclude />
    public <#= dpTypeName #> <#= dpName #>
    {
        get { return this._<#= dpPrivateName #>; }
        
        set
        {
            if (this._<#= dpPrivateName #> == value)
            {
                return;
            }
            
            this._<#= dpPrivateName #> = value;
            OnPropertyChanged("<#= dpName #>"); <#= postCodeText #>
        }
    }
    
<#
        }
#>
    
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged == null)
        {
            return;
        }

        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }    
}
<#
    }
    
    this.PopIndent();
#>

}

.tt 파일에서는 지정된 WPFAux.xml 파일을 읽어서 설정된 XML 값에 따라 데이터바인딩 클래스들을 partial로 정의해 다음과 같이 생성해 냅니다.

namespace WpfApplication1
{
    using System.Data;
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Diagnostics;
    using System.Configuration;
    using System.Runtime.InteropServices;
    using System.ComponentModel;
    using System.Runtime.CompilerServices;
    using System.Runtime.Serialization;
    using System.Collections.ObjectModel;
    using System.Windows.Media.Imaging;
    
    public partial class MainWindow
                : INotifyPropertyChanged
                        
    {
        public class Properties
        {
            public const string MyText = " MyText";
        }
        
        string _myText;
        /// <exclude />
        public string MyText
        {
            get { return this._myText; }
            
            set
            {
                if (this._myText == value)
                {
                    return;
                }
                
                this._myText = value;
                OnPropertyChanged("MyText"); 
            }
        }
        
        
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged == null)
            {
                return;
            }
    
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }    
    }

}

MainWindow가 가져갈 소스코드 복잡도를 xml 파일로 대신해 T4가 처리하고 있습니다. 이제부터는 WPF 프로젝트에 포함되는 데이터바인딩 가능한 요소들을 쉽게 처리할 수 있습니다. 단지, WPFAux.xml 파일에 해당 클래스 명과 그 안에 데이터바인딩될 속성들을 추가해 주면 그만입니다.




첨부한 소스코드는 위의 처리가 포함된 예제 프로젝트입니다.

참고로, Visual Studio의 T4 코드 편집창은 C# 코드에 대해 인텔리센스를 제공하지 않는데요. 다음의 툴은 이런 단점을 보완해 나온 제품입니다. ^^

tangible T4 Editor 2.2.3 plus UML modeling tools
; http://t4-editor.tangible-engineering.com/T4-Editor-Visual-T4-Editing.html

물론 전문적인 소스코드 생성이 아니라면 Visual Studio의 단순 코드 편집창에서 해도 그다지 불편함이 없습니다.






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

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/2/2023]

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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13607정성태4/25/2024195닷넷: 2248.C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024212닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024426닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024478오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024723닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024802닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024853닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024890닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024871닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024899닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024881닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241073닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241053닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241069닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241085닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241224C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241200닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241079Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241156닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241270닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241170오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241337Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241144Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241270개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241487Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...