December 01, 2003 12:12 AM

Deploy Apps With Ease

Leverage the tools in the .NET Framework to create a simple installation process.
DevConnections
Rating: (0)

asp:cover story

LANGUAGES:C#

ASP.NET VERSIONS:1.0 |1.1

 

Deploy Apps With Ease

Leverage the tools in the .NET Framework to create asimple installation process.

 

 

ASP.NET makes it easier than everto build killer Web applications and Web services. But building the app is onlypart of the battle. Hopefully you'll ship that application someday and put itinto production. One of the great capabilities .NET brings to the table isXcopy deployment - the ability to copy your files into a directory wherethey're ready to run. That works great for simple applications and deployingpatches and updates, but enterprise applications usually have a more complexarchitecture, requiring a few (or many) more steps to get the application fullydeployed to the target server.

 

At a minimum for a Web application,you need to have the installation process create a virtual directory for youand copy the application files into it. But for enterprise-class Web apps, youlikely need to perform additional steps. For example, you might need toregister shared components in the Global Assembly Cache (GAC), installdatabases, add event logs, gather information from the Administrator performingthe installation to customize configuration parameters of the install, or run otherinstallers, scripts, or programs as part of the installation process.

 

To accomplish these tasks you needto do two things. First, plan for deployment early in the design process.Second, package your application for deployment as a Windows Installer project,which will perform all the additional steps needed to deploy your applicationsuccessfully. In this article, I'll discuss some common considerations fordeploying ASP.NET applications and some easy solutions.

 

Deployment Starts With Design

If your application has anycomplexity whatsoever, early in your design you need to be thinking about howyou plan to deploy it. Know what pieces and parts will make up yourapplication, and what the target production environment will be, both from ahardware and software standpoint. Some of these things might change as yourproduct evolves. So if you keep deployment in mind as you build your app, youcan assess how architecture and design changes might impact deployment anddecide your course of action.

 

The tasks you need your .NETapplication install process to perform generally fall into several categories.The easy part is getting a set of files into the appropriate directories on thetarget machine. You could accomplish this any number of ways, including simplycopying the files over the network or using FTP, or by deploying a compressedfile (using WinZip or Microsoft Cabinet) and uncompressing it on the targetserver.

 

For ASP.NET, you also need tocreate a virtual directory or site in IIS. There also might be some form ofregistration step, which will require you either to register shared assembliesin the GAC or register COM components that will ship with your application.Most real-world applications have you create or update one or more databasesand populate them with runtime or configuration data. Finally, you might haveother custom processing steps that need to be part of your installation processto execute other installer applications, run administration scripts, createevent logs, or countless other tasks.

 

The most robust way to deployapplications on the Windows platform is to use Microsoft's Windows Installertechnology. This means creating a setup program or Microsoft Installer (MSI)file that encapsulates all the steps of the installation process into a singleprocedure that needs to run on the target machine. MSI files actually are aform of database file, although it has a very complex schema and API forinteraction. Using Windows Installer, you also can get automatic support forinstallation failure and rollback, repair, and uninstall through the ControlPanel Add/Remove Programs applet. Visual Studio Setup projects allow you tocreate an MSI file easily to encapsulate the installation process completely.Web setup projects also handle the creation of the virtual directory in IIS foryou.

 

To register files once they'replaced on the target machine, command-line batch files or scripts work nicelyif you're performing the install procedures manually; but a Windows Installerpackage can automate that process for you as part of the installation. WindowsInstaller packages also let you detect errors in the install process, and youcan choose whether to report them to the user or to roll back the installationif the problem is more serious.

 

Deciding which assemblies should bemade shared assemblies can be difficult. If you plan to take advantage of theversion-enforcement capabilities in .NET, you'll need to apply strong names toyour assemblies whether you make them shared assemblies (by placing them in theGAC) or keep them private (by deploying them in the local application folders).If you go with strongly named assemblies, you might want to use yourapplication configuration file to specify what versions of which assemblies aresupported.

 

Use Visual Studio Setup Projects

VS .NET includes a fairly powerful and easy-to-usecapability to create setup projects that you can use to design and compileinstallation packages for your applications. To create one for an ASP.NETapplication, simply create a new project and select Web Setup Project from theSetup and Deployment Projects folder in the Project Wizard. If you do this fromwithin a VS .NET solution that contains your Web project, the wizard will pickup some default settings automatically for deploying the Web applicationcontained in the solution. Once the project is created, you can get to all theviews containing the various setup steps, properties, and configuration throughthe context menu for the project. Simply right-click on the project in SolutionExplorer and expand the View menu (see Figure 1). For a standard ASP.NETdeployment, you should include content files and the primary output in the WebApplication folder at a minimum, but you also can include source files,documentation, debug files, and localization resources.

 


Figure 1. The Project menu for SetupProjects provides access to all the parts of the project you need to manage,including viewing the files installed, Custom Actions, User Interface, Registrysettings, and Launch Conditions.

 

When you place the primary outputfrom a Web application in the Web Application Folder, the setup project createsthe \bin subfolder and places the compiled output from the Web applicationthere. It also detects dependencies and places any dependent assemblies thataren't shared into the output \bin folder. Through the views of a setup projectand the properties for items in those views, you can fully customize the waythe installation behaves and what actions are performed (see Figure 2). You cancreate a setup project in its own solution, but it works much better if youcreate a solution that contains both the application you're deploying and thesetup project because the setup project can include categories of files fromthe application project (such as primary output, documentation files, contentfiles, and so on).

 


Figure 2. You can manage manyaspects of your setup project through the Properties window for the objectsthat compose the setup project, and you can manipulate those objects throughone of several views available in a setup project.

 

Deploying assemblies to the GAC isa simple matter of placing the file in the GAC folder in the File System viewof a Visual Studio .NET setup project. Remember that the assemblies you deploythere will require a strong name. If you manage the project that creates theshared assembly separately from the main Web application, you should create aMerge Module setup project for that shared assembly. Then, incorporate themerge module into the main setup project for the Web application so the mergemodule can be included in other setup projects with minimal configuration. ForCOM components, there's a Register property for files added to the project soyou can have COM components registered on installation automatically.

 

You'll want to gather additionalinformation frequently from the person performing the installation so you cancustomize aspects such as which database server to use, account information,and perhaps information to place in an application configuration file. Figure 3shows you how Visual Studio .NET setup projects let you add dialogs to thesetup process using one of many template dialogs. You can name and label theinput fields in the dialogs as desired, then pass the values from these fieldsto custom build steps for further processing.

 


Figure 3. You can select from one ofmany form templates to add custom dialogs to the setup process, then you canuse the information collected in these forms either to set predefined installervariables or pass information to your custom actions as parameters.

 

Empower Your Installation Project

The key to a complete installationrequires a combination of the ability to specify custom build steps and someform of code to specify what happens in those steps. Visual Studio .NETprojects let you create Custom Actions that run for the actions Install,Uninstall, Rollback, and Commit. You could simply execute Windows script orbatch files from these actions if you want to code your custom actions as such,but this approach doesn't allow tight integration into the installation processbecause the scripts or batch file will run outside the transacted environmentof the Windows Installer.

 

There's a very powerful way toaccomplish just about anything you might need your installation to do and,unlike many commercial installer products, it doesn't require you to learn anyspecial scripting languages or macros. The .NET Framework includes many classesin the System.Configuration.Install namespace that let you implement Installerclasses using .NET languages that can integrate directly into a WindowsInstaller project.

 

The code download for this articleincludes four projects in a solution to demonstrate an example deployment of aWeb application (see the Download box for details). First is a simple Webapplication (DeployTestApp) that has a single Web page that displays a list ofcustomers from a database. Second, there's a class library project(DeployTestBLL) that contains the code that gets the data from the database,representing a business-logic layer for a typical Web application. Third is aWeb setup project (DeployTestSetup) that creates the Windows Installer packagefor creating the Web application on a target machine as well as all theresources it needs. The fourth project (DBInstallerLib) contains the custominstaller class that gets called by the Windows Installer package to performthe custom build step.

 

This application's setuprequirements include the ability for the person running the installation tospecify the name of the database server, the name of the database to becreated, and optionally a username and password if the connection to thedatabase isn't a trusted Windows Authentication connection. The setup programthen needs to create the database, populate a table in that database withruntime data, and update the web.config file to include the appropriateconnection string for the database once it's created.

 

To accomplish these steps, you needto create a custom installer class that can run from the Windows Installerprocess created by the setup project. To create a custom installer class, firstcreate a class library project and include a reference in that project to theSystem.Configuration.Install.dll library. Then, add a class to the project thatderives from the Installer class. You need to place a RunInstaller attribute onthis class as well; Figure 4 provides the code. The Installer base classincludes the virtual methods Install, Uninstall, Commit, and Rollback, whichcorrespond to the parts of a Windows Installer process. You can override thesemethods to add custom installation steps to be executed during the overallinstallation process.

 

[RunInstaller(true)]

public class DBInstaller : Installer

{

  public override voidInstall(IDictionary stateSaver)

  {

    base.Install(stateSaver);

    CreateDatabase();

    ImportData();

    UpdateConfigConnStr();

  }

 

  public override voidUninstall(IDictionary stateSaver)

  {

    // Remove resources asnecessary

  }

}

Figure 4. Bycreating a class derived from Installer, you can include any kind of customprocessing in a Windows Installer setup process that you can code in your .NETlanguage of choice.

 

This article's sample code uses aSQL script for creating the database generated by SQL Enterprise Manager. Itreads in the script and executes each command in the script using theSqlCommand class. It then uses the Bulk Copy Program (bcp.exe) utility toimport a set of sample data exported from the development database as itsdeployed runtime data. In this case, it's the Customers table from theNorthwind database, but it's created in its own database on the target machineso as not to interfere with your own copy of Northwind.

 

To run the Bulk Copy Program, youcould use the Process class from the System.Diagnostics namespace to executebcp.exe on the command line. But instead, you can hijack some convenientcapability out of the System.VisualBasic namespace - specifically theInteraction class' Shell method. Note that I'm calling this from a C# classlibrary; behold the power of cross-language compatibility in .NET! The Shellmethod makes it easy to run an application as a fully constructed command line,specify the behavior of the window in which it'll run, and run the applicationas the interactive user so it can pick up the Windows Authentication identityof that user for something such as logging into SQL Server.

 

Once the class library with yourinstaller class is built, you can add a custom action to the install processfor your setup project and point it to the output of your installer classlibrary. To do this, go to the File System view in the setup project and addthe primary output of the class library to a folder in the output of theinstallation process. (In the code download, I created a Setup subfolder of theWeb application and required the setup project to place the output of theinstaller class library project there.) Now go to the Custom Actions view,right-click on the Install folder, and select Add Custom Action from thecontext menu. You are presented with a dialog to select executable files andscripts from the output folders of the installation, and you simply can pointthe action to the class library containing the installer class. Once you'vedone this, you can set properties for the action, including theCustomActionData property to be passed to the installer or script file asparameters (see Figure 5).

 


Figure 5. The CustomActionDataproperty for a custom action lets you pass parameters into the custom action.These parameters can be gleaned from the user from custom dialogs in the setupor standard properties such as TARGETDIR.

 

Using this technique of creatingcustom actions through Installer-derived classes means you can incorporate anyactions you need in your installation process if you can determine how to codeit in .NET. You even can throw in Windows Forms to gather further informationfrom the user or to show progress or information regarding your custom actions.The VS .NET setup projects automate the most common actions for you, such aswhen you place files in locations on the target machine, register sharedlibraries or COM components, and create virtual directories. There are alsosome prebuilt installer components for creating Event Logs, PerformanceCounters, Message Queues, and Services. For more information on using thesecomponents, I recommend "Deploying N-Tier Applications with Visual Studio.NETSetup Projects" by Ron Jacobs (http://www.gotdotnet.com/team/xmlentsvcs/deployntier.aspx).If you use Visual Studio .NET Setup projects with custom actions, built-ininstaller components, and your own Installer-derived classes, there shouldn'tbe any installation hurdle you can't tackle.

 

The sample code in thisarticle is available for download.

 

Brian Noyes is a consultant, trainer, and writer withIDesign Inc. (http://www.idesign.net).Brian specializes in architecture, design, and coding of .NET data-drivenWindows and Web applications, and office automation and desktop productivityapplications. He's an MCSD with more than 12 years of programming, design, andengineering experience, and he is a contributing editor for asp.netPRO and other publications. E-mail him at mailto:brian.noyes@idesign.net.

 

Additional Deployment Options

Deployment is a huge topic andthere are countless variations on what the requirements and solutions might be.If you're going to be creating installation packages frequently and allowingend users to install them, you might want to purchase a dedicated installationtool such as one from InstallShield (http://www.installshield.com)or Wise for Visual Studio .NET (http://www.wise.com).For most situations, however, you can get by with the tools in Visual Studioand the .NET Framework - if you know where to look and don't mind writing alittle extra .NET code.

 

 

 

Add a Comment

There are no comments to display. Be the first one!
You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement




Comments from the DevConnections Community

Join our community of development pros.

Windows problem

I all, I have a problem on my Windows Vista that began afetr the purchase of an external Hard Disk Freecom. A few days afetr the purchase I discon...

Most Recent Posts

GOOGLE LINKS
SPONSORED LINKS
FEATURED LINKS