Microsoft MVP성태의 닷넷 이야기
VS.NET IDE: 85. T4를 이용한 INotifyPropertyChanged 코드 자동 생성 [링크 복사], [링크+제목 복사],
조회: 19960
글쓴 사람
정성태 (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)
13511정성태1/4/20242189닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20242117닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20242167오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242207오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242848닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232425닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232965닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232553닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232426Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232533닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232315개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232399디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233077닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232476오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232462Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232410Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232555Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232660닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232342개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232266Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232391개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232173개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232105오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232409개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232222개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232102오류 유형: 883. dotnet build/restore - error : Root element is missing
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...