Advanced Web and Worker Roles
Exercise 2: Using Start-Up Tasks to Register a COM Component

Collapse All Expand All Language Filter: All Language Filter: Multiple Language Filter: Visual Basic Language Filter: C#

Visual Basic Usage
C#

A start-up task is a command, either an executable or a script, executed prior to the start of a role instance. The command can perform set up tasks that are required to prepare the environment for the application, such as installing applications, registering COM components, configuring IIS settings, or registering performance counters.

In this exercise, you explore the use of start-up tasks to configure the environment where a service executes. To do this, you will use a sample Web application that requires a COM component to work.

Task 1 – Registering a COM Component

Many applications today still rely on functionality provided by “legacy” COM components. Moving these applications to the cloud requires that each virtual machine instance hosting the application have the necessary components installed and registered. Registration needs to be carried out upon role start up and requires administrative privileges.

In this task, you create a start-up task that registers the COM component required by the sample application.

Note:
Important: Make sure that you have launched the dependency checker to set up the lab before starting this task. The setup procedure builds the COM component required by the solution from source code in the Assets folder. Note that you need to have Visual C++ installed for this purpose. In addition, to use the COM component, the identity of the process instantiating it must have access to the directory where the component is installed. To ensure this, avoid launching the service from a location inside your user profile folder and instead, copy the project files to a folder with unrestricted permissions, for example, to a folder within the default installation location of the training kit, C:\WAPTK.

1. Start Microsoft Visual Studio 2010 as an administrator.
2. Open the Begin solution located in Ex2-StartupTasks in the Source folder of the lab. The solution contains a Windows Azure project and a Web role that makes use of the LegacyCOM component.

   Note:
   The LegacyCOM project, located in the Assets folder of the lab, implements a very simple COM library using Active Template Library (ATL). The library contains a single component class with a method that receives a name parameter and returns a greeting message.

3. Press F5 to build and run the application. During the build process in Visual Studio, a pre-build event registers the COM component. A message box should notify you when the registration succeeds. Click OK to proceed.

   Figure 8
   Successful COM component registration

   Note:
   Normally, the Visual C++ development environment takes care of the registration. Here, the automatic registration in the LegacyCOM project has been intentionally disabled and instead, a post-build event configured to handle this requirement and to produce an explicit message to notify you when this occurs. Later in this task, you will see that the component, which only needs to be registered to build the solution, will be unregistered by a post-build step.

4. Wait for the application to launch in the Compute Emulator and for the Home page to open in your browser. Then, enter your name and then click Greet me. Notice that the application responds with a greeting message generated by the COM component.

   Figure 9
   Running application showing the output from the COM component

5. Close the browser window to stop debugging and shut down the application.
6. In the Build Events tab of the SampleWebApp project’s properties, add a post-build event to unregister the COM component after the Web application is built. Use the following command line.

   Post-build event command line | Copy Code
   --- | ---
       IF DEFINED PROCESSOR_ARCHITEW6432 (SET DEV_PLATFORM=%PROCESSOR_ARCHITEW6432%) ELSE (SET DEV_PLATFORM=%PROCESSOR_ARCHITECTURE%)
       regsvr32.exe /u "$(ProjectDir)\%DEV_PLATFORM%\LegacyCOM.dll"

   Note:
   To build the Web application, the component must be registered on the development machine. However, because you are using the same machine to launch the application in the compute emulator, you need to ensure that the COM component is not registered when you test the startup task; otherwise, you will be unable to determine whether the task succeeded.

7. You will now execute the application without the required COM registration. Press F5 to build and run the application in the compute emulator. Notice that when the solution builds, you first receive a notification that the COM component has been registered, and then, after the build completes, a second notification indicating that the component has been unregistered. Click OK to dismiss both message boxes.

   Figure 10
   Successful unregistration of the COM component after the build completes

8. Wait for the application to launch in the compute emulator and for the Home page to open in your browser. In the browser window, enter your name and click Greet me. Notice that after submitting the form, an exception is raised and execution halts in the debugger.

   Figure 11
   COMException raised when the COM component is not registered

9. Press F5 to continue execution and allow the exception to be handled by ASP.NET.

   Figure 12
   ASP.NET unhandled exception handler

10. Close the browser window to stop debugging and shut down the application.
11. Next, define a startup task to set up the role and register the COM component. To do this, open the ServiceDefinition.csdef file in the Windows Azure project, locate the WebRole element in the service model and inside it, insert a Startup element with a single task, as shown below.

    (Code Snippet – AdvancedWebAndWorkerRoles-Ex2-01-StartUpTask-XML)

    XML | Copy Code
    --- | ---
        <ServiceDefinition name="CloudService" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition">
          <WebRole name="SampleWebApp">
            <Sites>
              <Site name="Web">
                <Bindings>
                  <Binding name="HttpIn" endpointName="HttpIn" />
                </Bindings>
              </Site>
            </Sites>
            <ConfigurationSettings>
            </ConfigurationSettings>
            <Endpoints>
              <InputEndpoint name="HttpIn" protocol="http" port="80" />
            </Endpoints>
            <Imports>
              <Import moduleName="Diagnostics" />
            </Imports>
        <Startup>
              <Task commandLine="Register.cmd" executionContext="elevated" taskType="simple" />
            </Startup>
          </WebRole>
        </ServiceDefinition>

    Note:
    The Startup element contains one or more Tasks that the role executes during its bootstrapping process. Each task includes a commandLine parameter that defines a program or a batch file to execute. Tasks can specify an executionContext that allows them to run in the same security context as the role or with administrative privileges. Because registering a COM component requires writing information to a registry hive that is not accessible to regular users, the registration task uses an elevated execution context. Additionally, tasks can specify a type that determines how they are scheduled. The following types are available: Simple: the startup process launches the task and does not proceed until the task completes. Background: the startup process launches the task in the background and then continues. Foreground: similar to a background task, but the role cannot shut down until all the foreground tasks have ended.

12. Create a new text file in the root of the SampleWebApp project and name it Register.cmd. This file will contain a script to register the COM component.
13. Add the following content to the Register.cmd script.

    Command | Copy Code
    --- | ---
        echo off
        regsvr32.exe /s "%~dp0%PROCESSOR_ARCHITECTURE%\LegacyCOM.dll"

    Note:
    The script shown above registers the COM component using the regsvr32.exe utility that is normally present in any Windows distribution and is available in the Windows Azure Guest OS. It registers the version of the component appropriate to the platform where the role is running. Notice that the path that specifies the component to register uses the %PROCESSOR_ARCHITECTURE% environment variable to select the folder that matches the current platform, either amd64 for 64-bit systems or x86 for 32-bit systems. This allows you to run the same script locally, during development, if you are working on a 32-bit OS, or in the cloud, when you deploy the application to the 64-bit Windows Azure environment. Note that the lab setup procedure builds the COM component for both platforms. Normally, during registration, the regsvr32.exe utility produces a message box that requires confirmation. When hosted in the compute emulator, you can close the dialog and proceed with the startup process. However, when deploying to Windows Azure, if the task stops to wait for user input, it will block, causing the role to remain in a busy state and never start. For this reason, the registration is performed in silent mode by appending an /s parameter to the command line.

14. Set the Copy to Output Directory property of the script file to Copy always and make sure that its Build Action property is set to None.

    Figure 13
    Copying the startup script to the output directory

15. Once again, press F5 to build and run the application in the compute emulator.
16. Wait for the application to launch in the Compute Emulator and for the Home page to open in your browser. Then, enter your name and then click Greet me. Notice that the application responds with a greeting message confirming that the start-up task successfully registered the COM component.
17. Close the browser window.
18. Optionally, you may want to deploy the service package to Windows Azure and test the COM registration process in the cloud.

    Note:
    For this lab, you have access to the source code for the COM component and are able to build and deploy the 64-bit version when deploying to Windows Azure. If you need to register a COM component for which you do not have source code, be aware that 32-bit components cannot be accessed directly by a 64-bit role process, and instead need to be launched in a separate surrogate process.