Click here to Skip to main content
11,481,838 members (63,664 online)
Click here to Skip to main content

Remoting from IIS Hosted component to ASP.NET Client application

, 17 Apr 2003 65.9K 3 31
Rate this:
Please Sign up or sign in to vote.
A walkthrough to set up a remoting server app on IIS, consumed by an ASP.NET client web application.

Introduction

This walkthrough will show how to set up a simple component on IIS and access it through an ASP.NET webapp. Please refer to other articles to get background information on remoting. The goal of this project is to:

  1. Make a remote service hosted on IIS that authenticates users
  2. Make wrapper classes to abstract the remoting "fabric" to the client
  3. Set up an ASP.NET web application to consume the remote service through the wrapper assembly

No demo project is provided here because you'll have to do some setup with IIS an so forth yourselves. I didn't get this subject myself before I actually struggled with it on my own. So the intent here is to guide you through the process.

Background

There are a lot of literature on .NET remoting out there. Ingo Rammer's book "Advanced .NET Remoting" is told to be great and his website (www.dotnetremoting.cc) for sure are. Other sources for this subject can be somewhat complex from time-to-time because they often are written by experienced COM/DCOM programmers. For me it seemed as they made it more difficult than it is. This is why I made this simple straight-forward walkthrough to get remoting up and running in a known environment for ASP.NET programmers. Here is my blog from yesterday with some more background.

First off: Define your service

Before you start coding, decide what your service is supposed to do, because you're going to make an interface. The interface will be built in a separate assembly (DLL) and deployed with both client and server application, so they have a common ground. My service, in this case, is supposed to authenticate users so I'll define my interface like this:

public interface IAuthenticationService
{
    string Authenticate(string username, string password);
}

The interface takes username/password as parameters and returns an encrypted FormsAuthenticationTicket (as String) that the ASP.NET application will use for creating a cookie for the authenticated user.

Secondly: The server application

To be able to run a class as a .NET remoting service you have to make a class that inherits MarshalByRefOBject. We also want the class to implement the IAuthenticationService interface defined above, so the client can use it.

public class AuthenticationService : MarshalByRefObject, 
                                       IAuthenticationService
{
    private IUserDAO UserDAO;
    
    public AuthenticationService()
    {
        // Get an instance of our User Data Access Object
        UserDAO = (IUserDAO)ServiceLocator.Instance.
                  DataAccessObjectGet(StorageTypes.SqlServer, 
                  Services.UserService);
    }

    
    public string Authenticate(string username, string password)
    {
        UserItem user;
        try
        {
            // Get the user from the datastore and validate password
            user = UserDAO.UserByEmailGet(username);
            if(!(user.Password.CompareTo(password) == 0))
                return "";
        }
        catch(eFactory.Data.NoDataFoundException)
        {
            // User Not found
            return "";
        }

        // Create Userdata - omitted for clarity
        return encryptedTicket;
    }
}

Piece of cake. Inherit MarshalByRefObject (from System.Runtime.Remoting) and implement the interface we made earlier. In this example I use a singleton ServiceLocator class to delver an instance of a data access object for the data-service, UserService. Then this service (UserDAO) is used to fetch the user object that contains the password.

Now we can compile our server component and deploy our service to IIS. If you have IIS installed the simplest thing to do is:

  1. Create a new virtual folder on IIS (through inetmgr.exe) that points to the directory containing our server project. Beware that the name you provide for the folder also will be the application name in IIS.

    You might experience some trouble with setting up the virtual folder on IIS. One hint is that all parent directories of the one you assign as a virtual IIS folder must allow the ASPNET user to read, execute and list. Otherwise consult MSDN for advice on setting up virtual folders.

  2. Make sure that the DLL is placed directly under the \bin folder (not in \bin\debug!)
  3. Create a Web.Config file in the root of the virtual folder (our project folder). This Web.config file needs to hold the remoting settings (deployment description). Additionally you'd probably want to include some database connection strings and so forth if you are doing lookups in your authenticate method. The server web.config looks like this:
    <configuration>
    <system.runtime.remoting>
    <application>
        <service>
            <wellknown    
                mode="SingleCall" 
                type="CodeProject.AuthenticationService, 
                                 AuthenticationServiceComponent"
                objectUri="AuthenticationService.soap" />
        </service>
        <channels>
            <channel    
                name="TheChannel"
                priority="100"
                ref="http" />
        </channels>
        </application>
    </system.runtime.remoting>
    <appSettings>
        <add key="SqlServer" value="connstring"/>
    </appSettings>
    </configuration>

The remoting part of the config file is contained by the <system.runtime.remoting> tags. The application element inside is set up automatically by ASP.NET and IIS so we don't have to specify any attributes (specifying the name attribute would conflict because the name of our application is already set to be the same as the name of the virtual directory).

Then we specify our services. ASP.NET only supports well-known services (not client-activated) so we don't have to think much about that. The really important thing here is the type attribute. The first parameter here is the fully qualified class name of our service. My AuthenticationService class was compiled in the namespace CodeProject as you can see. The second parameter in the type attribute is the name of the DLL file. This file resides in the \bin directory of the IIS virtual folder and contains the class CodeProject.AuthenticationService. The third attribute is objectUri and defines a URI for our service. Just set it to [classname.soap] for now.

What's left here is to define a channel for IIS to use for this service. We'll give it a name, TheChannel, set a priority flag and make a reference to the pre-defined "HTTP" channel in machine.config.

Finally I had to add my database connection stringSmile | :)

Now you should be able to check out your service by entering it's URL and get the WSDL. like this:

http://hostname/VirtualFolderName/objectUri?wsdl in my case: http://localhost/AuthenticationRemotingService/AuthenticationService.soap?wsdl.

Really cool isn't it?

Next lets make the client! Or not yet?

I found it convenient to wrap all remoting code in a supporting assembly to catch remoting errors and such. Because others (other coders) that are going to use this service have to import my Interface assembly anyways, it won't hurt to supply some wrappers.

I chose to make a singleton class to front my service. The only thing it does is to get the remote object and call on the authenticate service and return it's value as a HttpCookie. If something goes wrong it catches the exception. It also hides some semi-nasty implementation code to be able to instantiate an object of our interface type without having to hardcode the URL. I did a slight rewrite of Ingo Rammers RemotingHelper class, converting it to a singleton to accomplish this.

This is the LoginHandler wrapper class:

public sealed class LoginHandler
{
    public static readonly LoginHandler Instance = new LoginHandler();

    private LoginHandler(){}

    public HttpCookie DoLogin(string username, string password)
    {
        try
        {
            IAuthenticationService auth =             
                (IAuthenticationService)RemotingHelper.Instance.GetObject
                (typeof(IAuthenticationService));
        }
        catch(System.Runtime.Remoting.RemotingException ex)
        {
            //do some logging
            return "";
        }
        
        string ticket = auth.Authenticate(username, password);
        if(ticket == "")
            return null;
        else
            return new System.Web.HttpCookie(FormsAuthentication.
                            FormsCookieName, ticket);

    }    
}

The rewrite of Ingo Rammer's class:

internal sealed class RemotingHelper 
{
    public static readonly RemotingHelper Instance = 
                                  new RemotingHelper();

    private IDictionary wellKnownTypes;

    private RemotingHelper() 
    {
        wellKnownTypes = new Hashtable();
        foreach (WellKnownClientTypeEntry entr in 
            RemotingConfiguration.GetRegisteredWellKnownClientTypes()) 
        {
              if (entr.ObjectType == null) 
            {
                throw new RemotingException("A configured 
                  type could not be found. Please check spelling");
            }
            wellKnownTypes.Add (entr.ObjectType,entr);
        }
    }

    public Object GetObject(Type type) 
    {
        WellKnownClientTypeEntry entr = 
                (WellKnownClientTypeEntry)wellKnownTypes[type];
        if(entr == null) 
        {
            throw new RemotingException("Type not found!");
        }
        return Activator.GetObject(entr.ObjectType,entr.ObjectUrl);
    }
}

When instantiated this class reads all available well-known types from the registered types collection in the RemotingConfiguration. It then compares the class name you provide in GetObject to the well-known types. Without this class, you'd have to hardcode the service server URL or get this from the config file.

Off to the ASP.NET client webapp!

Now its playtime. All the hard work is nearly done. Finish off by:

  1. Create a new ASP.NET web application.
  2. Add references to the Wrapper-, and Interface assemblies.
  3. Open the client application web.config file.

    You will need to let your client application know where to find the implementation of the interface defined in the assembly you just added. It's the implementation of this interface we will "remote". Just like for the server config file you have to place a system.runtime.remoting element as a sub-element to <configuration> Its done like this:

    <system.runtime.remoting>
    <application>
        <client url="http:/localhost/YourIISVirtualFolderName
                                  /AuthenticationService">
            <wellknown    
            type="CodeProject.IAuthenticationService, 
                           RemotingInterfacesComponent" 
            url="http://localhost/YourIISVirtualFolderName/
                            AuthenticationService.soap" />
        </client>
    </application>
    </system.runtime.remoting>

    The URL of the client element is the address of your virtual folder on IIS that you defined for your server component. Then we define a well-known type which is describing the fully qualified name for the interface we made first off in this walkthrough, and the second parameter is (like in the server config) the name of the DLL containing this interface. This DLL must of course be available and referenced by our ASP.NET client web app. The last parameter is the URL to the service + the objectUri that we defined in the server web.config file. We don't need to set up any channels here. IIS will handle it.

  4. Finally to make your client actually set up the remoting you have to kick start it when the application starts up. Open the global.asax and enter this line in the Application_Start event handler.
    protected void Application_Start(Object sender, EventArgs e)
    {
        RemotingConfiguration.Configure(Server.MapPath("Web.config"));
    }

    This will read the remoting section in the web.config and set it all in place (or generate a kick-ass remotingexception when you start up your webappSmile | :)

Now go ahead and call the wrapper class LoginHandler from your web-client and enjoy the HttpCookie from the serviceSmile | :) Good luck!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Mads Nissen
Software Developer (Senior)
Norway Norway
http://weblogs.asp.net/mnissen
http://www.puzzlepart.com

Comments and Discussions

 
GeneralBuild error Pin
evb514530-Jun-06 12:04
memberevb514530-Jun-06 12:04 
QuestionIs there a code sample for this article? Pin
dsl200310-Apr-04 12:48
memberdsl200310-Apr-04 12:48 
AnswerRe: Is there a code sample for this article? Pin
suqingyang21-Jun-04 3:31
membersuqingyang21-Jun-04 3:31 
Generalregistering httpchannel in webform client side Pin
anonymous_guy10-Jul-03 16:31
memberanonymous_guy10-Jul-03 16:31 
GeneralRe: registering httpchannel in webform client side Pin
Mads Nissen11-Jul-03 1:46
memberMads Nissen11-Jul-03 1:46 
GeneralRe: registering httpchannel in webform client side Pin
anonymous_guy11-Jul-03 6:20
memberanonymous_guy11-Jul-03 6:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 18 Apr 2003
Article Copyright 2003 by Mads Nissen
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid