Extreme ASP.NET

Web Deployment Projects

Fritz Onion

Contents

Deployment in ASP.NET 2.0
Web Deployment Projects
Merging Assemblies
Pluggable Configuration Files
Creating Reusable User Controls
Conclusion

When ASP was first released, Web programming was more difficult because you needed IIS to serve your ASP pages. Later, ASP.NET 2.0 and Visual Studio® 2005 made everything easier by introducing the Web site model of development. Instead of creating a new project inside Visual Studio, the Web site model lets you point to a directory and start writing pages and code. Furthermore, you can quickly test your site with the built-in ASP.NET Development Server, which hosts ASP.NET in a local process and obviates the need to install IIS to begin developing. The beauty of the Web site model is that you can develop your Web application without thinking about packaging and deployment. Need another class? Add a .cs file to the App_Code directory and start writing. Want to store localizable strings in a resource file? Add a .resx file to the App_GlobalResources directory and type in the strings. Everything just works; you don't have to think about the compilation and deployment aspect at all.

When you are ready to deploy, you have several options. The simplest choice is to copy your files to a live server and let everything be compiled on-demand (as it was in your test environment). The second option is to use the aspnet_compiler.exe utility and precompile the application into a binary release, which leaves you nothing but a collection of assemblies, static content, and configuration files to push to the server. The third option is to again use aspnet_compiler.exe, but to create an updateable binary deployment where your .as*x files remain intact (and modifiable) and all of your code files are compiled into binary assemblies.

This seems to cover every possible scenario, leaving the developer to focus simply on writing the Web application, with packaging and deployment decisions to be made later when the application is actually deployed. There was a fair amount of backlash against this model, however, especially from developers who were used to their Web projects being real projects, specified in real project files, that let you inject pre-and post-build functions, exclude files from the build process, move between debug and release builds with a command-line switch, and so on. In response, Microsoft quickly introduced the Web Application Project or WAP, initially released as an add-in to Visual Studio 2005, and now included in Visual Studio 2005 Service Pack 1 (SP1), available for download from msdn.microsoft.com/vstudio/support/vs2005sp1.

WAP provides an alternative to the Web site model that is much closer to the Visual Studio .NET 2003 Web Project model. The new WAP model compiles all of the source code files during the build process and generates a single assembly in the local /bin directory for deployment. WAP also makes it much easier to incrementally adopt the new partial class codebehind model introduced in ASP.NET 2.0 because you can now open a Visual Studio .NET 2003 project and only your .sln and .csproj (or .vbproj) files will be modified during the conversion. You can then convert each file and its codebehind class to the new partial class model independently of any other file in the project (by right-clicking on the file in the Solution Explorer and selecting Convert to Web Application), or just leave them using the old model. This is in contrast to converting a Visual Studio .NET 2003 Web project to the Web site model, which converts all files at once and does not support incremental adoption.

Finally, there is a new project type called Web Deployment Projects (the main topic of this column), which introduces myriad additional deployment options for both Web site projects and Web Application Projects. Web Deployment Projects fill the remaining holes in the deployment options for both Web site apps and Web Application Projects and make it possible to implement practically any deployment scenario in a simple and extensible way. To understand exactly what this new project type adds, let's first review what we had before Web Deployment Projects were available.

Deployment in ASP.NET 2.0

When you build an application using the Web site model, you have the option of precompiling the site for deployment. You can access the precompilation utility through the Build | Publish menu in Visual Studio 2005 or directly through the command-line utility aspnet_compiler.exe. Figure 1 shows the interface to this tool exposed by Visual Studio.

Figure 1 Publish Web Site Utility

Figure 1** Publish Web Site Utility **(Click the image for a larger view)

The first decision you have to make when using the publish utility is whether you want your .as*x files to be updatable once deployed (use the "Allow this precompiled site to be updatable" option of -u switch in the aspnet_compiler.exe command-line utility). This decision hinges on whether you want to be able to make minor changes to your pages once deployed without having to go through the entire deployment process again. You may, in fact, want to explicitly disallow any modifications to the deployed pages and require that all modifications go through the standard deployment (and hopefully testing) process, in which case publishing the site as not updatable is the proper choice.

When a site is published as not updatable, it is possible to completely remove all .as*x files and publish only binary assemblies (plus configuration files and static content). However, without the physical files in place, it is impossible for ASP.NET to tell which classes to use for which endpoint requests. For example, if a request comes into your application for Page1.aspx and you have used non-updatable binary deployment, there very well may not be any Page1.aspx file on disk, and there is nothing in the existing configuration files to indicate which class in the collection of assemblies deployed to the /bin directory should actually be the handler for this request. To remedy this, the compilation process will also generate a collection of .compiled files that contain endpoint-to-type mapping and file dependency information in a simple XML format, and these files must be published along with the binary assemblies in the /bin directory of the deployed site. As an example, if you did have a page named Page1.aspx in your application, the aspnet_compiler.exe utility would generate a file named page1.aspx.cdcab7d2.compiled (with the hash code varying) that contained the following XML:

<?xml version="1.0" encoding="utf-8"?>
<preserve resultType="3"  
          virtualPath="/SampleWebSite/Page1.aspx" 
          hash="8a8da6c5a" filehash="42c4a74221152888" 
          flags="110000" assembly="App_Web_aq9bt8mj" 
          type="ASP.page1_aspx">
  <filedeps>        
    <filedep name="/SampleWebSite/Page1.aspx" />
    <filedep name="/SampleWebSite/Page1.aspx.cs" />
  </filedeps>
</preserve>

The other major decision you have to make when publishing a Web site with this utility is the granularity of the packaging of the generated assemblies. You can either create a separate assembly for each directory in your site or create a separate assembly for each compilable file in your site (.aspx, .ascx, .asax, and so on.) by checking the Use fixed naming and single page assemblies (or -fixednames in the aspnet_compiler.exe command-line utility). This decision is not as obvious as you might think, as each option has its own potential issues. If you elect to not use the -fixednames option, then every time you publish your application a completely new set of assemblies will be generated, with completely different names from the ones published earlier. This means that deployment is trickier because you must take care to delete all of the previously published assemblies on the live server before deploying the new assemblies or you'll generate redundant class definition errors on the next request. Using the -fixednames option will resolve this problem as each file will correspond to a distinctly named assembly that will not change from one compilation to the next. If you have a large site, however, generating a separate assembly for each page, control, and Master Page can easily mean managing the publication of hundreds of assemblies. It is this problem of assembly granularity in deployment that Web Deployment Projects solve in a much more satisfying way, as you will see.

You can also introduce assembly signing into the compilation process to create strong-named, versioned assemblies, suitable for deployment in the Global Assembly Cache (GAC) if needed. You can mark the generated assemblies with the assembly-level attribute AllowPartiallyTrustedCallers using the -aptca option, which would be necessary if you did deploy any assemblies to the GAC and were running ASP.NET at a low or medium level of trust. (Keep in mind that this attribute should only be applied to assemblies that have been shown not to expose any security vulnerabilities, as using it with a vulnerability could expose a luring attack.)

One other detail about publishing your site is that if you do elect to use Web Application Projects instead of the Web site model, the Build | Publish dialog box will look quite different, as shown in Figure 2. Web Application Projects assume that you want to publish the application as updatable .as*x files and precompiled source files (the same model it uses in development), so the binary-only deployment options are not available. This utility is really closer in nature to the Copy Web site utility available with Web sites than it is to the Publish Web Site utility since it involves copying files produced by the standard build process.

Figure 2 Publish Web Utility for Web Application Projects

Figure 2** Publish Web Utility for Web Application Projects **(Click the image for a larger view)

Technically you are not restricted from using binary-only (non-updatable) deployment, even if you are using Web Application Projects. If you think about it, the output of the build of a WAP is a valid Web site, which you can then pass through the aspnet_compiler.exe utility to generate create a binary deployment. You just can't invoke it from the Visual Studio 2005 interface which, fortunately, Web Deployment Projects rectify.

Web Deployment Projects

So what's missing from the existing compilation and deployment options presented so far? Primarily two things: the ability to control the naming of assemblies, especially for deployment purposes, and the ability to consolidate all of the output assemblies into a single assembly for simplified deployment. Web Deployment Projects solve both of these problems. Perhaps even more significantly, however, they also tie up a lot of loose ends in the deployment story that existed with Web site applications and Web Application Projects.

At their core, Web Deployment Projects (available for download at msdn2.microsoft.com/aa336619.aspx) represent just another type of project you add to your solution. Like all Visual Studio project files, Web deployment projects are MSBuild scripts that can be compiled directly in the IDE or run from the command line. Instead of specifying a collection of source code files to compile, however, Web Deployment Projects contain build commands to compile and package Web sites (or Web Application Projects). This means that they will invoke the aspnet_compiler.exe utility (among others) to create a deployment of a particular Web application. Web Deployment Projects are shipped as a Visual Studio add-in package that includes an easy-to-use menu item for injecting new projects and a complete set of property pages to control all of the available settings. To add one to an existing application, right-click on an existing Web site (or Web Application Project) and select the Add Web Deployment Project item as shown in Figure 3. This will add a new .wdproj file containing an MSBuild script to your solution, which will generate a deployment of the application you created it from.

Figure 3 Adding a Web Deployment Project

Figure 3** Adding a Web Deployment Project **

Figure 3a

Figure 3a   

Figure 3b

Figure 3b**   **(Click the image for a larger view)

Figure 3c

Figure 3c   

Once the Web Deployment Project is part of your solution, you can access the property pages of the project file to control exactly what the project does for you, as shown in Figure 4. The default setting for a new deployment project is to deploy the application in updatable mode, with all the .as*x files intact, and the source files compiled into a single assembly deployed in the top-level /bin directory. These deployment projects work the same regardless of whether the source application is using the Web site model or the Web Application Project model, which means that you can now select either development model without impacting your deployment options. One of the most significant features of Web Deployment Projects is the ability to configure the deployment to be all binary (not updatable) in the form of a single assembly, the name of which you can choose. Using this model of deployment means that you can update your entire site merely by pushing a single assembly to the /bin directory of your live site, and not concern yourself with deleting existing assemblies prior to deploying or dealing with a partially deployed site causing errors. It is still necessary to deploy the .compiled files for the endpoint mappings, but these files only change when you add, delete, or move pages in your site.

Figure 4 Web Deployment Project Property Page

Figure 4** Web Deployment Project Property Page **(Click the image for a larger view)

Web Deployment Projects provide flexibility in deployment and let you make packaging and deployment decisions independently of how you actually built your Web applications. This independence between development and deployment was partially achieved in the original release of ASP.NET 2.0 with the aspnet_compiler.exe utility, but never fully realized because of the constraints imposed when performing the deployment. With Web Deployment Projects, the separation between development and deployment is now complete, and your decision about how to build your applications will no longer impact your deployment choices.

Merging Assemblies

Much of what Web Deployment Projects provide is just a repackaging of existing utilities exposed via MSBuild tasks and a new interface, but there are also a couple of completely new features included. The most intriguing is the ability to merge assemblies.

When you install Web Deployment Projects, you will find an executable called aspnet_merge.exe in the installation directory (%PROGRAMFILES%\MSBuild\Microsoft\WebDeployment\v8.0, by default). This executable is capable of taking the multi-assembly output of a precompiled site and merging the assemblies into one. This is the utility that is incorporated into your build script if you select the merge option in a Web Deployment Project. As an example of what is possible with this utility, consider the output of a precompiled Web site, run without the updatable switch, shown in Figure 5. The source application for this output contained two subdirectories, a top-level global.asax file, a class defined in App_Code, and a user control. The end result of the compilation is five different assemblies and a collection of .compiled files. If you run the aspnet_merge.exe utility on this directory with the -o switch to request a single assembly output, shown at the bottom of Figure 5, the result is a much more manageable single assembly named whatever you specify.

Figure 5a Using the aspnet_merge.exe Utility

Figure 5a** Using the aspnet_merge.exe Utility **(Click the image for a larger view)

Figure 5b

Figure 5b(Click the image for a larger view)

Although the aspnet_merge.exe utility and the corresponding MSBuild task that ship with Web Deployment Projects are new, the underlying technology for merging assemblies has actually been around since the Microsoft® .NET Framework 1.1 in the form of a utility made available from Microsoft Research called ILMerge, the latest version of which is available for download from research.microsoft.com/~mbarnett/ILMerge.aspx. This utility is directly incorporated into aspnet_merge.exe and does all the heavy lifting involved with merging assemblies. If you think about it, the merging of assemblies is a rather complicated task. You need to take into consideration signing, versioning, and other assembly-level attributes, embedded resources, and XML documentation, as well as manage the details of clashing type names, and so on. The ILMerge utility manages all of these details for you, with switches to control various decisions about the process. It also gives you the ability to transform .exe assemblies into .dll assemblies for packaging purposes. As an example, suppose you have three assemblies: a.dll, b.dll, and c.exe which you would like to merge into a single library assembly. As long as there were no conflicts in typenames, the following command line would generate a new library, d.dll with all of the types defined in a.dll, b.dll, and c.exe:

ilmerge.exe /t:library /ndebug /out:d.dll a.dll b.dll c.exe

Pluggable Configuration Files

The other completely new feature that comes with Web Deployment Projects is the ability to create pluggable configuration files. It is a common problem when deploying Web applications to find a way to manage the differences in your configuration files between development and deployment. For example, you may have a local test database to run your site, have another database used by a staging server, and yet another used by the live server. If you are storing your connection strings in web.config (typically in the connectionStrings section), then you need some way of modifying those strings when the application is pushed out to a staging server or to a production machine. Web Deployment Projects offer a clean solution to this problem with a new MSBuild task called ReplaceConfigSections.

This task allows you to specify independent files that store the contents of a particular configuration section independently based on solution configurations. For example, you might create a debugconnectionstrings.config file to store the debug version of our connectionStrings configuration section that looked like this:

<connectionStrings>
    <add connectionString="server=localhost;database=sales;
                           trusted_connection=yes" name="sales_dsn"/>
</connectionStrings>

Similarly, you would then create separate files for each of the solution configurations defined (release, stage, and so on) and populate them with the desired connection strings for their respective deployment environments. For the release configuration, you might name the file releaseconnectionstrings.config and populate it as follows:

<connectionStrings>
    <add connectionString="server=livedbserver;database=sales;
                           trusted_connection=yes" 
                           name="sales_dsn"/>
</connectionStrings>

Next, you would configure the MSBuild script added by Web Deployment Projects to describe which configuration sections in the main web.config file should be replaced, and the source files that will supply the content for the replacement. You could modify the script by hand, but there is a nice interface exposed through the property pages of the build script in Visual Studio that will do it for you, as Figure 6 shows. In this case, you are setting the properties for the debug solution configuration, so check the Enable Web.config file section replacement option and specify the section to be replaced along with the file with the contents to replace it:

connectionStrings=debugconnectionstrings.config

Figure 6 Property Page to Set Configuration File Section Replacement

Figure 6** Property Page to Set Configuration File Section Replacement **(Click the image for a larger view)

You would use this same dialog page to set the configuration replacement for the Release solution configuration (and any others we had defined) with the corresponding files.

When you then run the build script, the ReplaceConfigSections task extracts the contents from any associated config files and replaces the contents of the corresponding configuration section, creating a new web.config file that is pushed to the deployment directory. This configuration file replacement feature means that you can maintain configuration differences between deployment environments in a manageable way with text files that can be versioned under source control, and you don't have to resort to referring to that sticky note reminding you to change the connection string when you deploy. It should be emphasized that this feature works with any section of the configuration file, even custom sections, so if you have differences in other configuration sections (for example, appSettings) you can easily specify those differences with this build task as well.

Creating Reusable User Controls

There is an interesting side application of Web deployment projects that solves a problem that has plagued ASP.NET developers for years-how to create reusable user controls to share across applications. User controls are fundamentally just composite custom controls whose child controls are laid out in an .ascx file. The ability to use the designer for laying out controls and adding handlers is a huge benefit for most developers since it feels almost identical to building a page, except that the resulting .ascx file can be included as a control in any page. The disadvantage has always been that you need the physical .ascx file in the application's directory to actually use it. Techniques for making .ascx controls shareable across applications are available, but they usually involve chores like creating shared virtual directories between applications or harvesting temporary assemblies generated by ASP.NET at request time, and they've never been satisfactory.

The introduction of the aspnet_compiler.exe utility in version 2.0 brought us much closer to a decent solution. With the compiler, you can create a Web site consisting of only user controls and publish the site in non-updateable mode using the compiler to generate reusable assemblies. Once you have the resulting assembly (or assemblies), you can then deploy to any Web application and reference the user control just as you would a custom control (not by using the src attribute as you would for .ascx files). The only disadvantage to this technique is that you either have to accept the randomly named assembly produced by the compilation process or select the fixednames option in the compiler to generate a fixed named assembly for each Master Page in the site (not a single assembly for the entire collection).

Web Deployment Projects provide the final step to create truly reusable user control assemblies. You can take the same Web site consisting exclusively of user controls and add a Web Deployment Project to create a single output assembly with the name of your choice. It's even straightforward to create a signed assembly to deploy to the GAC for sharing controls across multiple applications without redeploying the assembly in each /bin directory.

Conclusion

The release of Web Deployment Projects completes the set of tools for deploying ASP.NET applications in a very satisfying way. It is now possible to deploy your applications in any manner ranging from all source to all binary, with complete control over the generation, packaging, and naming of the binary assemblies. In addition, Web Deployment Projects provide a solution for replacing sections of your configuration files based on your target build, and they solve the problem of distributing reusable user controls. Anyone who is building and deploying ASP.NET applications will undoubtedly find some aspect of Web Deployment Projects compelling enough to begin using them today.

Send your questions and comments for Fritz to  xtrmasp@microsoft.com.

Fritz Onion is a co-founder of Pluralsight, a Microsoft .NET training provider, where he heads the Web development curriculum. Fritz is the author of Essential ASP.NET (Addison Wesley, 2003) and Essential ASP.NET 2.0 (Addison Wesley 2006). Reach him at pluralsight.com/fritz.