Export (0) Print
Expand All

Chapter 8: Deploying Applications

Visual Studio 2005
 

Microsoft Corporation

March 2006

Summary: Focus on how to use the new ClickOnce deployment technology and review how to build Microsoft Windows Installer packages by using the setup project templates and tools included in Visual Studio 2005. You'll also learn how to choose the right method for deploying applications. (34 printed pages)

Contents

Introduction
Application: User-Initiated Updates with ClickOnce
New Concepts
Configuring ClickOnce Properties
ClickOnce Security
Windows Installer Enhancements
Walkthrough
Conclusion

Introduction

As an application developer, you know the challenges of deploying an application. For that reason, you'll be pleasantly surprised by the new tools as well as the improved tools included in Microsoft Visual Studio 2005 for deploying applications. In this chapter, you'll focus specifically on how to use the new ClickOnce deployment technology. You'll also review how to build Microsoft Windows Installer packages by using the setup project templates and tools included in Visual Studio 2005. Along the way, you'll also learn how to choose the right method for deploying applications given the variety of scenarios you'll face as a Microsoft Visual Basic .NET application developer.

Application: User-Initiated Updates with ClickOnce

This application demonstrates how to add a user-initiated updating capability to a Windows Forms application by using the ClickOnce application programming interfaces (APIs).

New Concepts

In Visual Studio 2005, you have a choice of three primary deployment options: Web, ClickOnce, and Windows Installer packages. Using the MS-DOS XCopy command to move application files from one place to another is another option, and it remains the simplest and most direct deployment method. It is also the least flexible and is really appropriate only in a few situations—for example, when updating a Web application (and even that should be qualified to mean only deployments that don't require updates to the IIS metabase) or for installing private .NET assemblies.

ClickOnce is an integrated deployment technology introduced in Visual Studio 2005 that allows you to install and run Windows applications from a Web server with little or no user interaction. Windows Installer is an installation and configuration service that ships as a part of Microsoft Windows Server 2003, Windows XP, Windows 2000, and Windows Me (and it is also available for Windows 9x and Windows NT 4.0 as a separate download). You'll find the deployment tools in Visual Studio 2005 build on the foundation of Windows Installer, providing you with rich capabilities for rapidly deploying and updating applications.

Background

The collection of services that make up ClickOnce represent the evolution of technologies that began to emerge in the first version of the .NET Framework known as No-Touch deployment. When version 1.0 of the .NET Framework was released, it immediately solved a number of problems faced by developers. Managed applications built on the .NET Framework could benefit from application isolation and low-impact deployment (also known as XCopy deployment). The .NET Framework 1.0 also remedied the problem of "DLL Hell" (where the installation breaks existing software and potentially future software installations) by providing a new approach to sharing and versioning components. Eliminating DLL version problems also opened the door to new ways of thinking about deploying Windows desktop applications that can provide more features and deliver a richer user experience than a Web-based application.

No-Touch deployment emerged as a Web-based deployment method that allowed users equipped with Internet Explorer 5.01 or later to download and install Windows desktop applications from a URL and run them on their local machine without running a typical Setup.exe. Also known as "href-exes," this deployment mechanism allowed you to combine the power of rich desktop applications with the deployment simplicity of Web applications.

Unfortunately, running applications directly from a Web location also has its limitations. First, by their very nature, applications launched from a Web page are available only online and are therefore at the mercy of network connectivity. Another significant problem with href-exes exists in the area of security. To run, applications more likely than not require changes to the default security policy on the client. In earlier versions of Visual Studio, it was virtually impossible for developers to determine the permissions needed for an application at design time. And no doubt many No-Touch deployments were dashed against the rocks of unforeseen security restrictions that rendered them unusable in production. An additional limitation of No-Touch deployments was that it provided no standard mechanism for managing versions of releases.

ClickOnce protects the user's machine and applications. When ClickOnce downloads and installs a program, it does not modify any files other than its own. You can set an update policy, and updates are managed using the .NET Framework versioning mechanism. In this section, you'll look at an application that illustrates using the ClickOnce deployment APIs to allow users to automatically update a Windows desktop application. But before examining the implementation details, let's review what's new with ClickOnce and how it fits within the spectrum of deployment capabilities you have to choose from with Visual Studio 2005. You'll also look in detail at how easy it is to implement ClickOnce deployment and automatic updating declaratively.

Note   As you'll learn in more detail when we discuss ClickOnce security, the tools provided in the Visual Studio 2005 IDE remove the guesswork from calculating and configuring security requirements for a Web-distributed rich-client application. This is a huge step forward in realizing the early promise of No-Touch deployment.

Code Access Security

Code Access Security (CAS) is a feature of the common language runtime (CLR) that enforces security based on the identity of code. As a developer, you probably won't work with CAS as part of your daily routine because the infrastructure for securing code is built in to the .NET Framework libraries. However, to make the right decisions about the security requirements for your applications, it is essential that you understand CAS— particularly how the .NET Framework handles evidence, permissions, and code groups. Equally important is that you address security issues early and often during the life cycle of a development project. A thorough discussion of CAS is beyond the scope of this book. To learn more, visit the MSDN Web site, which contains a number of articles on security issues in general and CAS in particular; or read any of a number of books specifically devoted to .NET Framework security, such as Writing Secure Code, 2nd Edition, by Michael Howard and David LeBlanc (Microsoft Press, 2003) or .NET Framework Security, by Brian A. LaMacchia, et al. (Addison-Wesley, 2002).

Advantages of ClickOnce

Building on the foundation of this earlier initiative, ClickOnce has been designed to address a number of obstacles associated with other deployment methods.

  • Automatic / Self-Service Updating: No-Touch Deployment introduced Web-based installation of desktop applications. ClickOnce extends this capability to provide a mechanism for automatically updating applications or for allowing users to update their applications at their own discretion. Updates are also applied without requiring the user to reinstall the entire application.
  • Self-Contained Applications: To avoid the versioning conflicts sometimes associated with applications using shared components, ClickOnce deploys applications as self-contained entities that won't interfere with other applications. This means that applications installed through ClickOnce won't be broken by later application installs.
  • Nonadministrator Installs: Windows Installer applications will run only under administrative permissions. ClickOnce applications can be installed under accounts with reduced permissions, and they are granted rights only as required to run the application.
  • Offline Access: Applications deployed using ClickOnce can be installed either to run online or locally. In the latter case, they are integrated with the Windows Shell, which includes adding a Start Menu shortcut to the application. This provides access anywhere and anytime to Web-deployed applications.
    Note   For versions 1.0 and 1.1 of the .NET Framework, Microsoft provides the Updater Application Block for .NET as a way to further extend the benefits of No-Touch deployment. Developed and released by the Microsoft Patterns and Practices group, this application block is available as a free download from MSDN, and includes documentation and custom .NET assemblies (with source code) for developers to add self-updating capabilities to their applications.

ClickOnce deployment also offers significant cost benefits in terms of money, time, and effort. Imagine how such savings can positively influence a critical decision point in your application designs: How many times have you built solutions as Web-based applications because you needed a way to easily deliver that application to a wide audience and you needed to be able to update the application quickly and easily? And if you're a developer working in a managed network environment, you face the additional obstacle of network administrators who are either unwilling or unable to support deploying updates that require an installation program to run on every client system on the network.

The bottom line is that for several good reasons, building solutions as Web-based applications has been the path of least resistance. Although advanced features and a rich user interface were sacrificed, Web applications were easier and cheaper and less of a headache to deploy and update. ClickOnce removes the need to make a tradeoff between functionality and ease-of-deployment because it brings the simplicity and reliability of Web-application deployment to rich-client applications.

None of this suggests that Web-based applications will become obsolete. They still provide the broadest reach for solutions that need to run on a wide variety of operating systems. A Windows Installer package remains the best choice for a full-featured client installation. In many scenarios, however, one can now look forward to delivering rich-client applications to users without having to face the deployment constraints that made that deployment modality an impractical option in the past.

At its core, ClickOnce is a set of new deployment features built into the .NET CLR. These features include a programmable interface as well as design-time support that are integrated into the Visual Studio 2005 IDE. Moreover, ClickOnce deployment functionality can be built directly into applications themselves, freeing you from the need to build a separate installation program.

Publishing a ClickOnce Application

ClickOnce technology is integrated in the Visual Studio 2005 IDE in two primary areas. The first place is in the Build menu, which includes a Publish menu item. The same command is also available from solution and project context menus in Solution Explorer. A third option for publishing within the Visual Studio 2005 IDE is to use command buttons available in the Publish pane of the Project Designer. (This represents the second key area of Visual Studio 2005 IDE integration with ClickOnce.) Selecting the Publish menu command (or clicking the Publish Wizard button in the Publish pane) launches a Publish Wizard (shown in Figure 8-1), a tool that guides you through the necessary steps required for publishing.

Aa730865.netvbdev0801(en-US,VS.80).gif

Figure 8-1. Publish Wizard.

The first page of the Publish Wizard asks you to select a location for the application. The other steps in the wizard similarly allow you to change other deployment settings (for example, install mode and how users will install the application, as well as selecting a public/private key required for signing the application and deployment manifests). If you need to make a change, click the Next button to advance through the wizard. Once you're finished updating the settings, click Finish.

Note   The deployment manifest is an XML file that describes a ClickOnce application deployment, including the current version of the deployment, update configuration settings, and most importantly, the current version of the ClickOnce application's application manifest.
Note   The application manifest is an XML file that identifies the application being deployed using ClickOnce, including the identity of the application's primary assembly, its security requirements, a list of nonassembly files used by the application, as well as any dependencies necessary for the application to run.

When you publish an application for the first time, Visual Studio 2005 creates a new folder in the solution named publish and stores the files necessary to install the application in that directory, including the deployment manifest and a bootstrapper program containing the application prerequisites. It also generates a Web page with links to the program installation and the prerequisites. If you specified a Web site as the publish location, the ClickOnce publish engine creates a virtual directory on the target Web server and copies the files from the local publish folder to that location. Finally, ClickOnce opens the publish page in a Web browser as shown in Figure 8-2.

Aa730865.netvbdev0802(en-US,VS.80).gif

Figure 8-2. Publish page.

Installing and Running a ClickOnce Application

If the application is deployed for offline use (this is the default install mode), clicking the Install button begins an installation of the application on the user's machine. If the application is configured for online use only, it will be launched directly from the publish page. Figure 8-3 shows the security confirmation message you receive when you attempt to install the application.

Aa730865.netvbdev0803(en-US,VS.80).gif

Figure 8-3. Installation confirmation dialog box.

After a user clicks the Install button, the application is installed to a local folder on the user's machine. Following successful installation, the ClickOnce subsystem then automatically runs the application from the local installation directory.

Note   For click-once deployment to work correctly, you may need to add the following MIME types to Internet Information Server:
.application application/x-ms-application
.deploy application/octet-stream
.manifestapplication/x-ms-manifest

Updating a ClickOnce Application

To deliver updates to your application, the procedure is the same as it is for publishing the original version of an application. The only thing you need to do prior to publishing the update is increment the version number of your application. You can increment the publish version automatically or manually. By default, the publish version is set to automatically increment the revision number every time you publish the application. As illustrated in Figure 8-4, however, you can clear the Automatically Increment Revision With Each Release check box to set this value manually.

Aa730865.netvbdev0804(en-US,VS.80).gif

Figure 8-4. Publish Version.

It is important to note that the publish version is entirely independent from the version number of the application assembly. If the application is configured to automatically increment the version with each release, the easiest way to publish the new version of a ClickOnce application is to click the Publish Now button in the Publish pane of the Project Designer. The publishing subsystem compiles the updated application and stores the assembly and its associated application manifest in a new folder in the publish location. It also updates the deployment manifest to point to the new application manifest. The next time a user opens the application (and assuming the application is configured to check for updates), the ClickOnce run time on the user's machine finds the new version and either notifies the user that an update is available or installs it automatically.

Figure 8-5 shows a typical update notification dialog box. In this example, you have the option to either install the updated version of the application or skip the update. You can control whether a user has the option to reject updates in the update configuration settings for the ClickOnce application.

Aa730865.netvbdev0805(en-US,VS.80).gif

Figure 8-5. Update notification.

To better understand how a ClickOnce application knows when an update to your application is available, examine the files and folders shown in Figure 8-6. This illustrates a typical update scenario where the original version of the application, stored in the folder WeatherReport_1.0.0.0, has been updated with a newer version stored in the folder WeatherReport_1.0.0.1.

Aa730865.netvbdev0806(en-US,VS.80).gif

Figure 8-6. Published application files.

The deployment manifest (the file WeatherReport.application shown in Figure 8-6) contains an entry for the latest version of the application. When an application checks for updates, ClickOnce looks at the deployment manifest and compares that to the current version of the application. If the available version is newer than the current version of the application, and depending on how you configure the update application settings, ClickOnce either displays a message prompt informing the user that an update is available or automatically updates the application.

Figure 8-7 illustrates this process. The server includes the application files for both the original version of the application and an updated version (1.0.0.1). The deployment manifest shows that a newer version of the application is available. When the installed application performs an update check, it will read the deployment manifest and know that an update is available.

Aa730865.netvbdev0807(en-US,VS.80).gif

Figure 8-7. Update check.

Configuring ClickOnce Properties

While the default ClickOnce settings might be appropriate in some situations, you will need to become familiar with the Publish pane of the Project Designer to control different deployment scenarios. The settings in the Publish pane allow you to configure advanced deployment options, configure a variety of update scenarios, add application prerequisites to the ClickOnce application, and manage how the files included in the application itself are treated within the application manifest.

Note   For more information on the Visual Studio 2005 Project Designer, see Chapter 3, "Visual Studio 2005 Integrated Development Environment."

Aa730865.netvbdev0808(en-US,VS.80).gif

Figure 8-8. Publish pane of the Project Designer.

Publishing Location

The publishing location can be a Web site, an FTP site, a file share, or the path to a disk. Selecting a disk path would be an appropriate option if your intention is to distribute the application on removable media such as a CD. Using a network file share or ftp server as the publishing location is a good alternative in cases where the target Web server is not configured to use Microsoft Front Page server extensions (a requirement for publishing to a Web site).

If the installation URL is different than the publishing location, in the Publish pane specify that address in the Installation URL text box. For example, if you publish to an internal Web site and the application is intended for Internet users, this would be the place to specify the external address. Another scenario in which you will need to specify a separate installation URL is if the publishing location is a file share or an ftp server.

You can also include a reference to Web-based help or other supporting documentation for the application by setting the URL in the Support URL from the Options button. If you enter an address for this property, it appears as a link on the publish page generated when you publish the application.

Install Mode

Install mode defines the deployment as either an installed application or a launched application. Table 8-1 summarizes the primary characteristics of each option.

Table 8-1. Install Mode Options

InstalledLaunched
Installed from Web, CD/DVD, or Network shareRuns directly from Web or Network share
Shell integration (entry added to Add or Remove Programs, Start menu presence)No shell integration
Available offlineAvailable online only
Variety of application update strategiesAlways runs the most recent version of the application

A ClickOnce installed application has the same basic properties as a traditionally installed Windows application. ClickOnce adds a program shortcut to the Start menu, and the application appears in the local Add or Remove Programs applet; therefore, it can be uninstalled like any other program or rolled back to a previous version.

You can set the Install Mode either in the Publish Wizard or in the Publish pane of the Project Designer. In the Publish pane, the section titled Install Mode And Settings contains two options. Select one of these options:

  • The Application Is Available Online or Offline Only
  • The Application Is Only Available Online
Note   Support for version rollback is limited to one prior version of the ClickOnce application.

A ClickOnce launched application executes from its published Web page. This gives it the "feel" of an href-exe—no shortcuts are added to the Start menu, and the application does not appear in Add or Remove Programs. However, while it might seem to users that applications deployed in this way are running from the source Web location, they are actually cached locally in a fashion similar to Web page caching and toward the same goal of reducing network traffic to improve application performance. This type of application caching was first introduced with No-Touch deployments, where the application executable is downloaded to the local machine's assembly download cache.

Publish Options

The Publish pane includes four button controls to access dialog boxes for manipulating additional publishing properties. If you click the bottom-most button, Options, this opens a Publish Options dialog box, which is shown in Figure 8-9.

Aa730865.netvbdev0809(en-US,VS.80).gif

Figure 8-9. Publish Options dialog box.

  • Publish Language: The Publish Language property controls the language of user interface items displayed during installation of the ClickOnce application. If this property is set to Default, the installation uses the culture and language settings on the user's computer. If you are publishing a localized version of the ClickOnce application, change this property to the language and culture matching the localization settings for the application.
  • Deployment Web Page: When you publish the first version of a ClickOnce application, the publishing engine creates an HTML page called publish.htm. The page displays the name of the Click-Once application and links for installing the application and (if specified) any prerequisites or supporting documentation, as well as a link to an MSDN ClickOnce help topic. This page is copied along with the ClickOnce application files to the publish location as part of the publishing process.

If you publish subsequent versions of the application, the publish page is not overwritten. That means you can customize the page after you have published it by using any HTML editor without having to worry about losing those changes later on.

The Publish Options dialog box allows you to change the name of the publish page from the default publish.htm. You can also disable opening this page in a Web browser after publishing by clearing the Open deployment web page after publish check box.

Determining Application Update Requirements

Give careful thought to update requirements before deploying version 1 of your application because the choices you make will be in effect when it comes time to release version 2. For example, if you configure version 1 of a ClickOnce application to check for updates in the background while the application is running and then, when you're preparing version 2 of the application, you decide you'd rather check for updates before the application launches, the change will not be applied until after version 2 is successfully installed.

Or consider how you might address a common update scenario by asking the question, "Do I need users to always have the most recent version of my application?" Depending on how you answer that question for any particular application, you can choose an update strategy that is relaxed in how it delivers updates or use a more rigorous approach that ensures users always have the most recent version of your application.

By default, a ClickOnce application looks for updates before the application starts. If an update is in fact available, a prompt appears asking her to install the update. This is an example of a fairly strict approach to updating because the user is prompted before the application will be allowed to run. You can change this behavior to check for updates after the application starts. In this case, when an update is available the update prompt appears after the application runs.

Configuring Automatic Update Options

While prompting a user might work in some cases, other situations will arise where updates are mandatory. An obvious example is if your application is sending data to a server and the data model is later modified on the server side; an out-of-date client runs the risk of sending bad data to the server. You can configure your application for updates as outlined in the following steps:

  1. Click the Updates button on the Publish pane of the Project Designer. This opens the Application Updates dialog box, shown in Figure 8-10.
  2. Select The Application Should Check For Updates check box.
  3. To choose when the application should check for updates, select Before The Application Starts, or After the Application Starts.
  4. To force an update, you can set the minimum required version.

    Aa730865.netvbdev0810(en-US,VS.80).gif

    Figure 8-10. Applications Updates dialog box.

Note   Remember, configuring application updates is necessary only for locally installed ClickOnce applications. If the application is configured to launch online, updates are by definition automatically delivered (that is, they work exactly the same way as Web page updates).

Setting Update Check Intervals

Unless configured otherwise, a ClickOnce-enabled application checks for updates every time it runs. You can change this behavior to a specified time interval—every two weeks, for example. This is a sensible option if the application doesn't require users to immediately receive the latest application update. Spacing automated update checks over longer time periods can be a good strategy if you also implement user-initiated updating to allow users to check for updates from within the application itself. (You'll look at how to implement user-initiated update checking later in the "Walkthrough" section of this chapter.)

Consider Your Bandwidth

The quality of the network connection used by your ClickOnce application should be a factor in determining a strategy for checking for updates. If your network has high-bandwidth, it is appropriate to check for updates before the application starts. On the other hand, if the network is slow, this can lead to very slow load times for your application. In this case (and if it is acceptable for users to temporarily use an outdated version of the application), a better option is to check for updates while the application is running to allow the .NET Framework to perform the update check on a background thread.

Application Prerequisites

ClickOnce applications require that the correct version of the .NET Framework be installed on a computer before they will run. Additionally, as with a standard installation program, a ClickOnce application might require additional software components. If the application uses the latest version of Microsoft Data Access Components (MDAC) or Microsoft DirectX, for example, you can include them in the ClickOnce deployment as a separate installation program that gets published with the ClickOnce application. Providing a separate installation program for application prerequisites is commonly referred to as bootstrapping. A bootstrapper has the following key features:

  • It's a lightweight installation program that installs only the components that are needed on the target machine.
  • It supports standard setup EXEs and Windows Installer installation packages (.msi files).
  • It supports automatic rebooting and resumption.
  • It's easy to add redistributable packages to the list of available prerequisites.

The bootstrapper bridges the gap between ClickOnce and higher impact software installations. The bootstrapper can also be useful in a corporate setting where you have .NET components built in-house that are shared across various applications and need to be installed in the global assembly cache (GAC). Because ClickOnce application files can be installed only to the local application cache, assemblies destined for the GAC must be installed using a Windows Installer installation package (.msi file) added to the application prerequisites. A caveat to bear in mind is that the bootstrapper requires Full Trust permissions. Your users will need administrative permissions to install components included in the bootstrapper regardless of the security level specified by the ClickOnce application itself.

To configure which installation components to include in the bootstrapper, use the Prerequisites dialog box, which provides a list of available redistribution packages. (See Figure 8-11.) By default, the Microsoft .NET Framework 2.0 redistributable package (Dotnetfx.exe) is preselected. This is a bootstrapper utility that will automatically download and install the .NET Framework if it is not present on the user's machine. The dialog box lets you choose to download the prerequisites from the vendors' web site, the same location as the application, or specify another location for download. Using a different location would be a good choice if your organization uses a common set of prerequisites and you want to conserve disk space on your deployment server as well as make sure every application receives the same version of the prerequisites.

Note   Prerequisites are extensible—you can add your own Windows Installer .msi files or other third-party redistribution packages to the bootstrapper program. For details, see the MSDN Library for the Visual Studio 2005 article "How to: Add Your Own Prerequisites to a ClickOnce Application."

Aa730865.netvbdev0811(en-US,VS.80).gif

Figure 8-11. Prerequisites dialog box.

When you publish the application, the prerequisites are bundled together into the bootstrapper setup program. The resulting publish Web page contains separate links for installing the ClickOnce application and the bootstrapper program.

Warning   Prerequisites cannot be updated using the auto-update feature of ClickOnce. Only the application itself is a candidate for updates.

Application Files

When you publish a ClickOnce application, all the files in the project get published along with the application. In certain situations, the project might contain files necessary for development but that you don't want to include in the deployment. In other cases, you might want to maximize application performance and installation time by specifying that certain files will be installed based only on conditions you can control. Using the Application Files dialog box in the Publish pane, you can exclude files, mark files as data files or as prerequisites, and create groups of files that download only when they are needed by the application.

Figure 8-12 illustrates how the Application Files dialog box can be used to group required and optional files. The file located at the top of the list (OnDemand.exe) is identified as the entry point to the application and is a required component of the deployment. The application icon file (App.ico) is also categorized as a required item. The assemblies OrderListControl.dll and OrderLibary.dll, however, are assigned to a group titled "OnDemand". These files will be marked as optional in the application manifest and will not be installed when the application is first used.

Note   To install items that are marked as optional, you must include code in your ClickOnce application that recognizes when optional assemblies or other files are requested by the application. Your code must then call either the DownloadFiles or DownloadFilesAsync method of the System.Deployment.ApplicationDeployment class to install the needed files. For more information, see the "Walkthrough: Downloading Assemblies On Demand with the ClickOnce Deployment API" topic in the Visual Studio 2005 documentation.

Aa730865.netvbdev0812(en-US,VS.80).gif

Figure 8-12. Application Files dialog box.

When you first open the Application Files dialog box, the type column will show all needed files as Included (Auto) files. As shown in Figure 8-12, you can change the type of some of the files. The type options available in the drop-down list of the dialog box vary depending on the file type of the associated file. For example, .dll files can be designated Include, Exclude, or as a Prerequisite. Help files, on the other hand, can be marked as Include, Data File, or Exclude.

The third column in the Application Files dialog box lists the file groups for the application. Initially, the only group listed is [Required]. If you need to identify files that should be included in the deployment but downloaded only under certain conditions (that is, installed optionally), you should create additional file groups and assign files to them.

To add a new group, follow these steps:

  1. In the Application Files dialog box, select a file that you want to include in the new group.
  2. Click the drop-down list under the Group field and choose New. This causes a New Group dialog box to display.

The new group name is thereafter available for you to assign to other files in the list within the Application Files dialog box.

ClickOnce Security

Before you get too far along in thinking about using ClickOnce as a new way to deploy rich-client applications, you might start having concerns about what this means for security. ClickOnce provides a simplified deployment model for full-featured desktop applications. These applications could come from a variety of sources, and you might trust these sources to varying degrees. (For example, you probably trust applications on your intranet more than applications from the Internet.) In fact, ClickOnce has been engineered for deploying applications that are extremely safe and secure.

ClickOnce Applications Run in a Sandbox

By default, ClickOnce applications execute in a security sandbox. A sandbox is determined based on the .NET security policy installed on a particular user's machine and the location from which the ClickOnce application is installed or run. Table 8-2 lists the default permissions for ClickOnce applications based on the publish location.

Table 8-2. Security Zones for Publish Locations

Publish LocationSecurity Zone
Launched from Internet Web siteInternet Zone
Install from Internet Web siteInternet Zone
Install from intranet Web siteIntranet Zone
Install from network file shareIntranet Zone
Install from CD-ROMFull

The default security policy in the .NET Framework is highly restrictive. An application running under the default Internet Zone, for example, does not have access to local file resources, cannot connect to databases, and cannot communicate with outside Web resources, to cite just a few restrictions. As a practical matter, before you deploy a ClickOnce application you'll need to determine what Code Access Security (CAS) permissions the application requires to do its work. And then you'll need to configure the application to request those permissions on install.

Configuring ClickOnce Code Access Security

The Security pane in the Project Designer of the Visual Studio 2005 IDE provides an interface for configuring permissions for a ClickOnce application. If it is deployed over the Internet, it has default Internet security permissions. If it is deployed within an intranet, it has Local Intranet permissions. If it is deployed via any other means, it has Full Trust permissions. As described in the previous section, you can deploy a ClickOnce application using the default permissions, in which case you don't need to make any changes in the Security pane. In Internet or intranet deployment scenarios, the default permissions might be too limiting. Conversely, applications deployed with Full Trust enjoy unrestricted system access. In either case, however, as a best practice the application should contain only permissions that it actually needs to run. To help you achieve this goal, the Security pane provides an interface for customizing ClickOnce security settings, as shown in Figure 8-13.

Aa730865.netvbdev0813(en-US,VS.80).gif

Figure 8-13. Security pane of the Project Designer.

Before you can begin customizing security settings for ClickOnce, you need to select the Enable ClickOnce Security Settings check box. This activates a group of security-related controls in the Security pane. You begin the customization process by selecting either full trust, or partial trust. If you select partial trust, you can define the minimum permissions necessary to run the application. You select the zone that most closely matches the permissions required by your application and use this zone as a starting point for your permission set. Then, working in the table of permissions provided in the Security pane, you can further modify the permission set by either enabling or disabling individual permissions as necessary.

To modify a particular permission in the table, scroll to the row in which it is listed. The Setting column contains a drop-down list with three options: Include, Exclude, and Zone Default. Select Include to add the permission or Exclude to remove the permission. Selecting Zone Default resets the permission to its default state for the selected zone.

Figure 8-14 illustrates an example of manual configuration of permissions. The setting for the FileDialogPermission has been explicitly excluded from the permission set, while the FileIOPermission has been included. Notice the information icon appearing in the Included column; this icon indicates that the FileIOPermission requires a level of trust that is higher than that provided by the selected security zone (in this example, Local Intranet).

Aa730865.netvbdev0814(en-US,VS.80).gif

Figure 8-14. Permission Settings dialog box.

If you include a permission that isn't included by default in the selected zone, an information icon appears in the permission row. This indicates that the application will require elevated permissions to run in the selected zone.

You can further modify individual permissions by modifying their particular properties. This allows you to define permissions for specific files or directories, registry keys, or individual Web sites, to name just a few examples.

To illustrate, Figure 8-15 shows the Properties page for the FileIOPermission. The available properties displayed in this window will vary depending on the underlying permission. In the case of the FileIOPermission, for example, you can specify which files or folders require file access, and further define the type of access required to Read, Write, Append or Path discovery using the check boxes provided in the grid. To request unrestricted access to the file system, select the Grant assemblies unrestricted access to the file system radio button.

Aa730865.netvbdev0815(en-US,VS.80).gif

Figure 8-15. Defining properties for the FileIOPermissions.

Manually tailoring security permissions works fine if you know precisely what permissions are necessary for your application. Evaluation of the security requirements for an application should absolutely be an integral part of a project's development life cycle, and therefore you should know what permissions you need to configure. For many reasons, however, that might not always be the best approach. You might not be certain about the permission requirements for your application or how a particular permission influences application behavior. And in a situation of uncertainty, it is far more likely that you will request more permissions than are necessary, violating the primary goal of ensuring that the application has only permissions it needs to run. Fortunately, the Visual Studio 2005 IDE includes two additional tools—the Permissions Calculator and a facility that allows you to debug the application using the configured security settings—that help you accurately identify the security requirements for your ClickOnce application.

Permissions Calculator

The Permissions Calculator is available from the Security pane of the Project Designer. If you aren't sure about the code access security requirements for your application, use the Permissions Calculator tool to perform a static analysis of the code in your project. When the analysis is complete, the tool automatically updates the ClickOnce security permissions for the project as a custom set of permissions.

Caution   Because the Permissions Calculator does a static analysis of your code, in some cases the tool might not be 100-percent accurate. If your application requires dynamic file system access, for example, you will need to configure this permission manually.

Debugging in a Security Zone

As a companion to the Permissions Calculator, you can run your application in the debugger by using the currently defined ClickOnce security settings. This approach lets you test your application using the exact permissions granted when the application is deployed. Recall from the discussion earlier in this chapter about the limitations of No-Touch deployment that developers would build and debug applications in an environment with Full Trust and then have those applications throw security exceptions when they were deployed over the Internet or an intranet. Using the currently defined ClickOnce security settings to run your application in the debugger allows you to entirely remove the guesswork in determining whether an application will have sufficient permissions to work when it is actually deployed.

To configure a project for debugging in the sandbox, click the Advanced button on the Security pane to display a dialog box for configuring the application to run with the currently selected ClickOnce security settings. You can also specify the URL from which the ClickOnce application will be downloaded.

Figure 8-16 shows the Advanced Security Settings dialog box with a typical configuration. The Debug This Application With The Selected Permission Set check box is selected. The URL value entered in the text box will determine the level of trust granted to the application while executing in the debugger.

Aa730865.netvbdev0816(en-US,VS.80).gif

Figure 8-16. Enabling debugging in the sandbox.

Once the application is configured for debugging in the sandbox, simply run the application in the debugger and exercise its functionality. If you attempt to perform a task for which the application does not have the required permission in the selected security zone, a run-time security error displays as it would if the application were actually deployed.

Elevating Permissions

Now consider what happens after you have established the security settings for a ClickOnce application. When you publish a ClickOnce application, the permissions defined in the Security pane of the Project Designer get written to the trustInfo element of the application manifest.

When a user launches or installs the application, the ClickOnce subsystem reads the permissions requested from the application manifest and notifies the user if they are beyond the permissions provided by the default security zone. For example, if you have deployed a ClickOnce application over the Internet that requires local file system access and you have followed good security practice by configuring the application to request the minimum set of permissions, when a user installs the application from its publishing location he will be presented with a prompt stating that the application requests a higher level of trust than the Internet Zone.

Figure 8-17 shows the security warning message that appears when a user attempts to install a ClickOnce application requesting a higher level of trust. A message at the bottom of the message window warns that the application requires potentially unsafe access to the computer.

Aa730865.netvbdev0817(en-US,VS.80).gif

Figure 8-17. Application installation security warning.

Authenticode Signing

A security policy can also grant permissions based on the publisher of a ClickOnce application. Digital certificates provide information about a software publisher that is verified by a trusted third-party. For commercial software distribution, you would likely obtain a certificate from a company such as Thawte or VeriSign. You can use a digital certificate to sign a deployment manifest. The .NET Framework SDK includes a tool for file-signing called SignCode.exe.

Windows Installer Enhancements

Microsoft Windows Installer is an installation and configuration service that ships as a part of Windows Server 2003, Windows 2000, and Windows XP. As of this writing, most systems use Windows Installer version 2.0 (including Windows 9x and Windows NT 4.0, where Windows Installer can be installed as a separate download). Visual Studio 2005 will support Windows Installer version 3.0, and we'll look at some enhancements provided in this release in the sections that follow.

Warning   While Windows Installer version 2.0 can be used on Windows 9x and Windows NT 4.0, Windows Installer version 3.0 is not available to these older operating systems.

Earlier types of setup programs used a procedural model, providing scripted instructions for application installations. An installation package file (characterized by its .msi extension) uses structured storage to organize resources and custom actions associated with a particular installation. At installation time, the Windows Installer engine parses the data in the installation file to build both the installation script and a rollback script that is available for uninstalling the program at a later date. To prevent uninstalls from breaking other applications, a local database tracks information about all the applications on a computer, such as registry settings and installed files. On uninstall, Windows Installer reads this database to confirm that no other applications are relying on files or registry settings that it is removing.

Windows Installer also provides a self-repair facility, which allows applications to automatically reinstall missing files that might have been deleted by the user. A related feature is installation rollback; if a fatal error occurs midway through an installation, Windows Installer can abort the installation and return the computer to its original state.

Windows Installer 3.0 Enhancements

Version 3.0 of Windows Installer includes a number of enhancements to the existing Windows Installer feature set and adds new areas of functionality. Among the improvements in Windows Installer 3.0 is better author control and resource management, including improvements to the interfaces for querying a computer for users and other software products installed on the machine.

The most significant improvement in Windows Installer 3.0 is the addition of a softwarepatching capability. Whereas in the past application updates might have required a full reinstall of a particular application, patch installation packages (or .msp files) allow developers to deploy incremental updates to their applications. Among the key benefits of MSP files is that they allow for smaller and better performing installation packages.

Visual Studio 2005 Integration

Building on the foundation of Windows Installer technology, Visual Studio 2005 includes tools for creating comprehensive and far-reaching installations. That said, you will also find that Visual Studio 2005 does not include all the authoring tools necessary to take full advantage of the capabilities of Windows Installer. Notably absent from the Visual Studio 2005 IDE, for example, is the ability to create Windows Installer 3.0 software update packages.

Note   For comprehensive Microsoft Windows Installer authoring tools, you should investigate products from third-party vendors, such as InstallShield and Wise.

Setup Projects   Visual Studio 2005 includes several project templates for building installation programs based on Windows Installer technology. As shown in Figure 8-18, you have three basic types of installer projects: Setup projects, Web Setup projects, and Smart Device CAB projects. They are distinguished from one another based on where the installer will be deployed: Setup projects will install files into the file system of a target computer; Web Setup projects install files into a virtual directory of a Web server; and Smart Device CAB projects install Pocket PC, Smartphone or other Windows-CE based applications.

Aa730865.netvbdev0818(en-US,VS.80).gif

Figure 8-18. Visual Studio 2005 Setup projects templates.

Table 8-3 summarizes each of the various deployment project types and their purpose. In addition to the three primary setup projects discussed above, you will find project templates for building a Merge Module or CAB project.

Table 8-3. Visual Studio 2005 Deployment Project Types

Project TypePurpose
Setup ProjectBuilds an installer for a Windows-based application
Web Setup ProjectBuilds an installer for a Web application
Merge Module ProjectPackages components that can be shared by multiple applications
CAB ProjectCreates a cabinet file for downloading to a legacy Web browser
Smart Device CAB ProjectBuilds an installer for a Smart Device application

Another choice in the setup project templates is the Setup Wizard; while not a setup project itself, choosing this item launches a wizard that guides you through the process of choosing the correct deployment project type.

Note   Windows Installer project files (.wip) created with the Visual Studio Installer add-in for Visual Studio 6.0 cannot be opened in Visual Studio 2005.

Merge Modules: Merge modules are a special type of deployment project. They can be used to deliver shared code, files, resources, registry entries, and setup logic to applications as a single file. As a simplified form of an .msi file, merge modules have an .msm file name extension. As such, they cannot be installed directly and need to be merged into a setup project. When a merge module is merged into the .msi file of an application, all the information and resources required to install the components contained in the merge module are incorporated into the application's .msi file. Because all the information needed to install the components is delivered as a single file, the use of merge modules can help reduce version conflicts, missing registry entries, and improperly installed files.

Tip   Merge modules can be incorporated directly into a Setup Project or a Web Setup Project from the Project menu.

Building a Windows Installer Installation Package

If you have worked with setup projects in previous versions of Visual Studio, the tasks you need to perform in building a setup project in Visual Studio 2005 should be familiar to you. In most cases, you'll want to create the installation as a subproject of the solution containing the application you intend to deploy. You can choose either one of the predefined setup projects or the Setup Wizard to create the shell for the project. A key advantage of using a Windows Installer-based installer rather than ClickOnce is the flexibility it provides in customizing the installation. And the Visual Studio 2005 IDE provides editors to work with registry settings and file types and associations. You can also customize the user interface for the installation, specify launch conditions, and define custom actions to be performed after installation.

Tip   Remember, you can include Windows Installer packages with a ClickOnce deployment as a prerequisite.

Installing Files, Folders, and Shortcuts: The basic task of a Setup project is installing files to the target computer. The File System Editor represents the file system on a target computer, and you use this tool to specify where application files will be installed. In most cases, you will want to place application files in the Application Folder or in subfolders you create beneath the Application Folder. When installed on a target computer, files from the Application Folder will be located in the Program Files\Manufacturer\ProductName folder, where Manufacturer is the company name that you used when you installed Visual Studio and ProductName is the name that you used for the deployment project. You can override both of these settings in the properties window for the setup project.

Figure 8-19 shows the File System Editor for a setup project that will include the primary output from a project titled "WeatherReport." Note that both this application project and the setup project (WeatherReportSetup) are listed in Solution Explorer. The Application Folder also includes a shortcut to the application being installed and the icon file (Icon1.ICO) associated with the application. After adding an icon file to the Application Folder, you can use it to set the icon property of shortcuts or the icon associated with the item added to the Add or Remove Programs list on the target computer (set using the AddRemoveProgramsIcon property of the Setup project).

Aa730865.netvbdev0819(en-US,VS.80).gif

Figure 8-19. The File System Editor.

You can also configure the installation to add items to the desktop and/or Start Menu of the target machine. Most commonly, you will add a shortcut to the installed application. In the File System Editor, add shortcuts in the folders titled User's Desktop and User's Program Menu to install shortcuts on the user's desktop and Start Menu, respectively. In the example shown in Figure 8-19, you could simply cut the shortcut listed in the Application Folder and paste it into the User's Desktop or User's Program Menu, or both.

Creating File Associations: Use the File Types Editor to establish file associations on the target computer by associating file extensions with your application and specifying the actions allowed for each file type. You can also specify the default action for a file type, such as opening or printing the file. The default actions occur when a user double-clicks a file in Windows Explorer. And all the actions you specify appear as commands in the context menu when a user right-clicks a file in Windows Explorer. Figure 8-20 shows an example of using the File Types Editor to add Open and Print actions for a file type of .wxl.

Aa730865.netvbdev0820(en-US,VS.80).gif

Figure 8-20. The File Types Editor.

Modifying the User Interface: A set of default dialog boxes are provided automatically for display during installation. This set of dialog boxes provided varies based on the type of project you're building. Using the User Interface Editor, you can reorder or delete dialogs.

As shown in Figure 8-21, the dialog tree displayed in the editor contains two sections: Install and Administrative Install. The Install section includes the dialog boxes displayed when an end user runs the installer, while the Administrative Install section contains the dialog boxes displayed when a system administrator uploads the installer to a network location. If you want to build an install with no user interface, simply delete all dialog boxes in the Install section of the dialog tree. Or you can add dialog boxes to the install project from a set of available templates.

Aa730865.netvbdev0821(en-US,VS.80).gif

Figure 8-21. The User Interface Editor.

Managing Registry Keys and Values: If the application install requires changes to the registry, use the Registry Editor to add registry keys and values during installation. As illustrated in Figure 8-22, the Register Editor provides a split-pane window for adding registry settings. The left pane displays a hierarchal view of the registry on the installation target machine, which you can use to build paths to one or more registry keys. Use the right pane to add values for the currently selected registry key.

Aa730865.netvbdev0822(en-US,VS.80).gif

Figure 8-22. The Registry Editor.

Defining Launch Conditions: Use the Launch Conditions Editor to define conditions that must be met to successfully run an installation. For example, you can check for a specific version of an operating system. If a user attempts to install on a system that does not meet the condition, the installation aborts. You can also configure launch conditions to search the target computer for a particular file, registry key, or component. Windows Installer performs searches and conditional evaluations at the beginning of an installation and in the order shown in the Launch Conditions Editor.

Figure 8-23 shows the Launch Conditions editor. This editor contains folders to add search and launch conditions and it shows the default launch condition requiring a specific version of the .NET Framework. For this particular launch condition, the Properties pane allows you to specify the supported runtime.

Aa730865.netvbdev0823(en-US,VS.80).gif

Figure 8-23. The Launch Conditions Editor.

Defining Custom Actions: Custom actions provide a mechanism for performing tasks at the end of an installation. For example, you might want to launch a self-registration program or relay account information to a Web service after an application is installed, or you might want to direct users to a customer satisfaction survey on uninstall. Custom actions are built as separate .dll or .exe files and then added to the project where they can be associated with different phases of the installation by using the Custom Actions Editor. Figure 8-24 shows the Custom Actions Editor, which includes separate folders for placing the binaries used to perform Install, Commit, Rollback, or Uninstall tasks.

Aa730865.netvbdev0824(en-US,VS.80).gif

Figure 8-24. The Custom Actions Editor.

Building the Installation Package: Building the installation package is no different than compiling a finished .NET assembly. Selecting Build from the project menu causes the .msi file to be compiled along with the bootstrapper program. You can also test installations directly from the Visual Studio 2005 IDE. When a setup project is active in the IDE, the Project menu includes menu items for Install and Uninstall, making it a very simple matter to safely test installations in development. Figure 8-25 shows the installation package (WeatherReportSetup.msi), and the bootstrapper programmer (setup.exe) as they appear in the Setup project's Debug directory.

Aa730865.netvbdev0825(en-US,VS.80).gif

Figure 8-25. The compiled .msi installation file and bootstrapper.

Walkthrough

This example is a Visual Basic .NET Windows Forms application that provides user-initiated updating using the ClickOnce APIs. Before you start, make sure to disable automatic update checking in the project properties; having an application check for updates every time a user launches the application renders user-initiated update checks redundant (unless you expect your users will never close your application!).

Important   To use the ClickOnce APIs from code, include a project reference to the System.Deployment assembly.

Providing UI Access

Of course you need to provide a way for your users to check for updates from your application. One option is to place a Check For Updates menu item on your application's main form. As Figure 8-26 illustrates, the demo application includes submenus for using either the synchronous or asynchronous version of the ClickOnce API for update checking.

Aa730865.netvbdev0826(en-US,VS.80).gif

Figure 8-26. Provide the user easy access to updates from the Help menu.

Adding Code to Check for Updates

At the top of the code file for the main form, import the deployment namespace as follows:

Imports System.Deployment
Imports System.Deployment.Application

Next, add code to the click event handler for the menu item to check for updates. ApplicationDeployment is a class contained in the System.Deployment namespace, and you'll use the properties and methods of this class to programmatically update to the current deployment (you also use this class for on-demand downloads of files). Before creating an instance of this, check the static IsNetworkDeployed property, a boolean value indicating whether the current application is a ClickOnce application:

      If Application.ApplicationDeployment.IsNetworkDeployed Then
            '  Update  check  code  goes  here.
        End If

As the code snippet illustrates, it is wise to enclose the update checking code within an If statement confirming that this is a ClickOnce application. If you attempt to create an instance of ApplicationDeployment for an application that is not ClickOncedeployed, the result is an InvalidDeploymentException error. Also, you cannot create an instance of ApplicationDeployment directly. Instead, use the static CurrentDeployment property, which returns the current ApplicationDeployment object for the ClickOnce application:

Dim  thisDeployment  as  ApplicationDeployment  =  _ 
ApplicationDeployment.CurrentDeployment

Once you have created an instance of the ApplicationDeployment object, you can all the CheckForUpdate method to determine whether a newer version of the application is available. This method returns a Boolean value of true if an update is available:

If  True  =  thisDeployment.CheckForUpdate()  Then
   '  New  version  of  application  is  available. Else
   '  Application  is  up-to-date. End  If

The asynchronous version of this method is CheckForUpdateAsync. To implement this method, you first need to add an event handler for the CheckForUpdateCompleted event:

AddHandler  thisDeployment.CheckForUpdateCompleted,  _ AddressOf  CheckForUpdateCompleted

thisDeployment.CheckForUpdateAsync()

The method signature for the CheckForUpdateCompleted event includes a CheckForUpdateCompletedEventArgs object. In the event handler, you need to check the value of the boolean UpdateAvailable property of CheckForUpdateCompletedEventArgs to determine if a new version of the application is available:

Private  Sub  CheckForUpdateCompleted(ByVal  sender  As  Object,  _ ByVal  e  As  
CheckForUpdateCompletedEventArgs)

If  e.UpdateAvailable  Then
'  New  version  of  application  is  available.
Else

'  Application  is  up-to-date.
End  If
End  Sub

The CheckForUpdateCompleted event is called on the main application thread. So it is perfectly safe to use your application's Windows Forms controls directly within this callback.

The Update method of the ApplicationDeployment class updates the application to the latest version:

thisDeployment.Update()

The asynchronous version of this method, UpdateAsync, uses the same pattern as the CheckForUpdateAsync method. The UpdateAsync method raises two separate events: ProgressChanged occurs at intervals during download of the updated application files, which can be useful for reporting installation progress for large applications, or updates that execute over a slow network connection; UpdateComplete occurs when the update is complete. Before calling the UpdateAsync method, first add event handlers for the UpdateComplete event and (optionally) the ProgressChanged event:

AddHandler  thisDeployment.UpdateCompleted,  AddressOf  Update_UpdateCompleted
AddHandler  thisDeployment.ProgressChanged,  AddressOf  Update_ProgressChanged thisDeployment.UpdateAsync()

The method signature for the ProgressChanged event handler includes a DeploymentProgress-ChangedEventArgs parameter. You can access the properties of this object to report the status of the application update. In this example, the progress information is written to a panel on the status strip of the application's main Windows form.

Private  Sub  Update_ProgressChanged(ByVal  sender  As  Object,  _ ByVal  e  As  
DeploymentProgressChangedEventArgs)
'  Calculate  progress  of  update  and  store  value  in  local  string. Dim  
updateProgress  As  String  =  String.Format(  _
"{0:D}K  out  of  {1:D}K  downloaded   {2:D}%  complete",  _
e.BytesCompleted  /  1024,  _
e.BytesTotal  /  1024,  e.ProgressPercentage)
'  Update  status  bar  with  update  progress. Me. ToolStripStatusLabel1.Text  =  
updateProgress
End  Sub

The method signature for the UpdateComplete event handler includes an AsyncCompletedEventArgs parameter. The code in the event handler should examine the properties of this object to determine the outcome of the application update. AsyncCompletedEventArgs exposes a Cancelled property, which signals whether the update was canceled, and an Error property, which contains exception information if an error occurred during the update.

Private  Sub  Update_UpdateCompleted(ByVal  sender  As  Object,  _ ByVal  e  As  
AsyncCompletedEventArgs

If  Not  e.Cancelled  Then
If  (e.Error  Is  Nothing)  Then
'  Update  was  successful.

Else
Else

End  If

'  Error  occurred  during  update.
'  Update  was  cancelled. End  If
End  Sub

Conclusion

With ClickOnce, you can deploy and update rich-client applications as simply and easily as Web applications. Using the tools provided in Visual Studio 2005, it is simple to add ClickOnce functionality to an application. The programming model for building custom updating solutions is powerful and straightforward, and it gives you plenty of room for addressing various deployment scenarios. Finally, and probably most importantly, the security features built into ClickOnce allow you to deliver applications that are not only feature-rich and convenient to deploy and maintain, but which also enjoy the protections provided by the .NET Framework.

Even though Visual Studio 2005 and the .NET Framework 2.0 introduce a simple and easy-to-use declarative model for deploying applications with ClickOnce, this isn't a one-size fits all solution. For more complex application installations that might require deploying shared components or other high-impact changes to a computer system, Microsoft Windows Installer technology, which is tightly integrated into all modern Windows operating systems, gives you the power and flexibility you need to build reliable and highly customizable installation programs.

Show:
© 2014 Microsoft