첨부 소스 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

TestProject.zip
0.15MB

▶ Platforms/Windows/Package.appxmanifest

<?xml version="1.0" encoding="utf-8"?>
<Package
    xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
    xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
    xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
    IgnorableNamespaces="uap rescap">
    <Identity Publisher="CN=User Name" />
    <Properties>
        <PublisherDisplayName>User Name</PublisherDisplayName>
    </Properties>
    <Dependencies>
        <TargetDeviceFamily Name="Windows.Universal"
            MinVersion="10.0.17763.0"
            MaxVersionTested="10.0.19041.0" />
        <TargetDeviceFamily Name="Windows.Desktop"
            MinVersion="10.0.17763.0"
            MaxVersionTested="10.0.19041.0" />
        <PackageDependency Name="Microsoft.VCLibs.140.00"
            MinVersion="14.0.24217.0"
            Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" />
        <PackageDependency Name="Microsoft.VCLibs.140.00.UWPDesktop"
            MinVersion="14.0.24217.0"
            Publisher="CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US" />
    </Dependencies>
    <Resources>
        <Resource Language="x-generate" />
    </Resources>
    <Applications>
        <Application Id="App"
            Executable="$targetnametoken$.exe"
            EntryPoint="$targetentrypoint$">
            <uap:VisualElements />
        </Application>
    </Applications>
    <Capabilities>
        <rescap:Capability Name="runFullTrust" />
    </Capabilities>
</Package>

 

728x90

 

▶ Person.cs

using SQLite;

namespace TestProject;

/// <summary>
/// 사람
/// </summary>
[Table("people")]
public class Person
{
    //////////////////////////////////////////////////////////////////////////////////////////////////// Property
    ////////////////////////////////////////////////////////////////////////////////////////// Public

    #region ID - ID

    /// <summary>
    /// ID
    /// </summary>
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }

    #endregion
    #region 성명 - Name

    /// <summary>
    /// 성명
    /// </summary>
    [MaxLength(250), Unique]
    public string Name { get; set; }

    #endregion
}

 

300x250

 

▶ PersonRepository.cs

using SQLite;

namespace TestProject;

/// <summary>
/// 사람 저장소
/// </summary>
public class PersonRepository
{
    //////////////////////////////////////////////////////////////////////////////////////////////////// Field
    ////////////////////////////////////////////////////////////////////////////////////////// Private

    #region Field

    /// <summary>
    /// SQLite 연결
    /// </summary>
    private SQLiteConnection connection;

    /// <summary>
    /// 데이터베이스 파일 경로
    /// </summary>
    private string databaseFilePath;

    #endregion

    //////////////////////////////////////////////////////////////////////////////////////////////////// Property
    ////////////////////////////////////////////////////////////////////////////////////////// Public

    #region 상태 메시지 - StatusMessage

    /// <summary>
    /// 상태 메시지
    /// </summary>
    public string StatusMessage { get; set; }

    #endregion

    //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
    ////////////////////////////////////////////////////////////////////////////////////////// Public

    #region 생성자 - PersonRepository(databaseFilePath)

    /// <summary>
    /// 생성자
    /// </summary>
    /// <param name="databaseFilePath">데이터베이스 파일 경로</param>
    public PersonRepository(string databaseFilePath)
    {
        this.databaseFilePath = databaseFilePath;
    }

    #endregion

    //////////////////////////////////////////////////////////////////////////////////////////////////// Method
    ////////////////////////////////////////////////////////////////////////////////////////// Public

    #region 사람 추가하기 - AddPerson(name)

    /// <summary>
    /// 사람 추가하기
    /// </summary>
    /// <param name="name">성명</param>
    public void AddPerson(string name)
    {
        try
        {
            Initialize();

            if(string.IsNullOrEmpty(name))
            {
                throw new Exception("성명을 입력해 주시기 바랍니다.");
            }

            int recordCount = this.connection.Insert(new Person { Name = name });

            StatusMessage = string.Format("레코드 {0}건이 추가되었습니다(성명 : {1}).", recordCount, name);
        }
        catch(Exception exception)
        {
            StatusMessage = string.Format("{0} 추가시 에러가 발생했습니다 : {1}", name, exception.Message);
        }
    }

    #endregion
    #region 모든 사람 리스트 구하기 - GetAllPersonList()

    /// <summary>
    /// 모든 사람 리스트 구하기
    /// </summary>
    /// <returns>모든 사람 리스트</returns>
    public List<Person> GetAllPersonList()
    {
       try
       {
          Initialize();

          return this.connection.Table<Person>().ToList();
       }
       catch(Exception exception)
       {
          StatusMessage = string.Format("데이터 조회시 에러가 발생했습니다 : {0}", exception.Message);
       }

       return new List<Person>();
    }

    #endregion

    ////////////////////////////////////////////////////////////////////////////////////////// Private

    #region 초기화하기 - Initialize()

    /// <summary>
    /// 초기화하기
    /// </summary>
    private void Initialize()
    {
       if(this.connection != null)
       {
          return;
        }

       this.connection = new SQLiteConnection(databaseFilePath);

       this.connection.CreateTable<Person>();
    }

    #endregion
}

 

반응형

 

▶ FileHelper.cs

namespace TestProject;

/// <summary>
/// 파일 헬퍼
/// </summary>
public class FileHelper
{
    //////////////////////////////////////////////////////////////////////////////////////////////////// Method
    ////////////////////////////////////////////////////////////////////////////////////////// Static
    //////////////////////////////////////////////////////////////////////////////// Public

    #region 데이터베이스 파일 경로 구하기 - GetDatabaseFilePath(fileName)

    /// <summary>
    /// 데이터베이스 파일 경로 구하기
    /// </summary>
    /// <param name="fileName">파일명</param>
    /// <returns>데이터베이스 파일 경로</returns>
    public static string GetDatabaseFilePath(string fileName)
    {
        return Path.Combine(FileSystem.AppDataDirectory, fileName);
    }

    #endregion
}

 

▶ MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage x:Class="TestProject.MainPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    BackgroundColor="White">
    <Grid
        Margin="10"
        RowSpacing="10"
        ColumnSpacing="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*"    />
        </Grid.RowDefinitions>
        <Entry x:Name="nameEntry" Grid.Row="0"
            Placeholder="성명을 입력해 주시기 바랍니다." />
        <Button x:Name="addButtnon" Grid.Row="1"
            Text="추가하기" />
        <Label x:Name="statusMessageLabel" Grid.Row="2" />
        <Button x:Name="getButton" Grid.Row="3"
            Text="조회하기" />
        <CollectionView x:Name="collectionView" Grid.Row="4">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"  />
                            <ColumnDefinition Width="2*" />
                        </Grid.ColumnDefinitions>
                        <Label Grid.Row="0"
                            Text="{Binding ID}" />
                        <Label Grid.Column="1"
                            Text="{Binding Name}" />
                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </Grid>
</ContentPage>

 

▶ MainPage.xaml.cs

namespace TestProject;

/// <summary>
/// 메인 페이지
/// </summary>
public partial class MainPage : ContentPage
{
    //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
    ////////////////////////////////////////////////////////////////////////////////////////// Public

    #region 생성자 - MainPage()

    /// <summary>
    /// 생성자
    /// </summary>
    public MainPage()
    {
        InitializeComponent();

        this.addButtnon.Clicked += addButton_Clicked;
        this.getButton.Clicked  += getButton_Clicked;
    }

    #endregion

    //////////////////////////////////////////////////////////////////////////////////////////////////// Method
    ////////////////////////////////////////////////////////////////////////////////////////// Public

    #region 추가하기 버튼 클릭시 처리하기 - addButton_Clicked(sender, e)

    /// <summary>
    /// 추가하기 버튼 클릭시 처리하기
    /// </summary>
    /// <param name="sender">이벤트 발생자</param>
    /// <param name="e">이벤트 인자</param>
    public void addButton_Clicked(object sender, EventArgs e)
    {
        this.statusMessageLabel.Text = string.Empty;

        App.PersonRepository.AddPerson(this.nameEntry.Text);

        this.statusMessageLabel.Text = App.PersonRepository.StatusMessage;
    }

    #endregion
    #region 조회하기 버튼 클릭시 처리하기 - getButton_Clicked(sender, e)

    /// <summary>
    /// 조회하기 버튼 클릭시 처리하기
    /// </summary>
    /// <param name="sender">이벤트 발생자</param>
    /// <param name="e">이벤트 인자</param>
    public void getButton_Clicked(object sender, EventArgs e)
    {
        this.statusMessageLabel.Text = string.Empty;

        List<Person> personList = App.PersonRepository.GetAllPersonList();

        this.collectionView.ItemsSource = personList;
    }

    #endregion
}

 

▶ AppShell.xaml

<?xml version="1.0" encoding="UTF-8" ?>
<Shell x:Class="TestProject.AppShell"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:TestProject"
    Shell.FlyoutBehavior="Disabled">
    <ShellContent
        Title="사람"
        Route="MainPage"
        ContentTemplate="{DataTemplate local:MainPage}" />
</Shell>

 

▶ App.xaml

<?xml version = "1.0" encoding = "UTF-8" ?>
<Application x:Class="TestProject.App"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" />

 

▶ App.xaml.cs

namespace TestProject;

/// <summary>
/// 앱
/// </summary>
public partial class App : Application
{
    //////////////////////////////////////////////////////////////////////////////////////////////////// Property
    ////////////////////////////////////////////////////////////////////////////////////////// Static
    //////////////////////////////////////////////////////////////////////////////// Public

    #region 사람 저장소 - PersonRepository

    /// <summary>
    /// 사람 저장소
    /// </summary>
    public static PersonRepository PersonRepository { get; private set; }

    #endregion

    //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
    ////////////////////////////////////////////////////////////////////////////////////////// Public

    #region 생성자 - App(personRepository)

    /// <summary>
    /// 생성자
    /// </summary>
    /// <param name="personRepository">사람 저장소</param>
    public App(PersonRepository personRepository)
    {
        InitializeComponent();

        MainPage = new AppShell();

        PersonRepository = personRepository;
    }

    #endregion
}

 

▶ MauiProgram.cs

namespace TestProject;

/// <summary>
/// MAUI 프로그램
/// </summary>
public static class MauiProgram
{
    //////////////////////////////////////////////////////////////////////////////////////////////////// Method
    ////////////////////////////////////////////////////////////////////////////////////////// Static
    //////////////////////////////////////////////////////////////////////////////// Public

    #region MAUI 앱 생성하기 - CreateMauiApp()

    /// <summary>
    /// MAUI 앱 생성하기
    /// </summary>
    /// <returns>MAUI 앱</returns>
    public static MauiApp CreateMauiApp()
    {
        MauiAppBuilder builder = MauiApp.CreateBuilder();

        builder
            .UseMauiApp<App>()
            .ConfigureFonts
            (
                fontCollection =>
                {
                    fontCollection.AddFont("OpenSans-Regular.ttf" , "OpenSansRegular" );
                    fontCollection.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
                }
            );

        string databaseFilePath = FileHelper.GetDatabaseFilePath("people.db3");

        builder.Services.AddSingleton<PersonRepository>
        (
            serviceProvider => ActivatorUtilities.CreateInstance<PersonRepository>(serviceProvider, databaseFilePath)
        );

        return builder.Build();
    }

    #endregion
}
728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요