2012年1月11日 星期三

Installer Class and Custom Actions

INTRODUCTION 
Installer Classes are great tools that you can develop and integrate with your Setup and Deployment Projects in order to perform additional tasks while running any application's installation or un-installation process, thru its MSI file.

Visual Studio .Net supports for Installer Classes dates back to the .Net Framework 1.0 (VS.Net 2002) This article focuses in its latest incarnation within VS.Net 2005.

An Installer Class contains code written by you that takes care of many things required to properly install your application on the end user's Target Machine; you can write an Installer Class using your favourite development language, i.e. Vb.Net, C#, C++, etc; this article's examples are written in C#.

There are very few limitations of the things an Installer Class could do. Perhaps the developer's knowledge imposes the major constraints (or the author's as we don't claim to know everything); the list below includes many of the things an Installer Class is able to do:
  • Change folder permissions.
  • Run your application after installation.
  • Create folders required by your application.
  • Update the application's config file with installation time parameters.
  • Send emails.
  • Write entries to the Target Machine's eventlog.
  • Install database schemas.
  • Windows Services (which, if we follow the existing procedures to deploy them, we are using Installer Classes already).
  • etc, etc, etc
Setup and Deployment Projects can reference as many Installer Classes as required. the Installer Class could be part of your own application's class collection or a stane alone DLL. It will be up to the developer and his/her organization rules to decide how to develop and deploy installer classes.  
SCOPE 

This document is based on VS.Net 2005 deployment projects, explaining as much as possible about Installer Classes and their integration to Setup and Deployment project's Custom Actions.; There are not too many differences between Setup and Deployment projects between Visual Studio 2003 and 2005, and based on this we may claim the information found on this article should help you to implement Installer Classes using Visual Studio 2003. 
The document contains the following sections: 
  • Requirements
  • Terminology
  • How to create an Installer Class
  • Un-written rules
  • Unpleasent features
  • Using these events (about Installer Class events)
  • Using the Commit event to change the target directory permissions.
  • Using the Uninstall event to clean the target directory
  • Where is the "NT AUTHORITY\SERVICE" account coming from?
  • Exceptions and Exception handling in your installer class.
  • Adding user interfaces (forms) to your installer class.
  • Launching your application after installation.
  • Conclusions.
  • References.
REQUIREMENTS 
It will be nice if you have Visual Studio 2005, and a project you want to deploy in order to practice the concepts covered by this document, as well as Virtual PC. Keep in mind that in the early stages of learning how to use Installer Classes you could create a crippled deployment package, which will never install or uninstall. 
TERMINOLOGY
  • Target Machine is the PC or workstation your project will be installed on.
  • Developer Machine is your PC, the one you use to develop your solution and create a deployment project.
  • Setup and Deployment Projects are specialized projects that install your solution on a target machine.
  • Custom Action an external process written by the developer that is run by the deployment project at installation time when the installation is about to finish.
  • MSI Microsoft Installer file, this files are generated by the Setup and Deployment projects.
HOW TO CREATE AN INSTALLER CLASS
  1. Create a new project using the Class Library template, the project name for this procedure will be MyInstallerClassDll


  2. Add a new Installer Class to the project MyInstallerClassDll by clicking on ProjectAdd Class, select the Installer Class template, you may enter any name, the name we will use in this procedure is MyInstallerClass
Your IDE should look like the one shown below:

  1. Delete the default Class1.cs object from the MyInstallerClassDll project by expanding the Solution Explorer, right click on theClass1.cs object and select the Delete option. 
     
  2. Enter the code window for MyInstallerClass object, it should be something like the code below: 
    Code:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Configuration.Install;

    namespace MyInstallerClassDll
    {
        [RunInstaller(true)]
        public partial class MyInstallerClass : Installer
        {
            public MyInstallerClass()
            {
                InitializeComponent();
            }
        } 
    }

That's it, those are the steps to create an Installer Class. As you can see it is inheriting from the Installer abstract class, and because of this, several installation events are exposed for you to override, like:
  • Commit
  • Install
  • OnAfterInstall
  • OnAfterRollback
  • OnAfterUninstall
  • OnBeforeInstall
  • OnBeforeRollback
  • OnBeforeUninstall
  • OnCommitted
  • OnCommitting
  • Rollback
  • Uninstall
All these events come to life when your installer class object is assigned as a Custom Action to a Deployment Project. These events by default are empty and you should code the logic to the ones required by your deployment project.

There are some unwritten rules and unpleasant features when using these events imposed by the way Deployment Projects behave at run time.

The sequence these events are raised is shown next:


Play attention to the facts: (a) untrapped exceptions on the OnBeforeInstall event will not trigger any of the Rollback events; and (b) you may reach the Rollback events from anyone of the installations events. 
UN-WRITTEN RULES
  • All these events should be bullet proof without throwing unexpected exceptions, if anyone of these methods throw an exception the installation or uninstallation request will fail.
  • It does not make much sense calling the Rollback event in the middle of a different event; you should implement these events independent of each other, your installation class may have common methods shared by these events, but cross calling installation related events are risky business.
  • Practice extreme caution when coding the Uninstall event, failure to do so may render your application un installable.
  • If you are using the savedState event's variable (more about this variable later), you should assign your installer class to all the Custom Action's modes (Install, Commit, Rollback and Uninstall) in the Deployment project.
  • Your installer class should not reference classes located outside its assembly because there is no way to know if those assemblies will be available (installed) at the time you reference a class or method from an external assembly.
UNPLEASANT FEATURES
  • None of the deployment project's properties is automatically available within your installer class.
  • Your Installer Class could be instantiated several times by the Windows Installer (installation) process, for this reason you can't rely on global variables to keep track of its different stages, that's why you should use the StateSaver and SavedState objects explained later on this article. 
USING THESE EVENTS 
  • You basically override the event you want to use by typing public override and space, then intellisense kicks in. 
      
  • Once you enter the event, its code should look like this:
Code:

public override void Commit(System.Collections.IDictionary savedState)
{
   base.Commit(savedState);
}

  • The declaration for the Install event is a little bit different, as shown: 
    Code:

    public override void Install(System.Collections.IDictionary stateSaver)
    {
       base.Install(stateSaver);
    }


    Its IDictionary parameter is named differently to the names used by the other events, here it is named stateSaver; It is very important to declare and use this event if you are saving installation parameters to be shared across all the installation events. For example, suppose that you want to pass the installation's target directory stored in the [TARGETDIR]parameter. You can do that with the code below in the Install event:
Code:

stateSaver.Add("TargetDir", Context.Parameters["DP_TargetDir"].ToString());

The complete Install event code including the line of code above should look like this:
Code:

public override void Install(System.Collections.IDictionary stateSaver)
{
   base.Install(stateSaver);
   stateSaver.Add("TargetDir", Context.Parameters["DP_TargetDir"].ToString());
}

Now, let's explain this statement: the stateSaver object-variable (IDictionary type) is the parameter received by the Install event, while theContext.Parameters["DP_TargetDir"] come from the CustomActionData property defined at the Deployment Project's Install custom action, as shown below: 


We named it, DP_TargetDir prefixed with the forward slash (/), We get its value from the deployment project's propery [TARGETDIR], notice that we are enclosing it between double quotes, and we added a backward slash (\) before closing the double quote; You must always add the backward slash before the final double quote for this parameter, otherwise you will get an unexpected behaviour at installation time.

The deployment project at installation time will add the CustomActionData parameters to the custom action's Context Parameters using the names chosen by you (DP_TargetDir in this example).

Whe you add an entry to the stateSaver dictionary, the installation process will create a file at the installation target directory with the base name of your Installer Class and the type InstallState, based on the samples names we are using in this explanation, the InstallState name will be: 
Code:

MyInstallerClassDll.InstallState 

Now, the savedState parameter passed to any event of your Installation Class will have the TargetDir as one of its entries. 
  • If we want to prove the explanation given in the previous section regarding the usage of the stateSaver and savedState dictionary parameters, we may use the Commit event to do so, the code below will dump all the key-values found in its savedState parameters as well as the class' Context Parameter dictionary.
    Code:

    public override void Commit(System.Collections.IDictionary savedState)
    {
       base.Commit(savedState);

       StreamWriter sw = new StreamWriter("C:\\Temp\\VbCity_caic_Commit.txt"false);

       sw.WriteLine("savedState count : " + savedState.Count.ToString());
       sw.WriteLine("savedState keys : " + savedState.Keys.Count.ToString());
       sw.WriteLine("savedState values : " + savedState.Values.Count.ToString());

       foreach (string k in savedState.Keys)
       {
          sw.WriteLine("savedState key[" + k + "]= " + savedState[k].ToString());
       }

       writeContext(sw);

       sw.Flush();
       sw.Close(); 
    }


    A "using System.IO;" line of code was added at the top of the class for the code in the Commit event to work because it is using the StreamWriter.

    The commit event is writing to a file on the Temp folder all the values in the savedState dictionary object as well as the Context.Parameters dictionary, the lattest by thewriteContext() method (its code shown below) 

    Code:

    private void writeContext(StreamWriter wrkSW)
    {
       wrkSW.WriteLine("Context Parameters");
       wrkSW.WriteLine("Count : " + Context.Parameters.Count.ToString());
       wrkSW.WriteLine("Keys : " + Context.Parameters.Keys.Count.ToString());
       wrkSW.WriteLine("Values : " + Context.Parameters.Values.Count.ToString());

       foreach (string k in Context.Parameters.Keys)
       {
          wrkSW.WriteLine("ContextKey [" + k + "]=" + Context.Parameters[k].ToString());
       }
    }


    When we run the deployment project with the Commit event code shown above, the text file (VbCity_caic_Commit.txt) contains the following data 
We should highlight few important things at this stage 
  1. As the Commit event knows the Target Directory where the application is being installed, you can save it to the register for future references from the application, which is a Frequent Asked Question.
  2. The Commit event can reference the TargetDir property from the Context.Parameters variable because it was initialized by theInstall event.
  3. You may use the code shown in the Commit example above to explore what is available on any event in your Installer Class.
  4. You should never attempt to modify the InstallState file, if you damage this file and the Uninstall event requires any information from it, you will not be able to uninstall the application.
  5. You should use the Commit event to apply final changes, like writing information to the register, changing folder permissions, etc.
USING THE COMMIT EVENT TO CHANGE THE TARGET DIRECTORY PERMISSIONS

If your deployment project is installing a Windows Services, and the Windows Services creates or write to files located on the TARGET DIRECTORY (Its home directory), you should change its permissions with the COMMIT event as long as the Windows Services is running under the LocalServiceNetworkService or LocalSystem. 

The code below changes the TARGETDIR permission for a Windows Services running under the LocalService account.
Code:

DirectorySecurity dirSec = Directory.GetAccessControl(savedState["TargetDir"].ToString());
FileSystemAccessRule fsar = new FileSystemAccessRule(@"NT AUTHORITY\SERVICE"

                              , FileSystemRights.FullControl
                              , InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
                              , PropagationFlags.None
                              , AccessControlType.Allow);
dirSec.AddAccessRule(fsar);
Directory.SetAccessControl(savedState["TargetDir"].ToString(), dirSec);
 

You should add the following reference at the top of your class for the code above to work
Code:

using System.Security.AccessControl;
We get the Directory Security for the target directory (Windows Services home directory) using the GetAccessControl method on it; We already know it is save to usesavedState["TargetDir"].ToString() from the explanations given before.

We create a new File System Access Rule for the NT AUTHORITY\SERVICE account, granting it (allowing, as the last parameter specifies AccessControlType.Allow) FullControl and setting the Inheritance Flags to ContainerInherit and ObjectInherit (both of them, the pipe between them works like a logical or, giving both of them), and setting the propagation flags to none. Why should we do this? the answer is simple, because it worked (after few hours of trial and error).

The complete code for the Commit event granting full permissions to the Windows Services' LocalService account is shown below: 
Code:

public override void Commit(System.Collections.IDictionary savedState)
{
   base.Commit(savedState);

   DirectorySecurity dirSec = Directory.GetAccessControl(savedState["TargetDir"].ToString());
   FileSystemAccessRule fsar = new FileSystemAccessRule(@"NT AUTHORITY\SERVICE"
 
                                 , FileSystemRights.FullControl
                                 , InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
                                 , PropagationFlags.None
                                 , AccessControlType.Allow);
   dirSec.AddAccessRule(fsar);
   Directory.SetAccessControl(savedState["TargetDir"].ToString(), dirSec);
}

 
We removed the code using the streamWriter as it is not relevant to change the TARGETDIR permissions. After these changes and installing the application, the target directory permissions for the NT AUTHORITY\SERVICE account are shown below; the account NT AUTHORITY\SERVICE is represented by the SERVICE account in the picture:



USING THE UNINSTALL EVENT TO CLEAN THE TARGET DIRECTORY 
Well, after working long hours and having countless meetings with your client, they decided to Uninstall your solution, or perhaps they were so thrilled that a new and more powerful one will replace the original one. Regardless of the reason, applications will not remain installed forever, sometime they have to go, and when this happens you want everything under its home directory (known as target directory by the deployment project) to get deleted. The deployment project's uninstall process will get rid of all the objects it installed (including your installer class), but its home directory may not be deleted if it is not empty and your application may have created files (log files, temp files, config files, registry entries, etc) that the deployment project is unaware of, so it will not consider deleting them at uninstallation time; this is a situation that your installer class' UNINSTALL event should take care of. 
The code below is for an installer class UNINSTALL event cleaning the target directory. 
Code:

public override void Uninstall(System.Collections.IDictionary savedState)
{
   base.Uninstall(savedState);

   String _TargetDir;

   _TargetDir = savedState["TargetDir"].ToString();

   if (File.Exists(_TargetDir + "DB.log") == true)
   {
      File.Delete(_TargetDir + "DB.log");
   }
   if 
(File.Exists(_TargetDir + "DB_Settings.log") == true)
   {
      File.Delete(_TargetDir + "DB_Settings.log");
   }
   if (File.Exists(_TargetDir + "DB.config") == true)
   {
      File.Delete(_TargetDir + "DB.config");
   }
}


You should not be concerned about deleting the Installer Class and its InstallState files as the un-install process will delete them at the very end, your IC's Uninstall event should delete whatever was created outside the initial installation. 
WHERE IS THE "NT AUTHORITY\SERVICE" ACCOUNT COMING FROM? 
One way to find the account a windows service is running under is by adding these lines of code in the Windows Service's OnStart event: 
Code:

   WindowsIdentity self = WindowsIdentity.GetCurrent();
   SecurityIdentifier selfSID = self.User;

   StreamWriter sw = new StreamWriter("C:\\Temp\\Iam.txt");
   sw.WriteLine("I am " + self.Name);
   sw.WriteLine("wow " + self.Groups.ToString());
   sw.Flush();
   sw.Close();


You will need the following namespaces for the code above to work 
Code:

using System.Security;
using System.Security.AccessControl;
using System.Security.Principal;
using System.IO; 


You should make sure, the Temp folder exists on the machine where you are running the Windows Service. The account NT AUTHORITY\SERVICE was found with the code above on a Windows Xp machine, it may change elsewhere, like Windows 2000 or 2003 Servers. 

EXCEPTIONS AND EXCEPTION HANDLING IN YOUR INSTALLER CLASS 
Your code in any Installer Class' event should handle any possible exception, if any exception is untrapped the application's whole installation or uninstallation process will fail; there is no way for the installation-uninstallation process to continue when your installer class raises an exception.

Sometimes anyone of the events in your installer class will find a no-go condition, a situation where you have to abort the process involved (Installation or Un-installation), what you do here is throwing an InstallException exception, using code like the one shown below: 
Code:

throw new InstallException(); 

That's the most simple way to throw an Installer Class exception, so simple that it does not describe the error, giving the user installing your application no-clues regarding the error condition, so you should avoid this approach.

You may give the user more information when throwing the InstallException, with code like this one: 

Code:

if (File.Exists("Test.txt") == false)
{
   throw new InstallException("File does not exist!");
}

If the condition shown in the code above return a true value the "File does not exist!" will be thrown and the process involved will be cancelled; the user will get an screen like the one below: 


Another way to throw an Installer Class' exception is while handling an exception, in this case you may want to include details of the real exception, like the code below illustrates: 
Code:

try
{
   throw new
 IOException("Forcing an error");
}catch (Exception ex)
{
   throw new
 InstallException("A forced exception", ex);
}

It forces an IOException for illustration only, your own installer class event may throw its own exception due to the complexity of the code in execution, anyhow, in this case the installation or installation process will stop with a diplay like the one below: 


As a feature of the Windows Installer module, any exception is recorded at the target machine's eventlog, you can use the Event Viewer (at the Control Panel's Administrative Tools. 


Remember: any exception in your installer class will prevent your application's installation (or un-installation).

You may not like using exceptions to report installation issues with your application, perhaps you want to show a more friendly interface to your enduser at installation time, probably the error condition is not that critical to cancel the installation at all, in all these scenarios, you may want to show a friendly form to your user, allowing him/her to continue with the installation process. 




ADDING USER INTERFACES (FORMS) TO YOUR INSTALLER CLASS

You can implement windows forms into your Installer Class fairly easy. First you should add a Reference to the System.Windows.Form namespace to your Installer Class project.


Then, add a reference to this namespace at the top of your installer class, with the following using statement:
Code:

using System.Windows.Forms; 

Next click on Project (in your installer class IDE) followed by Add Windows Form; that's partially it. This form will contain all the control your installation requires.

Now, within any of the Installer Class events you can open the form with the code below:
Code:

frmMonitor f = new frmMonitor("Install");
f.ShowDialog(); 

In the example, the form was named frmMonitor and it is taking a single parameter. We passed Install to it (as shown in the code); You should always keep in mind that installer classes have different "installation modes", such us InstallCommitRollback and Uninstall. You may implement individual forms for each one of these modes or a single one capable of handling any combination of them; the latter will require a parameter telling the form the "installation mode" taking place, but the choice is yours.

Also notice that the form is shown as a dialog (ShowDialog()). It should be like that to prevent the event completion before the user even gets a chance to see your form.

Based on the explanation given in this section so far, the screenshot below was taken from an installation having an Installer Class with a form showing the Install event's Context and stateSaver dictionaries on its form's multi line textbox: 



The form on the latest example receives three parameters in one of its constructors, as shown below:
Code:

public frmMonitor(string eventName
     , System.Configuration.Install.InstallContext context
     , System.Collections.IDictionary savedState
     )
   {

Where:
  • eventName is the name of the event calling the form.
  • context is the variable receiving the Installer Class context dictionary. Notice its type, which is System.Configuration.Install.InstallContext
  • savedState is the savedStated parameter received by the Installer Class's event.
The Installer Class's Install event code is shown below:
Code:

public override void Install(System.Collections.IDictionary stateSaver)

   base.Install(stateSaver);
   stateSaver.Add("TargetDir", Context.Parameters["DP_TargetDir"].ToString());
   frmMonitor f = new frmMonitor("Install", Context, stateSaver);
   f.ShowDialog();
   f.Dispose();
}


The tricky part of the example is how to pass around the Installer Class Context object.
KEEPING THE MOUSE WITHIN THE FORM SHOWN AS ShowDialog()
Although the form is shown by the ShowDialog() method, the mouse can move away from it, able to click on the Installer main form displayed behind it, this is an undesired behaviour, it probably happens because your form and the Installer are running on different threads, you can prevent this behaviour by trapping the mouse within your form boundaries. Any attempt for the mouse to leave your form borders will keep it inside it, you can do that with the form's MouseMove event, as explained next:
You should declare a couple of private variables, _X and _Y, they will keep track of your mouse position within the form.
   private int _X; // mouse's X position 
   private int _Y; // mouse's Y position

Then within the form's mouse move event, you record the mouse current position like this:
 private void Form1_MouseMove(object sender, MouseEventArgs e)
 {
    _X = e.X;
    _Y = e.Y;
 }

Now, when the mouse tries to leave the form, you can keep it inside its boudaries by using the Mouse Leave event, with the code show next:
private void Form1_MouseLeave(object sender, EventArgs e)
{
   if (Cursor.Position.X < this.Left + 4 || Cursor.Position.Y < this.Top + 30 || Cursor.Position.X >this.Left + this.Width - 5 || Cursor.Position.Y > this.Top + this.Height - 31)
   {
      Cursor.Position = new Point(this.Left + _X + 4, this.Top + _Y + 30);
   }
}

Here the constants 4, 5, 30 and 31 are related to the form borders and title bar, if your form does not have border or a title bar, you should adjust the code above accordingly.

I tested the code above with the following form: 

The mouse pointer was able to "escape" from the form when moving it really fast over the buttons (side ways) or any control on the form, my guess is that the mouse events on those controls obscures the form own mouse events allowing the mouse pointer to escape, once I made the form higher and widers, it was most difficult for the mouse pointer to escape.

LAUNCH YOUR APPLICATION AFTER INSTALLATION 
You can launch your application once it has been installed with the Installer Class' Commit event. Although possible, you should carefully assess implementing this feature, particularly so, when your application has any dependency with any installed component that requires rebooting the workstation (Target Machine); in the latter case, your application will mercilessly crash on the user installing it.

Now that we are aware of the disclaimer, you should add a reference to the System.Diagnostics at the top of your Installer Class code: 
Code:

using System.Diagnostics; 

Then you can launch your application with this code located at the Commit event in your Installer Class. Code:

public override void Commit(System.Collections.IDictionary savedState)
{
   base.Commit(savedState);
   
   // let's launch the application 

   Process.Start(@savedState["TargetDir"].ToString() + "Testings");
}
 

Comments:
  • Testings is the application the Installer Package is installing, you don't have to end it with the .exe suffix.
  • We are using the TargetDir property saved into the Installer Class' savedState object (dictionary) as explained earlier in this article.
  • The application (Testing) is launched when the installation is about to finish, because of this, the user will see your application and the installer completion form simultaneously as shown below: 

CONCLUSIONS 
  • Visual Studio Setup and Deployment ProjectsInstaller Class implementation as Custom Actions expose powerful features at your disposal to create very professional and robust installation packages for your applications.
  • It will take a while to master the different features exposed by the Installer Class. We strongly recommend throughly testing them before distributing your application,. Keep in mind that first impressions count in your users (customers) mind. You don't want your application to crash at installation time, or end up having to request your customers to apply several changes to the environment to complete your application installation; It will be wise to test your installation package on a Virtual PC environment or any spare PC made available to you.
  • Unhandled exceptions are your worst enemy when developing and implementing Installer Class objects. You should carefully assess the code you are using without taking risky assumptions. Keep in mind that the Target PC where your application will be installed on, is not within your control.

    Remember, this article is based on VS 2005 Setup and Deployment Projects and its Installer Class object. Although previous versions of Visual Studio support them (Installer Class objects) you should consider testing your functionalities if you are not using VS 2005; They may well work, Provoding that everything is hooked properly.

    At the time we wrote this article, the installation's Rollback event was failing to fully delete the TargetDir on the target PC.
  • There is no limitation (or we are not aware of any) on the number of Installer Class objects your Setup and Deployment Projects can reference. Based on this, you should not overload your Installer Class object with many functionalities making them very complex. Think about implementing specialized Installer Class objects instead. 
  • You should become familiar with the Environment and Application objects when developing Installer Class modules. Both objects expose helpful properties, like the operating system version, so keep an eye on them.

沒有留言:

張貼留言