Apply Your Knowledge





Apply Your Knowledge

Exercises

Using HTTP Channels with Binary Formatters

As I discussed in the chapter, the default formatter for the HTTP channel is SOAP, and for the TCP channel is Binary. The formatters are used for serializing and deserializing messages in the specified encoding.

The chapter has made use of these default formatters in the examples. In this exercise, you'll learn how to configure a channel to use a formatter different from the default one.

In particular I'll demonstrate how to use the binary formatter with the HTTP channel. This combination is especially useful when you want to optimize the performance of a remote object that is hosted on IIS. However, you should note that binary format is proprietary to the .NET Framework.

Estimated Time: 30 minutes.

  1. Launch Visual Studio .NET. Select File, New, Blank Solution, and name the new solution 320C03Exercises. Click OK.

  2. Add a new empty Web project named Exercise3_1_Server to the solution.

  3. Add references to StepByStep3_9.dll (the interface assembly containing IDbConnect) and StepByStep3_10.dll (the remotable object, DbConnect).

  4. Add a new Web configuration file to the project. Open the web.config file and add the following <system.runtime.remoting> element inside the <configuration> element:

    
    <configuration>
    
        <system.runtime.remoting>
    
            <application>
    
                <service>
    
                   <!--Set the activation mode,
    
                      remotable object,
    
                      and its URL -->
    
                    <wellknown mode="Singleton"
    
                        type=
    
                     "StepByStep3_10.DbConnect, StepByStep3_10"
    
                        objectUri=
    
                           "DbConnect.rem" />
    
                </service>
    
            </application>
    
        </system.runtime.remoting>
    
    ...
    
    </configuration>
    
    

    IIS is now hosting the StepByStep3_10.DbConnect remotable class as a server-activated object by using the Singleton activation mode.

  5. Add a new Visual C# .NET Windows application named Exercise3_1_Client to the solution.

  6. Add references to StepByStep3_9.dll (the interface assembly containing IDbConnect).

  7. In the Solution Explorer, right-click project Exercise3_1_Client and select Add, Add New Item from the context menu. Add an item named Exercise3_1_Client.exe.config, based on the XML file template.

  8. Open the Exercise3_1_Client.exe.config file and modify it to contain the following code:

    
    <configuration>
    
        <system.runtime.remoting>
    
            <application>
    
                <channels>
    
                    <channel ref="http">
    
                        <serverProviders>
    
                            <formatter ref =
    
                                 "binary" />
    
                        </serverProviders>
    
                    </channel>
    
                </channels>
    
            </application>
    
        </system.runtime.remoting>
    
    </configuration>
    
    
  9. In the Solution Explorer, select the project and click the Show All Files button in the tool bar. Move the Exercise3_1_Client.exe.config file from the project folder to the bin\Debug folder under the project, where the Exercise3_1_Client.exe file will be created when the project is compiled.

  10. In the Solution Explorer, rename the default Form1.cs to DbConnectClient.cs. Open the form in code view and change all occurrences of Form1 to refer to DbConnectClient instead.

  11. Place two GroupBox controls (grpQuery and grpResults), a TextBox control (txtQuery, with its MultiLine property set to true), a Button control (btnExecute), and a DataGrid control (dgResults) on the form. Refer to Figure for the design of this form.

  12. Add the following using directives:

    
    using System.Runtime.Remoting;
    
    using StepByStep3_9;
    
    
  13. Add the following code in the class definition:

    
    // Declare a Remote object
    
    IDbConnect dbc;
    
    
  14. Double-click the form and add the following code in the Load event handler:

    
    private void DbConnectClient_Load(
    
        object sender, System.EventArgs e)
    
    {
    
        // Load remoting configuration
    
        RemotingConfiguration.Configure
    
            ("Exercise3_1_Client.exe.config");
    
    
    
        // Instantiate the remote class
    
        dbc = (IDbConnect)
    
        Activator.GetObject(typeof(IDbConnect),
    
        @"http://localhost/Exercise3_1_Server/DbConnect.rem");
    
    }
    
    
  15. Double-click the Button control and add the following code in the Click event handler:

    
    private void btnExecute_Click(
    
        object sender, System.EventArgs e)
    
    {
    
        try
    
        {
    
           // Invoke a method on
    
           // the remote object
    
            this.dgResults.DataSource =
    
                dbc.ExecuteQuery(
    
                   this.txtQuery.Text);
    
            dgResults.DataMember = "Results";
    
        }
    
        catch(Exception ex)
    
        {
    
            MessageBox.Show(ex.Message,
    
               "Query Execution Error");
    
        }
    
    }
    
    
  16. Build the project. Set Exercise3_1_Client, the remoting client, as the startup project. Select Debug, Start Without Debugging to run the project. Enter a query in the text box and click the button. The code invokes a method on the remote object. The remote object is serialized and deserialized in binary format and is transported over the HTTP. The code binds the results from the remote method to the DataGrid control.

Note that you can specify the desired formatter for the client and need not specify the formatter for the server. The formatter requested by the client will be used to format data by the server for that client.

Dynamically Publishing a Well-Known Object

Well-known objects cannot be invoked from a client with a non-default constructor. However, you can create an object using any constructor you wish, initialize it any way you wish, and then make it available to clients.

You should use the RemotingServices.Marshal() method to publish an existing object instance.

Estimated Time: 30 minutes.

  1. Add a new Visual C# console application named Exercise3_2_Server to the solution.

  2. Add references to the .NET assembly System.Runtime.Remoting, the StepByStep3_9.dll (the interface assembly containing IDbConnect), and StepByStep3_10.dll (the remotable object, DbConnect).

  3. In the Solution Explorer, rename the default Class1.cs to DbConnectServer.cs. Open the file and change the name of the class to DbConnectServer in the class declaration.

  4. Add the following using directives:

    
    using System.Runtime.Remoting;
    
    using System.Runtime.Remoting.Channels;
    
    using System.Runtime.Remoting.Channels.Tcp;
    
    using StepByStep3_10;
    
    
  5. Add the following code in the Main() method:

    
    [STAThread]
    
    static void Main(string[] args)
    
    {
    
        // Create and register a TCP server
    
        // channel that listens on port 1234
    
        TcpServerChannel channel =
    
            new TcpServerChannel(1234);
    
        ChannelServices.RegisterChannel(
    
            channel);
    
    
    
        // Create the remotable object here
    
        // itself. Call the
    
        // RemotingServices.Marshal() method
    
        // to marshal (serialize) the created
    
        // remotable object to transfer the
    
        // object beyond application boundaries
    
        // with the specified uri
    
        DbConnect dbcPubs =
    
            new DbConnect("Pubs");
    
        RemotingServices.Marshal(
    
            dbcPubs, "Pubs.uri");
    
    
    
        DbConnect dbcNorthwind =
    
           new DbConnect("Northwind");
    
        RemotingServices.Marshal(
    
           dbcNorthwind, "Northwind.uri");
    
    
    
        Console.WriteLine(
    
            "Started server in the " +
    
            "Singleton mode");
    
        Console.WriteLine(
    
            "Press <ENTER> to terminate " +
    
            "server...");
    
        Console.ReadLine();
    
    }
    
    
  6. Build the project. This step creates a remoting server that creates the remotable object StepByStep3_1.DbConnect and is capable of marshaling the remote object across application boundaries.

  7. Add a new Visual C# .NET Windows application named Exercise3_2_Client to the solution.

  8. Add references to the .NET assembly System.Runtime.Remoting and the project StepByStep3_9 (the interface assembly).

  9. In the Solution Explorer, rename the default Form1.cs to DbConnectClient.cs. Open the form in code view and change all occurrences of Form1 to refer to DbConnectClient instead.

  10. Add the following using directives:

    
    using System.Runtime.Remoting;
    
    using System.Runtime.Remoting.Channels;
    
    using System.Runtime.Remoting.Channels.Tcp;
    
    using StepByStep3_9;
    
    
  11. Place three GroupBox controls (grpDatabases, grpQuery, and grpResults), a ComboBox control (cboDatabases), a TextBox control (txtQuery), a Button control (btnExecute), and a DataGrid control (dgResults) on the form. Set the DropDownStyle to DropDownList.

  12. Select the Items property of the cboDatabases control in the Properties window and click on the (…) button. This opens the String Collection Editor dialog box. Enter the following database names in the editor:

    
    Northwind
    
    Pubs
    
    
  13. Click OK to add the databases to the Items collection of the cboDatabases control.

  14. Add the following code in the class definition:

    
    // Declare a remote object
    
    IDbConnect dbc;
    
    
  15. Double-click the form and add the following code in the Load event handler:

    
    private void DbConnectClient_Load(
    
        object sender, System.EventArgs e)
    
    {
    
        // Register a TCP client channel
    
        TcpClientChannel channel =
    
            new TcpClientChannel();
    
        ChannelServices.RegisterChannel(
    
            channel);
    
    
    
        cboDatabases.SelectedIndex = 0;
    
    }
    
    
  16. Double-click the cboDatabases control and add the following code in the SelectedIndexChanged event handler:

    
    private void
    
       cboDatabases_SelectedIndexChanged(
    
        object sender, System.EventArgs e)
    
    {
    
        switch (
    
          cboDatabases.SelectedItem.ToString())
    
        {
    
            case "Pubs":
    
            {
    
                // Instantiate the remote class
    
                dbc = (IDbConnect)
    
                    Activator.GetObject(
    
                    typeof(IDbConnect),
    
                    @"tcp://localhost:1234/Pubs.uri");
    
                break;
    
            }
    
            case "Northwind":
    
            {
    
                // Instantiate the remote class
    
                dbc = (IDbConnect)
    
                    Activator.GetObject(
    
                    typeof(IDbConnect),
    
                    @"tcp://localhost:1234/Northwind.uri");
    
                break;
    
            }
    
        }
    
    }
    
    
  17. Double-click the btnExecute control and add the following code in the Click event handler:

    
    private void btnExecute_Click
    
        (object sender, System.EventArgs e)
    
    {
    
        try
    
        {
    
            // Invoke a method on
    
            // the remote object
    
            this.dgResults.DataSource =
    
                dbc.ExecuteQuery(
    
                this.txtQuery.Text);
    
            dgResults.DataMember = "Results";
    
        }
    
        catch(Exception ex)
    
        {
    
            MessageBox.Show(ex.Message,
    
                "Query Execution Error");
    
        }
    
    }
    
    
  18. Build the project. You now have a remoting client ready to use.

  19. Set the Exercise3_2_Server, the remoting server, as the startup project. Select Debug, Start Without Debugging to run the project. You should see a command window displaying a message that the server is started in the singleton activation mode. You should also see messages that the remote object is already created.

  20. Set Exercise3_2_Client, the remoting client, as the startup project. Select Debug, Start Without Debugging to run the project. Select a desired database from the combo box, enter a query in the text box, and click the button. The code invokes a method on the remote object that is already created on the server. The code binds the results from the remote method to the DataGrid control.

  21. Again select Debug, Start Without Debugging to run one more instance of the remoting client. Select a different database from the combo box, enter a query in the text box, and click the button. You should see that the second instance of the client fetches the data from the selected database.

Review Questions

1:

What is an application domain? How does the CLR manage an application domain?

A1:

The application domain, represented by the AppDomain class, is the basic unit of isolation for running applications in the CLR. The CLR allows several application domains to run within a single Windows process. The CLR ensures that code running in one application domain cannot affect other application domains. The CLR can terminate an application domain without stopping the entire process.

2:

What are MBR objects? What are their advantages and disadvantages?

A2:

MBR objects are remotable objects that derive from the System.MarshalByRefObject class. The MBR objects always reside on the server; the client application domain holds only a reference to the MBR objects and uses a proxy object to interact with the MBR objects. They are best suited when the remotable objects are large or when the functionality of the remotable objects is available only in the server environment on which it is created. However, they increase the number of network roundtrips between the server application domain and the client application domain.

3:

What do you mean by a channel? What are the different types of channels the .NET Framework provides?

A3:

A channel is an object that transports messages across remoting boundaries such as application domains, processes, and computers. The .NET Framework provides implementations for HTTP and TCP channels.

4:

What are the advantages and disadvantanges of the binary and SOAP formatters?

A4:

The binary formatter represents messages in a compact and efficient way, whereas the SOAP formatters are very verbose. The SOAP formatters can be used to communicate in heterogeneous environments, whereas the binary formatters can be understood only by .NET applications.

5:

What are the two modes for creating Server-Activated objects?

A5:

The two modes for creating SAOs are SingleCall and Singleton. SingleCall activation mode creates a remote object for each client request. The object is discarded as soon as the request completes. Singleton activation mode creates a remote object only once and all the clients share the same copy. Hence SingleCall SAOs are stateless and Singleton SAOs maintain state global to all clients.

6:

When should you choose to create a client-activated object?

A6:

CAOs are created for each client whenever the client requests. Hence CAOs are best suited when clients want to maintain private sessions with remote objects, when the clients want to control the lifetimes of the objects, or when they want to create customized remote objects with non-default properties.

7:

What is the benefit of using declarative configuration over programmatic configuration?

A7:

The main benefit of using declarative configuration over programmatic configuration is that you need not recompile the application after changing the remoting settings in the configuration file. The changes are picked up automatically.

8:

What are the two methods of the Activator class that enable you to create instances of remote objects?

A8:

The GetObject() method (for server-activated objects) and CreateInstance() method (for client-activated objects) are the two methods of the Activator class that enable you to create instances of remote objects.

9:

What are the advantages of using an IIS server as an activation agent?

A9:

Using IIS as an activation agent offers the following advantages:

  • You need not write a separate server program to register the remotable classes.

  • You need not worry about finding an available port for your server application. You can just host the remotable object and IIS automatically uses port 80.

  • IIS can provide other functionality, such as authentication and Secure Sockets Layer (SSL).

10:

What should you do while creating a remotable class so that its methods can be called asynchronously?

A10:

A remotable object by default is capable of being called asynchronously; therefore no extra efforts are required to create remote objects that can be called asynchronously.

Exam Questions

1:

You are designing a distributed application that hosts a remote object. You want only the authorized client applications to activate the remote object. You want to write the application with the minimum amount of code. Which of the following channels enables you to achieve this objective? (Select two.)

  1. HttpChannel

  2. HttpServerChannel

  3. TcpChannel

  4. TcpServerChannel

A1:

A, B. Your objective is to provide access to only authorized clients. Authorization is a function of the remoting host. IIS is the only available remoting host that provides you with this capability. IIS supports only HTTP communication. Therefore, you can use either the HttpChannel or HttpServerChannel channel because both allow you to listen to incoming messages from clients. IIS does not support TcpChannel and TcpServerChannel, so if you use these channels you have to write additional code to implement security and this is not desired in the given scenario. For more information, see the section "Choosing Between the HTTP and the TCP Channels" in this chapter.

2:

You are designing a company-wide order processing system. This application is hosted on a server in the company's headquarters in Redmond, Washington, and is accessed by 1500 franchise locations throughout the world. The application specification mentions that the franchisees should be able to access the order-processing system even through firewalls. A large number of franchisees access the application over a slow connection and your objective is to maximize the performance of the application. Which of the following combinations of channel and formatter would you choose in this scenario?

  1. Use a TCP channel with a binary formatter.

  2. Use a TCP channel with a SOAP formatter.

  3. Use an HTTP channel with a binary formatter.

  4. Use an HTTP channel with a SOAP formatter.

A2:

C. Firewalls generally allow HTTP messages to pass through, and the binary formatter provides a size-optimized format for encoding data. Using TCP may require administrators to open additional ports in the firewall, and the SOAP format is verbose when compared to binary and would take additional bandwidth, which is not a desirable solution for clients using slow connections. For more information, see the section "Choosing Between the HTTP and the TCP Channels" and "Channels and Formatters" in this chapter.

3:

You are designing a distributed application for a large automotive company. The application allows the part suppliers across the globe to collect the latest design specifications for a part. The application is heavily accessed by the suppliers. For greater scalability, you are required to design the application so that it can be deployed in a load-balanced environment. How should you host the remotable object in this scenario?

  1. As a server-activated object in SingleCall activation mode.

  2. As a server-activated object in Singleton activation mode.

  3. As a client-activated object using the HTTP channel.

  4. As a client-activated object using the SOAP formatter.

A3:

A. Only server-activated objects in SingleCall activation mode support load-balancing because they do not maintain state across the method calls. For more information, see the section "Server-Activated Objects" in this chapter.

4:

You have been hired by Great Widgets Inc., to create an application that enables their suppliers to access the purchase order information in real time. You create the required classes that the suppliers can activate remotely and package them into a file named gwpoinfo.dll. You plan to use IIS as the remoting host for this file. After the application has been deployed, minimal steps should be involved in changing the remoting configuration for this application. Any configuration changes made to the purchase order information system should not affect any other applications running on that server. Which of the following files would you choose to configure remoting for the purchase order information system?

  1. gwpoinfo.dll

  2. web.config

  3. global.asax

  4. machine.config

A4:

B. You should store the remoting configuration in the web.config file. This file is an XML-based configuration file that is easy to modify and does not require a separate compilation step. Storing configuration settings in gwpoinfo.dll or global.asax requires the additional step of compilation before the settings come into effect. The machine.config file is not suggested because any changes made to it affect all the applications running on the server. For more information, see the section "Using Configuration Files to Configure the Remoting Framework" in this chapter.

5:

You have designed a remotable class named ProductDesign. You now want to register this class with the remoting system in such a way that client programs should be able to remotely instantiate objects of this class and invoke methods on it. You want to have only one instance of this class on the server, no matter how many clients connect to it. Which of the following code segments fulfills your requirement?

  1. 
    RemotingConfiguration.
    
        RegisterWellKnownServiceType(
    
        typeof(ProductDesign),
    
        "ProductDesign",
    
        WellKnownObjectMode.SingleCall
    
    );
    
    
  2. 
    RemotingConfiguration.
    
        RegisterWellKnownServiceType(
    
        typeof(ProductDesign),
    
        "ProductDesign",
    
        WellKnownObjectMode.Singleton
    
    );
    
    
  3. 
    RemotingConfiguration.
    
        RegisterActivatedServiceType(
    
        typeof(ProductDesign),
    
        "ProductDesign"
    
    );
    
    
  4. 
    RemotingConfiguration.
    
        RegisterWellKnownClientType(
    
        typeof(ProductDesign),
    
        "ProductDesign"
    
    );
    
    
A5:

B. When you want to create just one instance of a remote object, without regard to the number of clients, you must create a server-activated object in the Singleton activation mode. For more information, see the section "Server-Activated Objects" in this chapter.

6:

You have designed a remotable class that allows the user to retrieve the latest weather information for their region. You do not want to write a lot of code to create a custom remoting host, so you decide to use IIS to host the application. The name of the remotable class is RemotingWeather.WeatherInfo and it is stored in an assembly named WeatherInfo.dll. You want the users to access this remotable class by using the URL http://RemoteWeather.com/users/WeatherInfo.rem. Which of the following remoting configurations would you place in the web.config file so that client applications can correctly retrieve weather information?

  1. 
    <system.runtime.remoting>
    
       <application>
    
           <service>
    
               <activated type=
    
                 "RemotingWeather.WeatherInfo, WeatherInfo"
    
                />
    
          </service>
    
          <channels>
    
               <channel ref="http" port="80" />
    
          </channels>
    
       </application>
    
    </system.runtime.remoting>
    
    
  2. 
    <system.runtime.remoting>
    
       <application>
    
           <service>
    
               <wellknown mode="Singleton"
    
                  type=
    
                  "RemotingWeather.WeatherInfo, WeatherInfo"
    
                 objectUri="WeatherInfo.rem"
    
               />
    
          </service>
    
       </application>
    
    </system.runtime.remoting>
    
    
  3. 
    <system.runtime.remoting>
    
       <application>
    
           <service>
    
               <activated type=
    
                 "RemotingWeather.WeatherInfo, WeatherInfo"
    
                />
    
          </service>
    
          <channels>
    
               <channel ref="http server"
    
                    port="80" />
    
          </channels>
    
       </application>
    
    </system.runtime.remoting>
    
    
  4. 
    <system.runtime.remoting>
    
       <application>
    
           <client>
    
               <wellknown mode="Singleton"
    
                 type=
    
                 "RemotingWeather.WeatherInfo, WeatherInfo"
    
                 objectUri="WeatherInfo.rem"
    
               />
    
          </client>
    
       </application>
    
    </system.runtime.remoting>
    
    
A6:

B. IIS supports only well-known or server-activated objects. Therefore, you must use the <wellknown> element rather than the <activated> element. Also, you are specifying the configuration for the server, so you must use the <server> element rather than the <client> element inside the <application> element to configure the WellKnown object. For more information, see the section "Using Configuration Files to Configure the Remoting Framework" and "Using IIS As an Activation Agent" in this chapter.

7:

You are a software developer for LubriSol, Inc., which manufactures chemicals for automobile industries. Your company does a lot of business with ReverseGear, Inc., which is the largest manufacturer of heavy vehicles in the country. ReverseGear, Inc., uses a .NET remoting application that allows its suppliers to check its daily parts requirements. Your objective is to create a client application to the ReverseGear's application that retrieves the information for parts produced by your company. All you know about the server application is its URL, which is http://ReverseGearInc.com/Suppliers/Req.rem. You want the quickest solution. What should you do to write a client application successfully?

  1. Contact ReverseGear, Inc., to ask for the interface and include reference to the interface in the client project.

  2. Open the URL in the Web browser and select View, Source to find how the remote class is structured.

  3. Use the Visual Studio .NET Add Web Reference feature to add a reference to the remote class in the client project.

  4. Use the Soapsuds tool to automatically generate the metadata and include the reference to this metadata in the client project.

A7:

D. Because you know that the server's .NET remoting application is using HTTP, you can use the Soapsuds tool to automatically generate the metadata for the server. For more information, see the section "Using the Soapsuds Tool to Automatically Generate an Interface Assembly" in this chapter.

8:

You want to host a remotable class via the .NET remoting framework so that remote clients can instantiate the class and invoke methods on it. The remotable class does not have any user interface but it must use Integrated Windows authentication to authenticate the users. Which of the following techniques you should use to host the remotable class? You want a solution that requires you to write minimal code.

  1. Use a console application as a remoting host.

  2. Create a Windows service and use that to host the remotable class.

  3. Use a Windows forms application to host the remotable class.

  4. Use Internet Information Services (IIS) as a remoting host.

A8:

D. You should use IIS as the remoting host because IIS has built-in support for Integrated Windows authentication. You'll have to write additional code to achieve this with other techniques. For more information, see the section "Using IIS As an Activation Agent" in this chapter.

9:

You are developing a remoting client to access a server-activated remotable object hosted at the URL tcp://finance:1234/Budget. You have obtained an interface assembly of this remote object. This assembly contains an interface named IBudget that is implemented by the remote class. You want to instantiate the remote object to invoke a method name GetDepartmentBudget(), which accepts a string value and returns a double value containing the department budget. Given the following code, what should you write in line 06 to successfully invoke the GetDepartmentBudget() method?


01: // Register a TCP client channel

02: TcpClientChannel channel =

      new TcpClientChannel();

03: ChannelServices.RegisterChannel(

      channel);

04: IBudget budget;

05: // Instantiate the remote class

06:

07: // Invoke the remote method

08: double budgetValue =

     budget.GetDepartmentBudget("HR");

  1. 
    budget = (IBudget)
    
           Activator.GetObject(typeof(IBudget),
    
           @"tcp://finance:1234/Budget");
    
    
  2. 
    budget = (IBudget)
    
            Activator.CreateInstance(
    
              typeof(IBudget),
    
              @"tcp://finance:1234/Budget");
    
    
  3. 
    budget = new IBudget();
    
    
  4. 
    RemotingConfiguration.
    
    RegisterWellKnownClientType(
    
           typeof(IBudget),
    
           @"tcp://finance:1234/Budget");
    
    Budget = new IBudget();
    
    
A9:

A. When you have an interface to a class and not the original class, you cannot use the new operator to instantiate the remote object. You should instead use the static methods of the Activator class. The Activator.GetObject() method is used to instantiate a server-activated object. For more information, see the section "Using Interface Assemblies to Compile Remoting Clients" in this chapter.

10:

You are developing an application that allows the client programs to instantiate a class named Inventory. You want the remote object to be created on the server so that it can access the inventory database. However, you want client programs to control the creation and the lifetime of the remote objects. Which of the following methods of the RemotingConfiguration class would you choose to register the remotable class with the remoting system on the server?

  1. RegisterWellKnownServiceType()

  2. RegisterWellKnownClientType()

  3. RegisterActivatedServiceType()

  4. RegisterActivatedClientType()

A10:

C. Your requirement is to register a client-activated remote object on the server, so you'll use the RegisterActivatedServiceType() method. The RegisterActivatedClientType() method is used to register the CAO with the remoting system in the client's application domain. The other two options are for creating the server-activated objects. For more information, see the section "Creating a Client-Activated Object" in this chapter.

11:

You work for a large chemical manufacturing company that has four production units across the country. Your team has the responsibility of designing a distributed application that allows different production units to share and update material safety information for various products. One of your co-workers is using the following code to create a remoting host to host a server-activated object. She is getting an error. What should she do to resolve this error?


01: using System.Runtime.Remoting;

02: using System.Runtime.Remoting.Channels;

03: using

System.Runtime.Remoting.Channels.Tcp;

04: using

      System.Runtime.Remoting.Channels.Http;

05: [STAThread]

06: static void Main(string[] args)

07: {

08:    TcpServerChannel tcpChannel =

              new TcpServerChannel(7777);

09:    HttpServerChannel httpChannel =

              new HttpServerChannel(8888);

10:    RemotingConfiguration.

         RegisterWellKnownServiceType

         (typeof(MsdsInfo), "MsdsInfo",

         WellKnownObjectMode.Singleton);

11: }

  1. Remove the statement at line 09.

  2. Add the following statements just before line 10:

    
    ChannelServices.RegisterChannel(tcpChannel);
    
    ChannelServices.RegisterChannel(httpChannel);
    
    
  3. In the statement at line 08, replace TcpServerChannel with TcpChannel, and similarly in the statement in line 09, replace HttpServerChannel with HttpChannel.

  4. Use the same port numbers in the statements in line 08 and line 09.

A11:

B. In this program, although you have created an instance of TcpServerChannel and HttpServerChannel objects, you haven't yet registered them with the remoting framework. You'll register the channels by using the RegisterChannel() method of the ChannelServices class. For more information, see the sections "Using the SingleCall Activation Mode to Register a Remotable Class As a Server-Activated Object," "Using the Singleton Activation Mode to Register a Remotable Class As a Server-Activated Object," and "Registering a Remotable Class As a Client-Activated Object" in this chapter.

12:

One of your coworkers has written the following code as part of a client application that activates a remote object. She is complaining that her program is not compiling. What should she modify in the program to remove this error? (Select all that apply.)


01: DbConnect CreateObject()

02: {

03:     TcpClientChannel channel =

            new TcpClientChannel(1234);

04:     ChannelServices.RegisterChannel(

            channel);

05:     RemotingConfiguration.

        RegisterWellKnownClientType(

06:         typeof(DbConnect),

07:         "tcp://localhost/DbConnect"

08:         );

09:     dbc = new DbConnect();

10:     return dbc;

11: }

  1. Change line 05 to use the RegisterWellKnownServiceType() method instead of the RegisterWellKnownClientType() method.

  2. Change the URL in line 07 to "tcp://localhost:1234/DbConnect"

  3. Remove the port number from the constructor of TcpClientChannel() in line 03

  4. Change the code in line 07 to objectUri="DbConnect"

A12:

B, C. When creating a client channel you should not specify a port number when calling the channel constructor. Instead, the port number should be used with the URL of the remote object. After the channels are created they should be registered with the remoting system. For more information, see the section "Channels" in this chapter.

13:

The Soapsuds tool (soapsuds.exe) can be used to automatically generate the interface assembly for the remotable object. Which of the following statements are FALSE related to the Soapsuds tool? (Select two options.)

  1. The Soapsuds tool can be used to generate metadata for server-activated objects.

  2. The Soapsuds tool can be used to generate metadata for client-activated objects.

  3. The Soapsuds tool can be used to generate metadata for remotable objects registered through the HTTP channel.

  4. The Soapsuds tool can be used to generate metadata for remotable objects registered through the TCP channel.

A13:

B, D. The Soapsuds tool is capable of generating metadata for server-activated objects on the HTTP channel. For more information, see the section "Using the Soapsuds Tool to Automatically Generate an Interface Assembly" in this chapter.

14:

You have designed a Windows application that is used by the shipping department of a large distribution house. The Windows application instantiates a remotable class hosted on Internet Information Services (IIS). The remotable class provides various services to the Windows application, such as address validation and calculation of shipping rates. When you deploy the application, users complain that when they click the Validate Address button, the Windows application freezes and they can't take further action till the address has been verified. What should you do to improve the application's responsiveness?

  1. Use the binary formatter instead of the SOAP formatter.

  2. Use the TCP channel to communicate instead of the HTTP channel.

  3. Modify the remotable class to support asynchronous method calls.

  4. Modify the Windows application to call the methods asynchronously on the remote object.

A14:

D. The issue in the question is not of speed but of responsiveness. This behavior occurs because the Windows application is calling the methods on the remote object synchronously. You can make the user interface more responsive by simply calling the remote method asynchronously. No modifications are needed on the remotable object to achieve this behavior. For more information, see the section "Asynchronous Remoting" in this chapter.

15:

When you derive a class from the MarshalByRefObject to make the class remotable, which of the following members of the class are not remoted? (Select all that apply.)

  1. non-static public methods

  2. static methods

  3. non-static private methods

  4. non-static public properties

A15:

B, C. Only non-static public methods, properties, and fields participate in remoting. For more information, see the section "Remote Object Activation" in this chapter.

Suggested Readings and Resources

1. Visual Studio .NET Combined Help Collection

• .NET Remoting Overview

• Remoting Examples

2. Ingo Rammer. Advanced .NET Remoting. Apress, 2002.

3. www.iana.org/assignments/port-numbers—List of assigned port numbers.


     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows