Redigera

Dela via


Walkthrough: Download 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

The ApplicationDeployment class and APIs in the System.Deployment.Application namespace are not supported in .NET Core and .NET 5 and later versions. In .NET 7, a new method of accessing application deployment properties is supported. For more information, see Access ClickOnce deployment properties in .NET. .NET 7 does not support the equivalent of ApplicationDeployment methods.

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 Reset settings.

Create 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.

    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.

    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. 
    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 void getAssemblyButton_Click(object sender, EventArgs e)
    {
        DynamicClass dc = new DynamicClass();
        MessageBox.Show("Message: " + dc.Message);
    }
    

Mark 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 deploy 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.

Test 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!"