Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# and the NET Platform, Second Edition - Andrew Troelsen.pdf
Скачиваний:
67
Добавлен:
24.05.2014
Размер:
22.43 Mб
Скачать

All Together Now!

 

C# and the .NET Platform, Second Edition

 

by Andrew Troelsen

ISBN:1590590554

If your head is spinning from reading the previous sections, fear not! The transparent proxy, real proxy,

Apress © 2003 (1200 pages)

message object, and dispatcher can typically be completely ignored, provided you are happy with the

This comprehensive text starts with a brief overview of the

default plumbingC#(whichlanguageis theandcasethenmostquicklyof themovestime).toAskeyyoutechnicalwill see,andthe process of specifying the channel object (andarchitecrelateduralformatter)issues for is.NETas simpledeve opersas a. single line of code. Furthermore, the .NET runtime is the entity in charge of orchestrating the creation and handshaking that takes place to invoke methods on objects located in distinct application domains. To help solidify the sequence of events, ponder Figure 12-

Table of Contents

7, which illustrates the basic process of two objects communicating across distinct application domains.

C# and the .NET Platform, Second Edition

Introduction

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter 7 - Callback Interfaces, Delegates, and Events

Figure 12-7: A high-level view of the default .NET Remoting architecture

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

A Brief Word Regarding the Extension of the Default Plumbing

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

A key aspect of the .NET Remoting layer (which is markedly different from that of classic DCOM) is the

Part Four - Leveraging the .NET Libraries

fact that most of the default remoting layers can be extended or completely replaced at the whim of the

Chapter 12 - Object Serialization and the .NET Remoting Layer

developer. Thus, if you truly want (or possibly need) to build a custom message dispatcher, custom

Chapterformatter,13 -orBuildingcustomarealBetterproxy,Windyouw are(Introducingfree to doWindowsso. Forms)

Chapter 14 - A Better Painting Framework (GDI+)

You are also able to inject additional levels of indirection by plugging in custom types that stand between a

Chapter 15 - Programming with Windows Forms Controls

given layer (for example, a custom sink used to perform preprocessing or post-processing of a given

Chapter 16 - The System.IO Namespace

message). Now, to be sure, you may never need to retrofit the core .NET Remoting layer in such ways.

Chapter 17 - Data Access with ADO.NET

However the fact remains that the .NET platform does provide the namespaces to allow you to do so.

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Note This chapter does not address the topic of extending the default .NET Remoting layer. If you

Chapter 19 - ASP.NET Web Applications

wish to learn how to do so, check out Advanced .NET Remoting (Rammer, Apress 2002).

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Terms of the .NET Remoting Trade

 

C# and the .NET Pla form, Second Edition

 

by Andrew Troelsen

ISBN:1590590554

Like any new paradigm, .NET Remoting brings a number of TLAs (three-letter-acronyms) into the mix.

Apress © 2003 (1200 pages)

Thus, before you see your first code example, we do need to define a number of terms used when

This comprehensive text starts with a brief overview of the

describing the compositionC# languageof and.NETthenRemotingquickly movesapplicationto key.technicalAs you wouldand guess, this terminology is used to describe a numberarchitecturalof detailsi suesregardingfor .NETcommondevelopersquestions. that arise during the construction of a distributed application: How do we pass a type across application domain boundaries? When exactly is a remote type activated ? How do we manage the lifetime of a remote object? (and so forth). Once you have

Table of Contents

an understanding of the related terminology, the act of building a distributed .NET application will be far

C# and the .NET Platform, Second Edition

less perplexing. Do understand that the acronyms that follow are mapped to specific code examples over

Introductionthe course of the chapter.

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Chapter 18 - ASP.NET Web Pages and Web Controls
Part Five - Web Applications and XML Web Services
Chapter 9 - Understanding .NET Assemblies
Part Three - Programming with .NET Assemblies

Object MarshalingC# nd the Choices.NET Platform,(MBRSecondorEditionMBV?)

by Andrew Troelsen

ISBN:1590590554

Under the .NET platform, you have two options regarding how a remote object is marshaled to the client.

Apress © 2003 (1200 pages)

First question: What the heck is marshaling? Simply put, marshaling is a term that describes how a remote

This comprehensive text starts with a brief overview of the

object is passed betweenC# languapplicationge and thendomainsquickly moves. Whentoyoukeyaret chnicaldesigninganda remotable object, you may choose to employarchitecturalmarshal-byissu-references for .NET(MBR,developersfor short). or marshal-by-value (MBV, for short) semantics. The distinction is as follows:

Table MBRof Contentsobjects: The caller receives a proxy to the remote object

C# and the .NET Platform, Second Edition

MBV objects: The caller receives a full copy of the object in its own application domain

Introduction

Part One - Introducing C# and the .NET Platform

If you configure an MBR object type, the CLR ensures that the transparent and real proxies are created in

Chapter 1 - The Philosophy of .NET

the client's application domain, while the MBR object itself remains in the server's application domain. As

Chapter 2 - Building C# Applications

the client invokes methods on the remote type, the .NET Remoting plumbing (examined previously) takes

Part Two - The C# Programming Language

over the show and will package, pass, and return information between application domain boundaries. To

Chapter 3 - C# Language Fundamentals

be sure, MBR objects have a number of traits above and beyond their physical location. As you will see, ChapterMBR objects4 - Objecthave-variousOrientedconfigurationProgrammingoptionswith C#regarding their activation options and lifetime

Chaptermanagement5 - Exceptions. and Object Lifetime

Chapter 6 - Interfaces and Collections

MBV objects, on the other hand, are local copies of remote objects (which as you can guess make use of

Chapter 7 - Callback Interfaces, Delegates, and Events

the .NET serialization protocol examined at the beginning of this chapter). MBV objects have far fewer

Chapter 8 - Advanced C# Type Construction Techniques

configuration settings, given that their lifetime is directly controlled by the client. Like any .NET object, once a client has released all references to an MBV type, it is a candidate for garbage collection. Given that

MBV types are local copies of remote objects, as a client invokes members on the type no network activity

Chapter 10 - Processes, AppDomains, Contexts, and Threads occurs during the process.

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

PartTo solidifyF ur - Leveragithe distinctiong the .betweenNET LibrariesMBR and MBV objects, think back to Chapter 3 when you examined the Chapterrole of 12the-C#Object"ref"Serializationkeyword. Recalland thethat.NETby default,RemotingparametersL yer are passed into a method by value. Thus,

Chapterif the receiving13 - Buildifunctiong a Bettattemptsr Windowto reassign(Introducingthe valueWindowsof theForms)incoming parameters, the caller is unaware of

Chapterthe modification14 - A Better. OnPaintingthe otherFrameworkhand, if method(GDI+)parameters are modified using the "ref" keyword, a Chapterreference15 -toProgrammingthe value typewithis passedWindowsintoFormsthe method,Controls and thus any modifications are realized after the

call.

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

The same basic behavior applies in the world of .NET Remoting. If a remote object has been configured as an MBV type, the caller receives a full copy of the remote object within the application's domain, again

using the same object serialization technique presented at the start of this chapter.

Chapter 19 - ASP.NET Web Applications

ChaptIf a remoter 20 - objectXML WebhasServicesbeen configured to be an MBR type, the client does not receive a local copy of the

Indextype. Rather, the remote object is bound to the application domain in which it was created, forcing the

Listcallerof Figuresto interact with the remote type via the intervening proxy layer.

List of Tables

Now, understand that it will be quite common for a single server to provide access to numerous MBR and MBV types. As you may also suspect, MBR types tend to support methods that return various MBV types, which gives way to the familiar factory pattern (e.g., an object that creates and returns other related objects). Next question: How do we configure our custom class types as MBR or MBV entities?

Configuring an MBV Object

To configure an object as an MBV type, you have two options, which happen to be the exact same choices you have when configuring a local .NET object for serialization. Recall that the simplest (and typically most common) approach is to mark your type with the [Serializable] attribute:

[Serializable]

public class MyCustomMBVClass

{...}

As you can tell, the gist of MarshalByRefObject is to define members that can be overridden to programmatically control the lifetime of the MBR object (more on lifetime management later in this chapter).
Note Just because you have configured a type as an MBV or MBR entity does not mean it is only useable within a remoting application, just that it may be used in a remoting application. For example, the System.Windows.Forms.Form type is a descendent from MarshalByRefObject, and thus if it is accessed remotely, is realized as an MBR type. If not, it is just another local object in the client's application domain.
InitializeLifetimeServices()
Obtains a lifetime service object to control the lifetime policy for this instance
GetLifetimeServices()
List of Figures
List of Tables
Retrieves the current lifetime service object that controls the lifetime policy for this instance
Index
Chapter 20 - XML Web Services
Chapter 19 - ASP.NET Web Applications
Chapter 18 - ASP.NET Web Pages and Web Controls
CreateObjRef() Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object
Member
Part Five - Web Applications and XML Web Services
System.MarshalByRefObject
Chapter 17 - Data Access with ADO.NET
Meaning in Life
Chapter public5 - Ex eptvirtualons and ObjectObjRefLi etimeCreateObjRef(Type requestedType);
Chapter public6 - Interfacesvirtualand Collectionsbool Equals(object obj);
Chapter public7 - CallbackvirtualInterfaces,intDelGetHashCode();gates, and Events Chapter public8 - AdvancedvirtualC# TypeobjectCons ructionGetLifetimeService();Techn ques
Part Threepublic- ProgrammingType GetType();with .NET Assemblies
public virtual object InitializeLifetimeService();
Chapter 9 - Understanding .NET Assemblies
public virtual string ToString();
Chapter 10 - Processes, AppDomains, Contexts, and Threads
}
Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming
Part Four - Leveraging the .NET Libraries
Chapter 12 - Object Serialization and the .NET Remoting Layer
Beyond the expected functionality provided by System.Object, Table 12-5 describes the role of the
Chapter 13 - Building a Better Window (Introducing Windows Forms) remaining members.
Chapter 14 - A Better Painting Framework (GDI+)
Chapter 15 - Programming with Windows Forms Controls
Table 12-5: Key Members of System.MarshalByRefObject
Chapter 16 - The System.IO Namespace

C# and the .NET Platform, Second Edition

The other, more exotic, approach is to implement the ISerializable interface. Using this technique, you are by Andrew Troelsen ISBN:1590590554

able to customize the serialization process to fit your needs (as illustrated previously in this chapter).

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the

ConfiguringC#anla guageMBRandObjectthen quickly moves to key technical and

architectural issues for .NET developers.

MBR objects are not marked as such using a .NET attribute, but rather derive (directly or indirectly) from the System.MarshalByRefObject base class:

Table of Contents

C# and the .NET Platform, Second Edition

public class MyCustomMBRClass : MarshalByRefObject

Introduction

{...}

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

ChapterSo, what2 exactly- BuildingdoesC#theApplicationsMarshalByRefObject base class bring to the table? Here is the formal definition:

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

public abstract class MarshalByRefObject : object

Chapter 4 - Object-Oriented Programming with C#

{

Note As a corollaryC# ndtothethe.NETpreviousPlatform,note, understandSecond Editionthat if a .NET type is not serializable and does not includeby AndrewMarshalByRefObjectTroels n in its inheritance chain,ISBN:1590590554the type in question can only be activatedApressand ©used2003in(1200thepages)originating application domain (meaning, they are context bound types). This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and architectural issues for .NET developers.

Table of Contents

C# and the .NET Platform, Second Edition

Introduction

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Final NotesC#Regardingand the .NET Platform,MBR/MBVSecondObjectsEdition

by Andrew Troelsen

ISBN:1590590554

The .NET Remoting layer has a number of intrinsic optimizations that help ensure that when a client

Apress © 2003 (1200 pages)

interacts with remotable objects, network traffic is kept to a minimum. To provide some insights to these

This comprehensive text starts with a brief overview of the internal tweaks, ponderC# languagethe followingand thenpoints:quickly moves to key technical and

architectural issues for .NET developers.

Treatment of static members: Static type members are never invoked remotely, but are triggered within the client-side application domain.

Table of Contents

Treatment of object fields and accessor methods: For object-level fields and accessor methods, the

C# and the .NET Platform, Second Edition

system inserts a check at runtime to see whether the object is a proxy. If it is not a proxy, field access

Introduction

is direct. Otherwise, the proxy provides accessors to the caller.

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Treatment of System.Object members: Provided that a remote type has not overridden the virtual

Chapter 2 - Building C# Applications

methods of System.Object, methods always execute in the client's application domain. However, if the

Part Two - The C# Programming Language

remote type overrides Equals() or ToString(), a network round-trip will occur.

Chapter 3 - C# Language Fundamentals

Now that you understand the distinct traits of MBR and MBV types, let's check out some issues that are

Chapter 4 - Object-Oriented Programming with C#

specific to MBR types (MBV types need not apply).

Chapter 5 - Exceptions and Object Lifetime Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Chapter 10 - Processes, AppDomains, Contexts, and Threads
Part Three - Programming with .NET Assemblies

Activation Choices# and the .NETforPlatform,MBR TypesSecond Edition(WKO or CAO?)

by Andrew Troelsen ISBN:1590590554

Another remoting-centric choice you face as a .NET programmer has to do with exactly when an MBR

Apress © 2003 (1200 pages)

object is activated and when it should be a candidate for garbage collection on the server. This might

This comprehensive text starts with a brief overview of the

seem like a strangeC# choicelanguagetoandmake,thenasquicklyyou mightmovesnaturallyo key assumetechnicalthatand MBR objects are created when the client requestsarchitecturalit and die whenissuestheforclient.NET developersis done. While. it is true that the client is the entity in charge of

instructing the remoting layer it wishes to communicate with a remote type, the server application domain may (or may not) create the type at the exact moment the client's code base requests it. The reason for

Table of Contents

this seemingly strange behavior has to do with the optimization. Specifically, every MBR type may be

C# and the .NET Plactivatedtform, Second Edition

configured to be using one of two techniques:

Introduction

As a Well Known Object (WKO)

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

As a Client Activated Object (CAO)

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Note A potential point of confusion is that fact that the acronym WKO is also called a server-activated

Chapter 3

- C# Language Fundamentals

 

object in the .NET literature. In fact, you may see the SAO acronym in various .NET-centric

Chapter 4

- Object-Oriented Programming with C#

 

articles and books. As you read online Help and find the terms WKO, server-activated object, or

Chapter 5

SAO, understand that these three terms are one and the same. Given that WKO seems to be

- Exceptions

Object Lifetime

Chapter 6

the- Interfacmonikers andof choiceC llectionsat present, I make use of this acronym in this chapter.

Chapter 7 - Callback Interfaces, Delegates, and Events

WKO objects are MBR types whose lifetimes are directly controlled by the server's application domain.

Chapter 8 - Advanced C# Type Construction Techniques

The client-side application activates the remote type using a friendly, well-known string name (hence the

term, WKO). The server's application domain allocates WKO types only when the client makes the first

Chapter 9 - Understanding .NET Assemblies

method call on the object (via the transparent proxy), not when the client's code base makes use of the

"new" keyword or via the static Activator.GetObject() method. To illustrate:

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

// Get a proxy to remote object. This line does NOT create the WKO type!

Chapter 12 - Object Serialization and the .NET Remoting Layer

object remoteObj = Activator.GetObject(/* params seen later... */);

Chapter 13 - Building a Better Window (Introducing Windows Forms)

// Invoke a method on remote WKO type. This WILL create the WKO object

Chapter 14 - A Better Painting Framework (GDI+)

// and invoke the ReturnMessage() method.

Chapter 15 - Programming with Windows Forms Controls

RemoteMessageObject simple = (RemoteMessageObject)remoteObj;

Chapter 16 - The System.IO Namespace

Console.WriteLine("Server says: {0}", simple.ReturnMessage());

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

ChapterThe rationale18 - ASPfor.NETthisWbehavior?Pages Thisand WebapproachControlssaves a network round-trip solely for the purpose of

Chaptercreating19the- ASPobject.NET. AsWebanotherApplicationsinteresting corollary, WKO types can onlybe created via the type's default Chapterconstructor20 -.XMLThisWebshouldServicesmake sense, given that the remote type's constructor is only triggered when the

client makes the initial member invocation. Thus, the runtime has no other option than to invoke the type's

Index

default constructor.

List of Figures

List of Tables

Note Always remember all WKO types must support a default constructor!

If you wish to allow the client to create a remote MBR object using a custom constructor, the server must configure the object as a client-activated object (CAO). CAO objects are entities whose lifetime is controlled by the client's application domain. When accessing a CAO type, a round-trip to the server occurs at the time the client makes use of the "new" keyword (using any of the type's constructors) or via the Activator type.

Stateful Configuration of WKO Types (Singleton or Single Call?)

The final .NET design choice to consider with regard to MBR types has to do with how the server should handle multiple requests to a WKO type. CAO types need not apply, given that there is always a one-to- one correspondence between a client and a remote CAO type (given that they are stateful).

Your first option is to configure a WKO type to function as a singleton type. As the name implies, the CLR will create a single instance of the remote type that will take requests from any number of clients, and is a

natural choice if you need to maintain stateful information among multiple remote callers. Given the fact

C# and the .NET Platform, Second Edition

that multiple clients could invoke the same method at the same time, the CLR places each client

by Andrew Troelsen ISBN:1590590554

invocation on a new thread. It is your responsibility, however, to ensure that your objects are thread-safe

Apress © 2003 (1200 pages)

using the same techniques seen in Chapter 10.

This comprehensive text starts with a brief overview of the

In contrast, a singleC#calllanguageobjectandis athenWKOquicklytype thatmovexistss to keyonlytechnicalduring theandcontext of a single method

architectural issues for .NET developers.

invocation. Thus, if there are 20 clients making use of a WKO type configured with single call semantics, the server will create 20 distinct objects (one for each client), all of which are candidates for garbage

collection directly after the method invocation. As you can guess, single call objects are far more scalable

Table of Contents

than singleton types, given that they are invariably stateless entities.

C# and the .NET Platform, Second Edition

IntroductionThe server is the entity in charge of determining the stateful configuration of a given WKO type.

PartProgrammatically,One - IntroducingtheseC# andoptionsthe .areNETexpressedPlatform via the System.Runtime.Remoting.WellKnownObjectMode

Chapterenumeration:1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

public enum WellKnownObjectMode

Chapter 3 - C# Language Fundamentals

{

ChapterSingleCall,4 - Object-Oriented Programming with C#

ChapterSingleton5 - Exceptions and Object Lifetime

Chapter} 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

ChapterSummarizing9 - Understandingthe.NETTraitsAs embliesof MBR Object Types

Chapter 10 - Processes, AppDomains, Contexts, and Threads

ChapterAs you11have- Typeseen,Reflthecticonfiguration, Late Binding,optionsandofAttributean MBV-BasedobjectProgrammingare no-brainer: apply the [Serializable] Pattributert Four -toLeveragingallow copiestheof.NETtheLibrariestype to be returned to the client's application domain. At this point, all

interaction with the MBV type takes place in the client's locale. When the client is finished using the MBV

Chapter 12 - Object Serialization and the .NET Remoting Layer

type, it is a candidate for garbage collection, and all is well with the world.

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

MBR types, however, have a number of possible configuration choices. As you have seen, a given MBR

Chapter 15 - Programming with Windows Forms Controls

type can be configured with regard to its time of activation, statefullness, and lifetime management. To

Chapter 16 - The System.IO Namespace

summarize the array of possibilities, Table 12-6 documents how WKO and CAO types stack up against

Chapter 17 - Data Access with ADO.NET the traits you have just examined.

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Table 12-6: Configuration Options for MBR Types

 

 

Chapter

19 - ASP.NET

 

Web Applications

 

 

ChapterMBR

20Object- XML WebWKOServicesBehavior (aka Server-

IndexTrait

 

Activated Object)

 

 

 

 

 

List of Figures

 

WKO types can only be activated using

 

 

Instantiation

 

List of Tables

 

the default constructor of the type, which

 

 

options

 

 

 

 

 

 

is triggered when the client makes the

 

 

 

 

 

first method invocation.

 

 

 

 

 

 

CAO Behavior

CAO types can be activated using any constructor of the type. The remote object is created at the point the caller makes use of constructor semantics (or via the Activator type).

State

 

WKO types can be configured as

management

 

singleton or single call entities. Singleton

 

 

types can service multiple clients, and

 

 

are therefore stateful. Single call types

 

 

are alive only during a specific client-side

 

 

invocation, and are therefore stateless.

The lifetime of a CAO type is dictated by the caller, and therefore, CAO types are stateful entities.

 

 

 

 

 

 

 

 

 

Lifetime

C#Singletonand the .NETWKOPlatform,types makeSeconduse ofEditiona

 

CAO types make use of a lease-

 

 

management

 

 

lease-based management scheme

 

based management scheme

 

 

 

by Andrew Troelsen

 

ISBN:1590590554

 

 

 

 

 

(described later in this chapter). Single

 

(described later in this chapter).

 

 

 

Apress © 2003 (1200 pages)

 

 

 

 

 

 

 

call WKO types are a candidate for

 

 

 

 

 

This comprehensive text starts with a brief overview of the

 

 

 

C#garbagelanguagecollectionand then quicklyafter themovescurrentto key technical and

 

 

 

architecturalmethod invocationissues for. .NET developers.

 

 

 

 

 

 

 

 

 

 

 

Table of Contents

C# and the .NET Platform, Second Edition

Introduction

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Chapter 10 - Processes, AppDomains, Contexts, and Threads
Chapter 9 - Understanding .NET Assemblies
Chapter 2 - Building C# Applications

Basic DeploymentC# and the .ofNETaPlatform,.NET RemotingS cond EditionProject

by Andrew Troelsen

ISBN:1590590554

Enough acronyms! At this point you are almost ready to build your first .NET Remoting application. Before

Apress © 2003 (1200 pages)

you do, however, I need to discuss one final detail—deployment. When you are building a .NET Remoting

This comprehensive text starts with a brief overview of the

application, you areC# almostlanguagecertainand thento endquicklyup withmovesthreeto distinctkey technical.NET andassemblies that will constitute the entirety of your remotearchitecturalapplicationissues(yes,for .NETthree,developersnot two). The first two assemblies I am sure you can already account for:

Table Theof Contentsclient: This assembly is the entity that is interested in obtaining access to a remote object. Like C# andanythe.NET.NETapplication,Platform, Secondthe clientEditionmay be a Windows Forms application, a console application or an

ASP.NET Web application.

Introduction

Part One - Introducing C# and the .NET Platform

The server: This assembly is the entity that receives channel requests from the remote client and

Chapter 1 - The Philosophy of .NET

hosts the remote objects. Be aware that the server application is often termed the listener application.

The server may be a custom console application, a custom Windows Service (as you will see), or MS

Part Two - The C# Programming Language

IIS.

Chapter 3 - C# Language Fundamentals

ChapterSo then,4 where- Objectdoes-Orientedthe thirdProgrammingassembly fitwin?th C#Well, in reality, the server application is typically a host to a

Chapterthird assembly5 - Exceptionsthat definesand Objectand implementsLif time the remote objects. For convenience, I'll call this assembly the

Chapt'general6 assembly'- Interfaces. ThisanddecouplingCollectionsof the assembly containing the remote objects and server host is quite Chaimportant,ter 7 -inCallbackthat bothIntheerfaces,clientDelegatand thes,serverand Eventsassemblies typically set a reference to the general

assembly in order to obtain the metadata definitions of the remotable types.

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

In the simplest case, the general assembly is placed into the application directory of the client and server. The only possible drawback to this approach is the fact that the client has a reference to an assembly that

contains CIL code that is never used (which may be a problem if you wish to ensure that the remote clients

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

cannot examine your custom proprietary code). Specifically, the only reason the client requires a reference

Part Four - Leveraging the .NET Libraries

to the general assembly is to obtain the metadata descriptions of the remotable types. There are several

Chapter 12 - Object Serialization and the .NET Remoting Layer ways to overcome this glitch, for example:

Chapter 13 - Building a Better Window (Introducing Windows Forms)

ChapterConstruct14 - A Betteryour remotePaintingobjectsFramewtorkmake(GDI+)use of interface-based programming techniques. In this way, Chapteryou15can- Programmingbuild an additionalwith WindowsassemblyFormsthatControlscontains nothing but interface definitions for the remote

types. Given this, the client is able to set a reference to a .NET binary that contains nothing but

Chapter 16 - The System.IO Namespace

interface definitions.

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Make use of the soapsuds.exe command line application. Using this tool, you are able to generate an

Chapter 18 - ASP.NET Web Pages and Web Controls

assembly that contains nothing but metadata descriptions of the remote types. You'll check out the

Chapter 19 - ASP.NET Web Applications

use of soapsuds.exe later in this chapter.

Chapter 20 - XML Web Services

IndexManually build an assembly that contains nothing but metadata descriptions of the remote types (from

List ofscratchFiguresor by altering the assembly generated via soapsuds.exe).

List of Tables

To keep things simple over the course of this chapter, you will build and deploy general assemblies that contain the required metadata as well as the CIL implementation.

Note If you wish to examine how to implement general assemblies using each of these alternatives, check out Distributed .NET Programming in C# (Barnaby, Apress 2002).

Building OurC# Firstand theDistributed.NET Platform, SecondApplicationEdition

by Andrew Troelsen

ISBN:1590590554

There is nothing more satisfying than building a distributed application using a new platform. To illustrate how

Apress © 2003 (1200 pages)

quickly you are able to get up and running with the .NET Remoting layer, let's build a simple example. As

This comprehensive text starts with a brief overview of the mentioned, the entiretyC# languageof thisandexamplethen quicklyconsistsmofvesthreeto key.NETtechnicalassemblies:and

architectural issues for .NET developers.

A general assembly named SimpleRemotingAsm.dll

A client assembly named SimpleRemoteObjectClient.exe

Table of Contents

C# and the .NET Platform, Second Edition

A server assembly named SimpleRemoteObjectServer.exe

Introduction

PartTheOnefirst-iterationIntroducingof thisC#exampleand the .makesNET Platformuse of various remoting-centric types (RemotingConfiguration and

ChapterChannelServices)1 - The Philosophythat are examinedof .NET in further detail in just a bit.

Chapter 2 - Building C# Applications

Part Two - The C# Programming LanguageAssembly

Building the General

Chapter 3 - C# Language Fundamentals

ChapFirst,erlet's4 -createObj ctthe-Orientgenerald Prograassemblyming(SimpleRemotingAsmwith C# .dll), which will be referenced by both the server

Chapterand client5 -binariesExceptions. SimpleRemotingAsmand Object Lifetime.dll defines a single MBR type named RemoteMessageObject, which

Chasupportster 6 two- Interfapublicesmembers:and CollectionsDisplayMessage() prints a client supplied message to the server's console Chapterwindow,7 while- CallbackReturnMessage()Int rfaces, Delegates,returns a andtextualEventsmessage to the client. Here is the complete code of this new

class library:

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chnamespacept r 9 - UnderstandingSimpleRemotingAsm.NET Assemblies

Chapter{ 10 - Processes, AppDomains, Contexts, and Threads

Chapter //11 -ThisType Reflection,is a typeLatethatBinding,willand Attributebe -Based Programming

Part Four//- Levemarshaledaging the by.NETreferenceLibra i s (MBR) if accessed remotely.

public class RemoteMessageObject: MarshalByRefObject

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter {13 - Building a Better Window (Introducing Windows Forms)

 

Chapter 14 - A //BetterThePaintingctorFrameworkprints (GDI+)a message just to

 

Chapter 15 - Programming// confirmwithitWindowshas beenForms activated.Controls

 

Chapter 16 - ThepublicSystem.IORemoteMessageObject()Namespace

ctor called!");}

Chapter 17 - Data{ Console.WriteLine("RemoteMessageObjectAccess with ADO.NET

Part Five - Web// This method takes an input string

 

 

Applications and XML Web Services

 

Chapter 18 - ASP.NET// fromWebthePagescaller.and Web Controls

 

 

public void DisplayMessage(string msg)

 

Chapter 19 - ASP.NET Web Applications

 

 

{ Console.WriteLine("Message is: {0}", msg);}

Chapter 20 - XML Web Services

 

Index

// This method returns a value to the caller.

public string ReturnMessage()

 

List of Figures

 

{ return "Hello from the server!"; }

 

List of Tables

 

}

 

 

}

The major point of interest is the fact that the type derives from the System.MarshalByRefObject base class, which ensures that the derived class will be accessible via a client-side proxy (e.g., an MBR object type). Also note I have added a Console.WriteLine() call in the type's constructor, to see exactly when the type is created. That's it. Go ahead and build your new SimpleRemotingAsm.dll assembly.

Building the Server Assembly

Recall that server assemblies are essentially hosts for general assemblies that contain the remotable objects. Thus, create a console-based *.exe assembly named SimpleRemoteObjectServer. The role of this binary is to open a channel for the incoming requests and register RemoteMessageObject as a WKO type. Set a reference to the System.Runtime.Remoting.dll and SimpleRemotingAsm.dll assemblies, and update Main() as follows:

Chapter 20 - XML Web Services

using System;

C# and the .NET Platform, Second Edition

 

using System.Runtime.Remoting;

ISBN:1590590554

by Andrew Troelsen

using System.Runtime.Remoting.Channels;

 

Apress © 2003 (1200 pages)

 

using System.Runtime.Remoting.Channels.Http;

 

This comprehensive text starts with a brief overview of the using SimpleRemotingAsm;

C# language and then quickly moves to key technical and

architectural issues for .NET developers. namespace SimpleRemoteObjectServer

{

class SimpleObjServer

Table of Contents

{

C# and the .NET Platform, Second Edition

static void Main(string[] args)

Introduction

{

Part One - Introducing C# and the .NET Platform

Console.WriteLine("***** SimpleRemoteObjectServer started! *****"

Chapter 1 - The Philosophy of .NET

Console.WriteLine("Hit enter to end.");

Chapter 2 - Building C# Applications

// Register a new HttpChannel

Part Two - The C# Programming Language

HttpChannel c = new HttpChannel(32469);

Chapter 3 - C# Language Fundamentals

ChannelServices.RegisterChannel(c);

Chapter 4 - Object-Oriented Programming with C#

// Register a WKO type, using singleton activation.

Chapter 5 - Exceptions and Object Lifetime

RemotingConfiguration.RegisterWellKnownServiceType(

Chapter 6 - Interfaces and Collectitypeof(SimpleRemotingAsmns .RemoteMessageObject),

Chapter 7 - Callback Interfaces,"RemoteMsgObjDelegates, and.Eventssoap",

Chapter 8 - Advanced C# TypeWellKnownObjConstruction TectModehniques.Singleton);

Part Three - ProgrammingConsolewith .NET.ReadLine();Assemblies

Chapter 9 - Understanding} .NET Assemblies

}

Chapter 10 - Processes, AppDomains, Contexts, and Threads

}

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Main() begins by creating a new HttpChannel type using an arbitrary port ID. This port is opened on registering

Chapter 13 - Building a Better Window (Introducing Windows Forms)

the channel via the static ChannelServices.RegisterChannel() method. Once the channel has been registered,

Chapter 14 - A Better Painting Framework (GDI+)

the remote server assembly is now equipped to process incoming messages via port number 32469.

Chapter 15 - Programming with Windows Forms Controls

ChapterNote16 The- ThenumberSyst myou.IO Namespaceassign to a port is typically up to you (or your system administrator). Do be aware,

Chapter 17 however,- Data Accessthat portwith IDsADObelow.NET 1024 are reserved for use.

Part Five - Web Applications and XML Web Services

Next, to register the SimpleRemotingAsm.RemoteMessageObject type as a WKO requires the use of the

Chapter 18 - ASP.NET Web Pages and Web Controls

RemotingConfiguration.RegisterWellKnownServiceType() method. Here you are informing the CLR that this

Chapter 19 - ASP.NET Web Applications

object is to be realized as a WKO type named RemoteMsgObj.soap. This second parameter to the static

RegisterWellKnownServiceType() is a simple string (of your choosing) that will be used to identify the object

Index

across application domain boundaries (hence the notion of a well-known object).

List of Figures

ListTheoffinalTablesparameter is a member of the WellKnownObjectMode enumeration, which you have specified as WellKnownObjectMode.Singleton. Recall that singleton WKO types ensure that a single instance of the RemoteMessageObject will service all incoming requests. Cool! Build your server assembly and move onto the client-side code.

Building the Client Assembly

Now that you have a listener that is hosting your remotable object, the final step is to build an assembly that will request access to its services. Again, let's use a simple console application. Set a reference to System.Runtime.Remoting.dll and SimpleRemotingAsm.dll. Implement Main() as follows:

using System;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels;

using System.Runtime.Remoting.Channels.Http;

using SimpleRemotingAsm;

C# and the .NET Platform, Second Edition namespace SimpleRemoteObjectClient

{

by Andrew Troelsen

ISBN:1590590554

Apress © 2003 (1200 pages)

 

 

class SimpleObjClient

 

{This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and static void Main(string[] args)

architectural issues for .NET developers.

{

Console.WriteLine("***** SimpleRemoteObjectClient started! *****"

Console.WriteLine("Hit enter to end.");

Table of Contents

// Create a new HttpChannel

C# and the .NET Platform, Second Edition

HttpChannel c = new HttpChannel();

Introduction

ChannelServices.RegisterChannel(c);

Part One - Introducing C# and the .NET Platform

// Get a proxy to remote WKO type.

Chapter 1 - The Philosophy of .NET

object remoteObj = Activator.GetObject(

Chapter 2 - Building C# Applications typeof(SimpleRemotingAsm.RemoteMessageObject),

Part Two - The C# Programming Language

"http://localhost:32469/RemoteMsgObj.soap");

Chapter 3 - C# Language Fundamentals

// Now use the remote object.

Chapter 4 - Object-Oriented Programming with C#

RemoteMessageObject simple = (RemoteMessageObject)remoteObj;

Chapter 5 - Exceptions and Object Lifetime

simple.DisplayMessage("Hello from the client!");

Chapter 6 - Interfaces and Collections

Console.WriteLine("Server says: {0}", simple.ReturnMessage());

Chapter 7 - Callback Interfaces,Console.Delegates,ReadLine();and Events

Chapter 8 - Advanced} C# Type Construction Techniques

Part Three} - Programming with .NET Assemblies

Chapter} 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

A few notes about this client app. First, note that the client is also required to register an HTTP channel, but the

Chapter 12 - Object Serialization and the .NET Remoting Layer

client does not specify a port ID as this is dynamically assigned by the .NET Remoting layer. Given that the clie

Chapter 13 - Building a Better Window (Introducing Windows Forms)

is interacting with a registered WKO type, you are limited to triggering the type's default constructor. To do so,

Chapter 14 - A Better Painting Framework (GDI+)

make use of the Activator.GetObject() method, specifying two parameters. The first is the type information that

Chapter 15 - Programming with Windows Forms Controls

describes the remote object you are interested in interacting with. Read that last sentence again. Given that the

Chapter 16 - The System.IO Namespace

Activator.GetObject() method requires the object's metadata description, it should make more sense why the

Chapter 17 - Data Access with ADO.NET

client is also required to reference the general assembly! Again, at the end of the chapter you examine various

Part Five - Web Applications and XML Web Services

ways to clean up this aspect of your client-side assembly.

Chapter 18 - ASP.NET Web Pages and Web Controls

The second parameter to Activator.GetObject() is termed the activation URL. Unlike classic DCOM which

Chapter 19 - ASP.NET Web Applications

identified remote objects using a numerical GUID, .NET makes use of a friendlier, more readable string name.

Chapter 20 - XML Web Services

Activation URLs that describe a WKO type can be generalized into the following format:

Index

List of Figures

ListProtocolScheme://ComputerName:Port/ObjectUrif Tables

Finally, note that the Activator.GetObject() method returns a generic System.Object type, and thus you must make use of an explicit cast to gain access to the members of the RemoteMessageObject.

Соседние файлы в предмете Программирование