Microsoft MVP성태의 닷넷 이야기
.NET Framework: 131. ClickOnce - 그룹화시켜 다운로드 [링크 복사], [링크+제목 복사],
조회: 25431
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

ClickOnce - 그룹화시켜 다운로드


클릭원스 해보신 분들치고 이 방법을 모르는 분은 거의 없을 것입니다. 프로젝트가 진행되면서 자연스럽게 다운로드 모듈이 많아지고 그렇게 되면 초기 로딩 시간이 느려지는 것 때문에, 필요하지 않은 모듈들을 적절하게 "그룹화"시켜서 필요할 때만 다운로드하도록 만들게 됩니다.

오늘은 이에 대해 설명할 텐데, 아래의 MSDN 도움말에 너무 잘 설명되어 있습니다.

Visual Studio에서의 배포
연습: 디자이너를 사용하여 ClickOnce 배포 API에서 요청 시 어셈블리 다운로드
; https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2015/deployment/walkthrough-downloading-assemblies-on-demand-with-the-clickonce-deployment-api-using-the-designer

즉, 이번 내용은 요약본 정도라고 보면 되겠지요. ^^




테스트를 위해 2개의 프로젝트를 생성하겠습니다.

  • WpfApplication1 (EXE)
  • ClassLibrary1 (Library)

WpfApplication1은 ClassLibrary1 프로젝트를 참조하고 있으며, 런타임 시에 다음과 같이 "시작" 버튼이 눌린 경우에만 "ClassLibrary1.dll"을 다운로드해서 실행시키는 것이 목표입니다. 간단하지요. ^^

[그림 1: 동적 다운로드될 어셈블리의 코드를 실행하는 버튼]
clickonce_group_download_1.png

버튼 이벤트의 코드는 그냥 확인 차원에서 다음과 같이 ClassLibrary1에서 제공되는 클래스의 메서드만을 사용해 줍니다.

[그림 2: 버튼 이벤트 핸들러]
clickonce_group_download_2.png

이제, 실행하고 빌드 오류가 없음을 확인하는 정도로만 끝냅니다.




테스트 프로젝트는 완성되었으니, 이제 클릭원스에서 분할 배포를 위한 설정 및 코드를 구현해야 합니다. WpfApplication1 프로젝트에 "System.Deployment" 어셈블리를 참조하고, 다음과 같이 App.xaml.cs 코드를 구성합니다.

public partial class App : Application
{
    public App()
    {
        AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
    }

    public string BinaryPath
    {
        get
        {
            string toolPath = typeof(App).Assembly.Location;
            return System.IO.Path.GetDirectoryName(toolPath);
        }
    }

    System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
    {
        Assembly newAssembly = null;


        if (ApplicationDeployment.IsNetworkDeployed)
        {
            ApplicationDeployment deploy = ApplicationDeployment.CurrentDeployment;

            string downloadGroupName = "MyTestGroup";

            try
            {
                deploy.DownloadFileGroup(downloadGroupName);
            }
            catch (DeploymentException de)
            {
                MessageBox.Show("Downloading file group failed. Group name: " + downloadGroupName + "; DLL name: " + args.Name);
                throw (de);
            }

            try
            {
                newAssembly = Assembly.LoadFile(this.BinaryPath + @"\ClassLibrary1.dll");
            }
            catch (Exception e)
            {
                throw (e);
            }
        }
        else
        {
            throw (new Exception("Cannot load assemblies dynamically - application is not deployed using ClickOnce."));
        }


        return (newAssembly);
    }
}

과정은 매우 간단합니다. 보시는 것처럼, AppDomain.CurrentDomain.AssemblyResolve 이벤트가 발생하면 별도의 다운로드 그룹으로 설정되어 묶여진 어셈블리들을 다운로드하는데, 예제에서는 이 그룹 이름을 "MyTestGroup"로 설정했습니다. 정상적으로 그룹 다운로드가 되었으면 Assembly.LoadFile을 이용해서 DLL을 로드하면 되고.

코드는 이것으로 끝입니다. 나머지는 Visual Studio에서 "ClassLibrary1.dll"을 "MyTestGroup"이라는 별도의 그룹으로 "표시"만 해주면 되는데요. 이 과정은 프로젝트 속성창에의 "Publish" 탭에서 "Application Files..." 버튼을 눌러 [그림 3]에서 보는 것과 같이 "Download Group"을 지정하면 됩니다.

[그림 3: 어셈블리 배포 그룹 단위 설정]
clickonce_group_download_3.png

테스트 한번 해볼까요? ^^

배포를 하고 웹 브라우저에 *.application 배포 주소를 입력해서 실행시키면 사용자 단위의 "C:\Users\[사용자계정]\AppData\Local\Apps\2.0" 폴더에 응용 프로그램이 다운로드가 됩니다. 시작 버튼을 누르기 전에는 아래와 같이 ClassLibrary1.dll이 내려와 있지 않는 것을 확인할 수 있습니다.

[그림 4: C:\Users\[사용자 계정]\AppData\Local\Apps\2.0 하위 폴더 내용]
clickonce_group_download_4.png

하지만 "시작" 버튼을 누르고 나면 "ClassLibrary1.dll"어셈블리가 "AssemblyResolve" 이벤트 핸들러에 작성된 코드 덕분에 내려오게 되고 모듈은 정상적으로 실행을 계속합니다.

[그림 5: 요청 시 다운로드한 ClassLibrary1.dll]
clickonce_group_download_5.png

사실, 위와 같은 과정에서 ApplicationDeployment.DownloadFileGroup 메서드에서 제공되는 기능은 그동안 많은 개발자들에 의해서 중복해서 만들어진 부분이었죠. 이 부분을 마이크로소프트에서 떠안아서 가니 나쁘진 않습니다.

그룹에 포함된 어셈블리를 찾는 규칙을 실험 삼아서 해보니 재미있는 점이 있습니다.
Publish로 새롭게 업데이트되면 ClassLibrary1.dll 자체가 변경되지 않아도 "AssemblyResolve" 이벤트가 발생합니다. 이때 서버의 배포 폴더에 해당 DLL의 유무는 상관이 없습니다. 왜냐하면, 이전에 클라이언트 측에 배포된 폴더의 "ClassLibrary1.dll" 파일을 ApplicationDeployment.DownloadFileGroup 메서드에서 로드해서 처리하기 때문입니다. 물론, 만약 ClassLibrary1.dll 파일이 업데이트된 경우였다면 서버에 새로운 hash값과 일치하는 어셈블리가 없다면 오류가 발생합니다. 즉, 클라이언트 측에 다운로드했던 이전 버전으로는 대체가 안 된다는 것!!!

그 의미는 곧, 새롭게 Publish해서 생성되는 폴더에는 변경되지 않은 어셈블리는 굳이 복사해 놓지 않아도 된다는 것입니다. (복사해 놓았다고 해도 상관은 없습니다. 어차피 사용하지 않으니까.) 이 정도면 굳이 힘들게 제작할 필요 없이 ApplicationDeployment.DownloadFileGroup에 다운로드 기능을 맡겨도 좋을 것 같습니다. ^^

다운로드: 예제 솔루션





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

[연관 글]






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

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

비밀번호

댓글 작성자
 




... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11224정성태6/13/201718195.NET Framework: 661. Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법파일 다운로드1
11223정성태6/12/201716836개발 환경 구성: 318. WCF Service Application과 WCFTestClient.exe
11222정성태6/10/201720562오류 유형: 399. WCF - A property with the name 'UriTemplateMatchResults' already exists.파일 다운로드1
11221정성태6/10/201717552오류 유형: 398. Fakes - Assembly 'Jennifer5.Fakes' with identity '[...].Fakes, [...]' uses '[...]' which has a higher version than referenced assembly '[...]' with identity '[...]'
11220정성태6/10/201722919.NET Framework: 660. Shallow Copy와 Deep Copy [1]파일 다운로드2
11219정성태6/7/201718231.NET Framework: 659. 닷넷 - TypeForwardedFrom / TypeForwardedTo 특성의 사용법
11218정성태6/1/201721054개발 환경 구성: 317. Hyper-V 내의 VM에서 다시 Hyper-V를 설치: Nested Virtualization
11217정성태6/1/201716936오류 유형: 397. initerrlog: Could not open error log file 'C:\...\MSSQL12.MSSQLSERVER\MSSQL\Log\ERRORLOG'
11216정성태6/1/201719046오류 유형: 396. Activation context generation failed
11215정성태6/1/201720001오류 유형: 395. 관리 콘솔을 실행하면 "This app has been blocked for your protection" 오류 발생 [1]
11214정성태6/1/201717707오류 유형: 394. MSDTC 서비스 시작 시 -1073737712(0xC0001010) 오류와 함께 종료되는 문제 [1]
11213정성태5/26/201722498오류 유형: 393. TFS - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
11212정성태5/26/201721837오류 유형: 392. Windows Server 2016에 KB4019472 업데이트가 실패하는 경우
11211정성태5/26/201720865오류 유형: 391. BeginInvoke에 전달한 람다 함수에 CS1660 에러가 발생하는 경우
11210정성태5/25/201721313기타: 65. ActiveX 없는 전자 메일에 사용된 "개인정보 보호를 위해 암호화된 보안메일"의 암호화 방법
11209정성태5/25/201768247Windows: 143. Windows 10의 Recovery 파티션을 삭제 및 새로 생성하는 방법 [16]
11208정성태5/25/201727976오류 유형: 390. diskpart의 set id 명령어에서 "The specified type is not in the correct format." 오류 발생
11207정성태5/24/201728305Windows: 142. Windows 10의 복구 콘솔로 부팅하는 방법
11206정성태5/24/201721581오류 유형: 389. DISM.exe - The specified image in the specified wim is already mounted for read/write access.
11205정성태5/24/201721274.NET Framework: 658. C#의 tail call 구현은? [1]
11204정성태5/22/201730811개발 환경 구성: 316. 간단하게 살펴보는 Docker for Windows [7]
11203정성태5/19/201718742오류 유형: 388. docker - Host does not exist: "default"
11202정성태5/19/201719810오류 유형: 387. WPF - There is no registered CultureInfo with the IetfLanguageTag 'ug'.
11201정성태5/16/201722569오류 유형: 386. WPF - .NET 3.5 이하에서 TextBox에 한글 입력 시 TextChanged 이벤트의 비정상 종료 문제 [1]파일 다운로드1
11200정성태5/16/201719364오류 유형: 385. WPF - 폰트가 없어 System.IO.FileNotFoundException 예외가 발생하는 경우
11199정성태5/16/201721178.NET Framework: 657. CultureInfo.GetCultures가 반환하는 값
... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...