연습: ClickOnce 배포 API를 통해 주문형 어셈블리 다운로드

기본적으로 ClickOnce 애플리케이션에 포함된 모든 어셈블리는 애플리케이션이 처음 실행될 때 다운로드됩니다. 그러나 소수의 사용자가 사용하는 일부 애플리케이션이 있을 수 있습니다. 이 경우 해당 형식 중 하나를 만들 때에만 어셈블리를 다운로드하고자 할 수 있습니다. 다음 연습에서는 애플리케이션의 특정 어셈블리를 "선택 사항"으로 표시하는 방법 및 CLR(공용 언어 런타임)에서 요청할 때 System.Deployment.Application 네임스페이스에 있는 클래스를 사용하여 이를 다운로드하는 방법을 설명합니다.

참고

System.Deployment.Application 네임스페이스의 ApplicationDeployment 클래스 및 API는 .NET Core 및 .NET 5 이상 버전에서 지원되지 않습니다. .NET 7에서 애플리케이션 배포 속성에 액세스하는 새로운 방법을 지원합니다. 자세한 내용은 .NET에서 ClickOnce 배포 속성 액세스를 참조하세요. .NET 7은 ApplicationDeployment 메서드와 동등한 메서드를 지원하지 않습니다.

참고 항목

이 절차를 사용하려면 완전 신뢰 상태에서 애플리케이션을 실행해야 합니다.

사전 요구 사항

이 연습을 완료하려면 다음 구성 요소 중 하나가 필요합니다.

  • Windows SDK. Windows SDK는 Microsoft 다운로드 센터에서 다운로드할 수 있습니다.

  • Visual Studio.

프로젝트 만들기

주문형 어셈블리를 사용하는 프로젝트를 만들려면

  1. ClickOnceOnDemand라는 디렉터리를 만듭니다.

  2. Windows SDK 명령 프롬프트 또는 Visual Studio 명령 프롬프트를 엽니다.

  3. ClickOnceOnDemand 디렉터리로 변경합니다.

  4. 다음 명령을 사용하여 퍼블릭/프라이빗 키 쌍을 생성합니다.

    sn -k TestKey.snk
    
  5. 메모장 또는 다른 텍스트 편집기를 사용하여 Message라는 단일 속성을 사용하여 DynamicClass라는 클래스를 정의합니다.

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace Microsoft.Samples.ClickOnceOnDemand
    {
        public class DynamicClass
        {
            public DynamicClass() {}
    
            public string Message
            {
                get
                {
                    return ("Hello, world!");
                }
            }
        }
    }
    
  6. 사용하는 언어에 따라 ClickOnceLibrary.cs 또는 ClickOnceLibrary.vb라는 파일로 텍스트를 ClickOnceOnDemand 디렉터리에 저장합니다.

  7. 파일을 어셈블리로 컴파일합니다.

    csc /target:library /keyfile:TestKey.snk ClickOnceLibrary.cs
    
  8. 어셈블리를 위한 퍼블릭 키 토큰을 얻으려면 다음 명령을 사용합니다.

    sn -T ClickOnceLibrary.dll
    
  9. 텍스트 편집기를 사용하여 새 파일을 만들고 다음 코드를 입력합니다. 이 코드는 필요한 경우 ClickOnceLibrary 어셈블리를 다운로드하는 Windows Forms 애플리케이션을 만듭니다.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Reflection;
    using System.Deployment.Application;
    using Microsoft.Samples.ClickOnceOnDemand;
    
    namespace ClickOnceOnDemand
    {
        [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Unrestricted=true)]
        public class Form1 : Form
        {
            // Maintain a dictionary mapping DLL names to download file groups. This is trivial for this sample,
            // but will be important in real-world applications where a feature is spread across multiple DLLs,
            // and you want to download all DLLs for that feature in one shot. 
            Dictionary<String, String> DllMapping = new Dictionary<String, String>();
    
            public static void Main()
            {
                Form1 NewForm = new Form1();
                Application.Run(NewForm);
            }
    
            public Form1()
            {
                // Configure form. 
                this.Size = new Size(500, 200);
                Button getAssemblyButton = new Button();
                getAssemblyButton.Size = new Size(130, getAssemblyButton.Size.Height);
                getAssemblyButton.Text = "Test Assembly";
                getAssemblyButton.Location = new Point(50, 50);
                this.Controls.Add(getAssemblyButton);
                getAssemblyButton.Click += new EventHandler(getAssemblyButton_Click);
    
                DllMapping["ClickOnceLibrary"] = "ClickOnceLibrary";
                AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
            }
    
            /*
             * Use ClickOnce APIs to download the assembly on demand.
             */
            private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
            {
                Assembly newAssembly = null;
    
                if (ApplicationDeployment.IsNetworkDeployed)
                {
                    ApplicationDeployment deploy = ApplicationDeployment.CurrentDeployment;
    
                    // Get the DLL name from the Name argument.
                    string[] nameParts = args.Name.Split(',');
                    string dllName = nameParts[0];
                    string downloadGroupName = DllMapping[dllName];
    
                    try
                    {
                        deploy.DownloadFileGroup(downloadGroupName);
                    }
                    catch (DeploymentException de)
                    {
                        MessageBox.Show("Downloading file group failed. Group name: " + downloadGroupName + "; DLL name: " + args.Name);
                        throw (de);
                    }
    
                    // Load the assembly.
                    // Assembly.Load() doesn't work here, as the previous failure to load the assembly
                    // is cached by the CLR. LoadFrom() is not recommended. Use LoadFile() instead.
                    try
                    {
                        newAssembly = Assembly.LoadFile(Application.StartupPath + @"\" + dllName + ".dll," +  
                "Version=1.0.0.0, Culture=en, PublicKeyToken=03689116d3a4ae33");
                    }
                    catch (Exception e)
                    {
                        throw (e);
                    }
                }
                else
                {
                    //Major error - not running under ClickOnce, but missing assembly. Don't know how to recover.
                    throw (new Exception("Cannot load assemblies dynamically - application is not deployed using ClickOnce."));
                }
    
    
                return (newAssembly);
            }
    
            private void getAssemblyButton_Click(object sender, EventArgs e)
            {
                DynamicClass dc = new DynamicClass();
                MessageBox.Show("Message: " + dc.Message);
            }
        }
    }
    
  10. 코드에서 LoadFile에 대한 호출을 찾습니다.

  11. PublicKeyToken을 이전에 검색한 값으로 설정합니다.

  12. 파일을 Form1.cs 또는 Form1.vb로 저장합니다.

  13. 다음 명령을 사용하여 실행 파일로 컴파일합니다.

    csc /target:exe /reference:ClickOnceLibrary.dll Form1.cs
    

어셈블리를 선택 사항으로 표시

MageUI.exe를 사용하여 ClickOnce 애플리케이션에서 어셈블리를 선택 사항으로 표시하려면

  1. MageUI.exe를 사용하여 연습: ClickOnce 애플리케이션 수동으로 배포에 설명된 대로 애플리케이션 매니페스트를 만듭니다. 애플리케이션 매니페스트에 대해 다음 설정을 사용합니다.

    • 애플리케이션 매니페스트의 이름을 ClickOnceOnDemand 로 지정합니다.

    • 파일 페이지의 ClickOnceLibrary.dll 행에서 파일 형식 열을 없음으로 설정합니다.

    • 파일 페이지의 ClickOnceLibrary.dll 행에서 Group 열에 ClickOnceLibrary.dll을 입력합니다.

  2. MageUI.exe를 사용하여 연습: ClickOnce 애플리케이션 수동으로 배포에 설명된 대로 배포 매니페스트를 만듭니다. 배포 매니페스트에 대해 다음 설정을 사용합니다.

    • 배포 매니페스트의 이름을 ClickOnceOnDemand로 지정합니다.

새 어셈블리 테스트

요청 시 어셈블리를 테스트하려면

  1. 웹 서버에 ClickOnce 배포를 업로드합니다.

  2. 배포 매니페스트에 URL을 입력하여 웹 브라우저에서 ClickOnce로 배포된 애플리케이션을 시작합니다. ClickOnce 애플리케이션 ClickOnceOnDemand를 호출하고 adatum.com의 루트 디렉터리에 업로드하면 URL은 다음과 같습니다.

    http://www.adatum.com/ClickOnceOnDemand/ClickOnceOnDemand.application
    
  3. 기본 폼이 나타나면 Button을 누릅니다. 메시지 상자 창에 "Hello, World!"라는 문자열이 표시되어야 합니다.