【转】How To: Host a Remote Object in a Windows Service

转自 http://msdn.microsoft.com/en-us/library/aa302410.aspx

 

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.

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.

    Copy Code

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

    Copy Code

    public int Add( int operand1, int operand2 )
    {
      return operand1 + operand2;
    }
  6. On the Build menu, click Build Solution.
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.

    Copy Code

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

    Copy Code

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

    Copy Code

    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.

    Copy Code

    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.

    Copy Code

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

    Copy Code

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

    Copy Code

     [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.

    Copy Code

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

    Copy Code

    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 Text File 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.

    Copy Code

    <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 Administrative Tools programs group, click Local Security Policy.
  3. Use the Local Security Policy 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.

    Copy Code

    installutil.exe remotinghost.exe
  3. In the Set Service Login 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 Administrative Tools 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 Start parameters 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.

    Copy Code

    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.

    Copy Code

    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 Build Solution.
  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".

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值