Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

 

patterns & practices Developer Center

How To: Host a Remote Object in a Windows Service

J.D. Meier, Alex Mackman, Michael Dunner, and Srinath Vasireddy
Microsoft Corporation

Published: November 2002

Last Revised: January 2006

Applies to:

  • Remoting (Microsoft® .NET Framework 1.1)

See the "patterns & practices Security Guidance for Applications Index" for links to additional security resources.

See the Landing Page for a starting point and complete overview of Building Secure ASP.NET Applications.

Summary: Objects called using the .NET Remoting infrastructure can be hosted by ASP.NET, custom executables or Windows services. This How To shows you how to host a remote object in a Windows service and call it from an ASP.NET Web application. (7 printed pages)

Contents

Notes
Summary of Steps Step 1. Create the Remote Object Class Step 2. Create a Microsoft Windows® Service Host Application Step 3. Create a Windows Account to Run the Service Step 4. Install the Windows Service Step 5. Create a Test Client Application
Additional Resources

This How To describes how to host a remote object in a Windows service and call it from an ASP.NET Web application.

Notes

  • Remote objects (that is, .NET objects accessed remotely using .NET Remoting technology) can be hosted in Windows services, custom executables, or ASP.NET.
  • Clients communicate with remote objects hosted in custom executables or Windows services by using the TCP channel.
  • Clients communicate with remote objects hosted in ASP.NET by using the HTTP channel.
  • If security is the prime concern, host objects in ASP.NET and use the HTTP channel. This allows you to benefit from the underlying security features of ASP.NET and IIS.

For information about how to host a remote object in ASP.NET (with IIS), see article Q312107, "HOW TO: Host a Remote Object in Microsoft Internet Information Services."

  • If performance is the prime concern, host objects in a Windows service and use the TCP channel. This option provides no built-in security.

Summary of Steps

This How To includes the following steps.

  • Step 1. Create the Remote Object Class
  • Step 2. Create a Microsoft Windows® Service Host Application
  • Step 3. Create a Windows Account to Run the Service
  • Step 4. Install the Windows Service
  • Step 5. Create a Test Client Application

Step1. Create the Remote Object Class

This procedure creates a simple remote object class. It provides a single method called Add that will add two numbers together and return the result.

To create the remote object class

  1. Start Microsoft Visual Studio® .NET and create a new Microsoft Visual C#® Class Library project called RemoteObject.

  2. Use Solution Explorer to rename class1.cs as Calculator.cs.

  3. In Calculator.cs, rename Class1 as Calculator and rename the default constructor accordingly.

  4. Derive the Calculator class from MarshalByRefObject to make the class remotable.

    public class Calculator : MarshalByRefObject
    
  5. Add the following public method to the Calculator class.

    public int Add( int operand1, int operand2 )
    {
      return operand1 + operand2;
    }
    
  6. On the Build menu, click BuildSolution.

Step 2. Create a Windows Service Host Application

This procedure creates a Windows service application, which will be used to host the remote object. When the service is started it will configure the TCP remoting channel to listen for client requests.

Note   This procedure uses an Installer class and the Installutil.exe command line utility to install the Windows service. To uninstall the service, run Installutil.exe with the /u switch. As an alternative, you could use a Setup and Deployment Project to help install and uninstall the Windows service.

To create a Windows Service host application

  1. Add a new Visual C# Windows Service project called RemotingHost to the current solution.

  2. Use Solution Explorer to rename Service1.cs as RemotingHost.cs.

  3. In RemotingHost.cs, rename the Service1 class as HostService and rename the default constructor accordingly.

  4. At the top of the file, add the following using statement beneath the existing using statements.

    using System.Runtime.Remoting;
    
  5. Locate the Main method and replace the existing line of code that initializes the ServicesToRun variable with the following.

    ServicesToRun = new System.ServiceProcess.ServiceBase[] { 
                                                new HostService() };
    
  6. Locate the InitializeComponent method and set the ServiceName property to RemotingHost.

    this.ServiceName = "RemotingHost";
    
  7. Locate the OnStart method and add the following line of code to configure remoting. The fully qualified path to the configuration file will be passed as a start parameter to the service.

    RemotingConfiguration.Configure(args[0]);
    
  8. Add a new C# class file to the project and name it HostServiceInstaller.

  9. Add an assembly reference to the System.Configuration.Install.dll assembly.

  10. Add the following using statements to the top of HostServiceInstaller beneath the existing using statement.

    using System.ComponentModel;
    using System.ServiceProcess;
    using System.Configuration.Install;
    
  11. Derive the HostServiceInstaller class from the Installer class.

    public class HostServiceInstaller : Installer
    
  12. Add the RunInstaller attribute at the class level as follows.

     [RunInstaller(true)]
    public class HostServiceInstaller : Installer
    
  13. Add the following two private member variables to the HostServiceInstaller class. The objects will be used when installing the service.

    private ServiceInstaller HostInstaller;
    private ServiceProcessInstaller HostProcessInstaller;
    
  14. Add the following code to the constructor of the HostServiceInstaller class.

    HostInstaller = new ServiceInstaller();
    HostInstaller.StartType = 
      System.ServiceProcess.ServiceStartMode.Manual;
    HostInstaller.ServiceName = "RemotingHost";
    HostInstaller.DisplayName = "Calculator Host Service";
    Installers.Add (HostInstaller); 
    HostProcessInstaller = new ServiceProcessInstaller();
    HostProcessInstaller.Account = ServiceAccount.User;
    Installers.Add (HostProcessInstaller);
    
  15. Within Solution Explorer, right-click RemotingHost, point to Add, and then click Add New Item.

  16. In the Templates list, click TextFile and name the file app.config.

    Configuration files with the name app.config are automatically copied by Visual Studio .NET as part of the build process to the output folder (for example, <projectdir>\bin\debug) and renamed as <applicationname>.config.

  17. Click OK to add the new configuration file.

  18. Add the following configuration elements to the new configuration file.

    <configuration>
    <system.runtime.remoting>
      <application name="RemoteHostService">
        <service>
          <wellknown type="RemoteObject.Calculator, RemoteObject" 
                     objectUri="RemoteObject.Calculator" 
                       mode="Singleton" />
        </service>
        <channels>
          <channel ref="tcp" port="8085">
            <serverProviders>
              <formatter ref="binary" />
            </serverProviders>
          </channel>
        </channels>
      </application>
    </system.runtime.remoting>
    </configuration>
    
  19. On the Build menu, click Build Solution.

Step 3. Create a Windows Account to Run the Service

This procedure creates a Windows account used to run the Windows service.

To create a Windows account to run the service

  1. Create a new local user account called RemotingAccount. Enter a password and select the Password never expires check box.
  2. In the AdministrativeTools programs group, click Local Security Policy.
  3. Use the LocalSecurityPolicy tool to give the new account the Log on as a service privilege.

Step 4. Install the Windows Service

This procedure installs the Windows service using the installutil.exe utility and then start the service.

To install the Windows service

  1. Open a command window and change directory to the Bin\Debug directory beneath the RemotingHost project folder.

  2. Run the installutil.exe utility to install the service.

    installutil.exe remotinghost.exe
    
  3. In the SetServiceLogin dialog box, enter the user name and password of the account created earlier in procedure 3 and click OK.

    View the output from the installutil.exe utility and confirm that the service is installed correctly.

  4. Copy the RemoteObject.dll assembly into the RemotingHost project output directory (that is, RemotingHost\Bin\Debug).

  5. From the AdministrativeTools program group, start the Services MMC snap-in.

  6. In the Services list, right-click Calculator Host Service, and then click Properties.

  7. Enter the full path to the service's configuration file (remotinghost.exe.config) into the Start parameters field.

    Note   A quick way to do this is to select and copy the Path to executable field and paste it into the Startparameters field. Then append the ".config" string.

  8. Click Start to start the service.

  9. Confirm that the service status changes to Started.

  10. Click OK to close the Properties dialog box.

Step 5. Create a Test Client Application

This procedure creates a test console application that is used to call the remote object within the Windows service.

To create a test client application

  1. Add a new Visual C# Console application called RemotingClient to the current solution.

  2. Within Solution Explorer, right-click RemotingClient, and then click Set as StartUp Project.

  3. Add an assembly reference to the System.Runtime.Remoting.dll assembly.

  4. Add a project reference to the RemoteObject project.

  5. Add the following using statements to the top of class1.cs beneath the existing using statements.

    using System.Runtime.Remoting.Channels;
    using System.Runtime.Remoting.Channels.Tcp;
    using RemoteObject;
    
  6. Add the following test code to the Main method to call and invoke the Calculator object hosted by the Windows service.

    TcpChannel chan = new TcpChannel();
    ChannelServices.RegisterChannel(chan);
    Calculator calc = (Calculator)Activator.GetObject(
                             typeof(RemoteObject.Calculator),
                     "tcp://localhost:8085/RemoteObject.Calculator");
    if (calc == null) 
      System.Console.WriteLine("Could not locate server");
    else 
      Console.WriteLine("21 + 21 is : " + calc.Add(21,21) );
    
  7. On the Build menu, click BuildSolution.

  8. Run the client application and confirm that the correct result is displayed in the console output window.

Additional Resources

For information about how to host a remote object in ASP.NET (with IIS), see article Q312107, "HOW TO: Host a Remote Object in Microsoft Internet Information Services".

patterns & practices Developer Center

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

© Microsoft Corporation. All rights reserved.