次の方法で共有


Walkthrough: Downloading Assemblies on Demand with the ClickOnce Deployment API Using the Designer

By default, all the assemblies included in a ClickOnce application are downloaded when the application is first run. However, there might be parts of your application that are used by a small set of the users. In this case, you want to download an assembly only when you create one of its types. The following walkthrough demonstrates how to mark certain assemblies in your application as "optional", and how to download them by using classes in the System.Deployment.Application namespace when the common language runtime demands them.

Note

Your application will have to run in full trust to use this procedure.

Note

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, click Import and Export Settings on the Tools menu. For more information, see Customizing Development Settings in Visual Studio.

Creating the Projects

To create a project that uses an on-demand assembly with Visual Studio

  1. Create a new Windows Forms project in Visual Studio. On the File menu, point to Add, and then click New Project. Choose a Class Library project in the dialog box and name it ClickOnceLibrary.

    Note

    In Visual Basic, we recommend that you modify the project properties to change the root namespace for this project to Microsoft.Samples.ClickOnceOnDemand or to a namespace of your choice. For simplicity, the two projects in this walkthrough are in the same namespace.

  2. Define a class named DynamicClass with a single property named Message.

    Public Class DynamicClass
        Sub New()
    
        End Sub 
    
        Public ReadOnly Property Message() As String 
            Get
                Message = "Hello, world!" 
            End Get 
        End Property 
    End Class
    
    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!");
                }
            }
        }
    }
    
  3. Select the Windows Forms project in Solution Explorer. Add a reference to the System.Deployment.Application assembly and a project reference to the ClickOnceLibrary project.

    Note

    In Visual Basic, we recommend that you modify the project properties to change the root namespace for this project to Microsoft.Samples.ClickOnceOnDemand or to a namespace of your choice. For simplicity, the two projects in this walkthrough are located in the same namespace.

  4. Right-click the form, click View Code from the menu, and add the following references to the form.

    Imports System.Reflection
    Imports System.Deployment.Application
    Imports System.Collections.Generic
    Imports Microsoft.Samples.ClickOnceOnDemand
    Imports System.Security.Permissions
    
    using System.Reflection;
    using System.Deployment.Application;
    using Microsoft.Samples.ClickOnceOnDemand;
    using System.Security.Permissions;
    
  5. Add the following code to download this assembly on demand. This code shows how to map a set of assemblies to a group name using a generic Dictionary class. Because we are only downloading a single assembly in this walkthrough, there is only one assembly in our group. In a real application, you would likely want to download all assemblies related to a single feature in your application at the same time. The mapping table enables you to do this easily by associating all the DLLs that belong to a feature with a download group name.

    ' 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.  
    Dim DllMappingTable As New Dictionary(Of String, String)()
    
    <SecurityPermission(SecurityAction.Demand, ControlAppDomain:=True)> _
    Sub New()
        ' This call is required by the Windows Form Designer.
        InitializeComponent()
    
        ' Add any initialization after the InitializeComponent() call.
        DllMappingTable("ClickOnceLibrary") = "ClickOnceLibrary" 
    End Sub 
    
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, AddressOf Me.CurrentDomain_AssemblyResolve
    End Sub 
    
    Private Function CurrentDomain_AssemblyResolve(ByVal sender As Object, ByVal args As ResolveEventArgs) As System.Reflection.Assembly
        Dim NewAssembly As Assembly = Nothing 
    
        If (ApplicationDeployment.IsNetworkDeployed) Then 
            Dim Deploy As ApplicationDeployment = ApplicationDeployment.CurrentDeployment
    
            ' Get the DLL name from the argument. 
            Dim NameParts As String() = args.Name.Split(",")
            Dim DllName As String = NameParts(0)
            Dim DownloadGroupName As String = DllMappingTable(DllName)
    
            Try
                Deploy.DownloadFileGroup(DownloadGroupName)
            Catch ex As Exception
                MessageBox.Show("Could not download file group from Web server. Contact administrator. Group name: " & DownloadGroupName & "; DLL name: " & args.Name)
                Throw (ex)
            End Try 
    
            ' 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")
            Catch ex As Exception
                Throw (ex)
            End Try 
        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.")
        End If 
    
        Return NewAssembly
    End Function
    
    // 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>();
    
    [SecurityPermission(SecurityAction.Demand, ControlAppDomain=true)]
    public Form1()
    {
        InitializeComponent();
    
        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");
            }
            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);
    }
    
  6. On the View menu, click Toolbox. Drag a Button from the Toolbox onto the form. Double-click the button and add the following code to the Click event handler.

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim DC As New DynamicClass()
        MessageBox.Show("Message is " & DC.Message)
    End Sub
    
    private void getAssemblyButton_Click(object sender, EventArgs e)
    {
        DynamicClass dc = new DynamicClass();
        MessageBox.Show("Message: " + dc.Message);
    }
    

Marking Assemblies as Optional

To mark assemblies as optional in your ClickOnce application by using Visual Studio

  1. Right-click the Windows Forms project in Solution Explorer and click Properties. Select the Publish tab.

  2. Click the Application Files button.

  3. Find the listing for ClickOnceLibrary.dll. Set the Publish Status drop-down box to Include.

  4. Expand the Group drop-down box and select New. Enter the name ClickOnceLibrary as the new group name.

  5. Continue publishing your application as described in How to: Publish a ClickOnce Application using the Publish Wizard.

To mark assemblies as optional in your ClickOnce application by using Manifest Generation and Editing Tool — Graphical Client (MageUI.exe)

  1. Create your ClickOnce manifests as described in Walkthrough: Manually Deploying a ClickOnce Application.

  2. Before closing MageUI.exe, select the tab that contains your deployment's application manifest, and within that tab select the Files tab.

  3. Find ClickOnceLibrary.dll in the list of application files and set its File Type column to None. For the Group column, type ClickOnceLibrary.dll.

Testing the New Assembly

To test your on-demand assembly

  1. Start your application deployed with ClickOnce.

  2. When your main form appears, press the Button. You should see a string in a message box window that reads, "Hello, World!"

See Also

Reference

ApplicationDeployment