101
Context and Remoting

Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting

Page 2: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

2 Context and Remoting

Objectives

ObjectivesProvide an introduction to the .NET Remoting core infrastructure

Explore the extensibility mechanisms that are available on the transport level and through the Remoting Context.

What You Will Learn Remoting Core Concepts and Rationale The Channel Architecture Channel and Formatter interaction Messages, Message Sinks, Proxies and Dispatchers The Remoting Context Remoting Extensibility and Context Attributes Remote Object Activation Configuring Remoting Services

Related Topics Covered in This Lesson SOAP HTTP

Page 3: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 3

Overview

OverviewSection 1: OverviewSection 2: Remoting ArchitectureSection 3: Context and InterceptionSection 4: Serving and Accessing ObjectsSection 5: Putting it togetherSummary

Page 4: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

4 Context and Remoting

Section 1: Overview

Section 1: OverviewWe will to start our tour through .NET Remoting with a brief look back at Remoting in COM+ and will investigate what the problems are with this model. Then we're going to move onto the .NET Remoting core concepts and the motivation for the design of .NET Remoting is defined today.

Looking back: Remoting in COM(+)What's wrong with that?.NET Remoting Core Concepts

Page 5: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 5

Section 1: Overview

Looking Back: Remoting in COM(+)All Objects implement IUnknown interfaceEvery COM object implements the IUnknown interface. IUnknown provides two basic services common to all objects: it allows for the dynamic exploration of object features and provides lifecycle control through Reference counting.

DCOM: Object-RPC based on DCE Wire FormatCOM's wire format is DCOM, which is an object RPC mechanism based on DCE, the distributed computing environment, which was an initiative to create a large-scale interoperability infrastructure in the early 1990s. DCOM uses the IUnknown interface to exchange interface references and switch between interface types.

Marshaling through MIDL generated Proxies/StubsMarshaling, that is the serialization of data for transfer, is done through proxies and stubs that are code generated by the MIDL compiler, which takes interface definition language (IDL) files as input that describe interfaces, method signatures and the rules how they should be marshaled over the wire. The generated code is emitted in the "C" language and compiled into DLLs.

Alternatively, dynamic interfaces can be exposed through the IDispatch interface, which is designed to be consumed by scripting languages or rapid application development environments.

Servers locally advertised in RegistryCOM servers are locally advertised in the registry and every client that wants to use such servers and has no

Page 6: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

6 Context and Remoting

code that is explicitly aware of dealing with a remote server, which is not necessarily the recommended model for COM, must have a partial mirror copy of these registry entries.

Activation "on-demand". COM’s server activation model is component oriented. Servers are launched at client request and objects are created through class factories.

Page 7: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 7

Section 1: Overview

What’s wrong with that?DCOM protocol is binary and complexThe first problem with this is that COM is a binary protocol and very complex. While this is not a problem in itself, it becomes one if we look at integration scenarios. Because COM is so complicated and difficult to implement, there is only one reasonably functioning implementation on non-Microsoft platforms. The German Software AG, directly using the Microsoft COM source code, has created this version. Since the information technology world is not and will very likely never be all Windows, everywhere and all the time, using DCOM application protocol across the Enterprise or across the Internet to integrate systems is not a good idea simply due to the lack of the availability for all platforms.

But even platforms competing with COM, such as CORBA, are not doing much better. CORBA implementations may be available on more platforms, but essentially the CORBA standard suffers from the same problems as COM in terms of complexity: if your object request broker (ORB) of choice is not available for certain platform or a new embedded device you are targeting, you have to wait for your middleware vendor to release the respective implementation, because writing CORBA implementation is typically beyond the scope of any company that doesn’t implement CORBA as their core business. So, at the end of the day, CORBA and COM are equally challenged by their own complexity.

Page 8: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

8 Context and Remoting

Marshaling is non-extensibleDCOM's marshaling and transports are also not really extensible. While you can influence the way in which objects are being packaged for transport by implementing some special interfaces, the rest of the remoting mechanism is essentially a closed model. Specifically, the wire format and the transport means are essentially set in stone. If an endpoints uses DCOM, the opposite endpoint must also use DCOM.

Reference counting difficult to masterReference counting is a great programming model because it solves a fundamental problem: object ownership. When you develop applications in C++ or any other object-oriented language with manual memory management, you always have to deal with the problem of who is owning the newly created objects.

Reference counting solves this ownership dilemma. Each object keeps track of its own usage count and once that drops to zero the object deletes itself. However, this opens up a whole new set of problems. If you do not execute maximum care in reference counting and balance your calls to AddRef() and Release(), you produce memory leaks that are even harder to track than those occurring if you stick with a traditional C++ model. Even harder to avoid are circular references where objects reference each other and may become groups of “zombies” taking up valuable resources once they are unrecoverable released by the mainstream application code.

While this may be tolerable some degree on the client-side, it is completely unacceptable for server-side operations, because servers need to run for months and years. Memory leaks make this impossible. Even with maturing tools, reference counting is still very difficult to master. Because COM uses a reference counting model, it also requires a mechanism called "distributed garbage collection", which periodically "pings" the endpoints to manage reference counts in case of endpoint failure. The “DCOM ping” results in added network traffic on large installations.

Registry is difficult to manage; registration clumsyWhen COM was introduced, the Windows Registry (a true child of COM) was a new and very exciting concept. However, the success of the COM component model comes now back to hunt it.

The Windows Registry has become far too complex to handle, is easily polluted by faulty install or uninstall procedures and registering COM components is

Page 9: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 9

sometimes clumsy. Another problem is that the registry is globally scope to a system and that you cannot have multiple versions of the same component co-existing on the same machine without using tricks.

The core problem for Remoting is that COM promotes location transparency. The location of a remote component is typically not known to the application but only configured in the registry. An application simply creates a component by specifying a class-ID, the matching entry is located from the Registry and the server, remote or local, is automatically launched by the COM runtime.

This model requires that each remote COM server is locally registered on each client. If you want to move the service to another server you have to update all client Registries, which may be a management problem.

The Registry-based model also makes software distribution difficult, because it is not sufficient to move files and components to the target machine, but it is typically also required to execute local code that enters information into the local registry.

Activation paradigm has component biasThe COM activation paradigm is very component oriented. That is good as long as you're dealing with components in the sense that you want to assemble applications from pre-built code blocks.

Remember that COM was initially designed to support Object Linking and Embedding (OLE) and later extended to support ActiveX controls. In both cases, a client would launch and initialize a compound-document server or ActiveX control component and use that code within its own context. Connecting to or locating objects in an already running server or service is much more difficult in COM, because that is not the primary scenario it was designed for. COM supports this explicitly only for a single machine and through the little known Running Object Table (ROT).

Connection oriented protocolLastly, DCOM is a connection-oriented protocol. In DCOM, the connection between client and server is established once and maintained for the duration of the conversation.

This typically no problem or may even be optimal for systems that only have a couple dozen active clients, but if you take this model to the Internet and high-capacity Internet server systems, the connection-oriented model does not work well.

Page 10: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

10 Context and Remoting

Connection-oriented server models cause the server to watch and maintain each individual client connection, which each may consume up several valuable server resources, but at least a dedicated TCP/IP socket. In addition to that, DCOM uses its own transport layer and numerous “random” IP ports, for which firewalls have to be specifically adjusted. In today's security critical Internet environment, this is a very real problem for many system administrators.

The .NET Remoting model is designed with these "lessons learned from the past" in mind and addresses most of the issues listed above.

Page 11: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 11

Section 1: Overview

.NET Remoting Core ConceptsThe Federated Services ModelBefore we dive into the technical details of the .NET Remoting model we are going to look at some other design motivations besides adjusting the Remoting model for the Internet reality. At the heart of Microsoft's third generation Internet vision is the "Federated Services" model.

The scope and requirements for Enterprise application design have changed dramatically with the universal connectivity provided by the Internet. Businesses require that their applications for sales, procurement, knowledge management, accounting and their e-commerce storefronts exchange information amongst each other and with external services. Such external services may be the systems of trading partners, which accept and send business documents in XML or EDI formats, or Web Service by providers that make financial information, news or other industry related data available. Common to all these services, if they are provided over the Internet, is that they must be built open standards to allow for maximum degree of interoperability.

The overall Microsoft .NET strategy with its XML centric Enterprise servers such as Microsoft SQL Server 2000, Microsoft Exchange 2000 and Microsoft BizTalk Server 2000, the .NET building block services such as Microsoft Passport and the “Hailstorm” initiative as well as the .NET Framework with its native support for Web Services and the Visual Studio.NET high-productivity development environment for Enterprise applications was designed to allow software developers to meet these requirements.

Page 12: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

12 Context and Remoting

The portion of the overall .NET technology set that we're covering here, the .NET Framework, reaches out to services on other machines or other business domains through the .NET Remoting subsystem.

When .NET Remoting operates in the Internet context, it is using HTTP as its fundamental transport protocol, which, itself, is implemented on top of TCP/IP. Messages that are exchanged between endpoints are expressed in XML and wrapped into SOAP envelopes. In effect, .NET Remoting builds on a layered model based on open Internet standards which allows .NET solutions to be easily integrated into the context of larger Enterprise IT infrastructures and enables the consumption of services exposed by any other system through .NET and vice versa.

Page 13: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 13

Section 1: Overview

Messages – RPC is not allThe DCOM protocol is a synchronous protocol. While COM+ enables asynchronous message calls by routing them through the Microsoft Message Queue (MSMQ), this extension does not really feel "native" to the COM model and shows unfortunately only very slow adoption by many developers (which can also be attributed to the fact that the ability to create such “queued components” is not really known in much of the developer community).

The COM was designed to be object-oriented RPC Protocol and that is what it is really good at. Because RPC is not the only communication mechanism required for applications, the Windows DNA technology set features multiple different Remoting models.

You use DCOM for bi-directional message calls, the Microsoft Message Queue, Microsoft Exchange messaging or queued components for queued message exchange or unidirectional method calls and only with the new Microsoft BizTalk Server there is now a good model for bi-directional exchange of business documents or larger messages.

Since even that did not meet all requirements, the Windows DNA technology set also features additional Remoting technologies such as the ADO remote data service (RDS) and, of course, fundamental Win32 networking services such as named pipes. So, at the end of the day, you have a plethora of choices for how to get data from one machine to another machine.

The goal of the .NET Remoting architecture is not to eliminate choice, but to reduce the number of

Page 14: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

14 Context and Remoting

programming interfaces that you must know to implement solutions on these different Remoting models to a minimum. .NET will still allow you to use all the technologies listed above, either natively or through its interoperability mechanisms, but the suggested way for creating network-enabled .NET solutions, and the way you will definitely prefer, is to use the .NET Remoting infrastructure that you will learn about in this lesson.

Page 15: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 15

Section 1: Overview

Application DomainsIn COM, marshaling and in-process and out-of-process Remoting occurs frequently. Message calls get marshaled between machines, processes, COM+ contexts, threads and between COM Apartments.

Especially the COM Apartment model and its marshaling rules has caused and is causing quite a lot of headaches for many programmers, although it was initially designed to make development easier by hiding the details of process of threads synchronization from developers.

.NET simplifies this model. Marshaling and remoting of objects occurs in exactly two cases: when messages cross “application domain” boundaries or, as we will see a bit later, context boundaries.

Isolated execution space for applications, Independent of OS concept of thread, processAn application domain (“AppDomain” in Framework-Reference speak) is an isolated execution space for applications. This is possible, because .NET’s managed code uses automatic memory management that prohibits any unauthorized memory access.

The application domain model is therefore independent of the operating system concept of threads or processes. A single operating system process can host multiple AppDomains. Application domains are fully isolated entities that share nothing but the common host process and the common language runtime code.

When application domains exchange messages, independent of whether there are located within the same

Page 16: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

16 Context and Remoting

process, in different processes or even on different machines they do so through .NET Remoting.

Page 17: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 17

Section 1: Overview

The Remoting ContextDerived from COM+ context ideaThe .NET Remoting context is a special boundary around objects that shared the same runtime behavior. This very similar to the COM+ concept of contexts.

If a COM+ component that is marked as to require a transaction create another COM+ component that is configured in the same way, they will share the same context and with that the same transaction. This is similar in the .NET Remoting context. If two context-bound objects share the same runtime properties, they also share the same context.

However, while both concepts are very similar, it is very important to stress that the COM+ context is (currently) not related to the .NET Remoting context. Even if the programming model for the COM+ service integration into .NET (which is covered in the COM/Interop module) looks strikingly similar, you must strictly differentiate between the two. The two models might converge at some future point in time, but at present it is not so.

Encloses objects with same functional contextGenerally speaking, the Remoting context encloses objects with the same functional context. This means that all objects that are contained in the context behave identical in some certain ways. This behavior is controlled by properties, which are installed into the context using attributes that are specified on the object classes. You are going to see more of this later in this lesson.

Page 18: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

18 Context and Remoting

Carries shared properties that describe behaviorThe properties that exist on the context are shared by all objects and describe or even actively control or provide the behavior.

Every call that passes a context boundary is processed by the Remoting infrastructure.

Page 19: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 19

Section 1: Overview

What is “Remote”, What is” Local”?"Local" are all objects within the same AppDomain, All other objects are "Remote"So, the terminology gets quite a bit easier compared to COM. We do not have to talk about different Apartments and exactly in which threads objects are located, but only have two terms: "remote" and "local" in the very simple sense that local objects are "nearby" and the remote objects are "further away".

By principle, all objects within the same application domain are "local". All other objects are "remote", even if the application domains are hosted within the same process.

Context-bound objectsContext-bound objects are a bit special. Towards each other, all objects that share the same context are "local" and objects that are located in other contexts are "remote".

"Local": Not marshaled, immediate object callsIf you call a method on a local object, the call is executed immediately through the application stack without any marshaling taking place.

"Remote": Marshaled, calls through proxiesWhen you call a remote object, the call is routed through a proxy and all arguments are marshaled. Important: For this entire lesson the term "method" shall be seen as a synonym for all fields, properties, events, delegates and methods that class may expose.

Page 20: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

20 Context and Remoting

With .NET, you only have to memorize two different Remoting boundaries: the application domain boundary and the context boundary.

Page 21: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 21

Section 2: Remoting Architecture

Section 2: Remoting ArchitectureIn this section we are going to look at the fundamentals of the Remoting architecture. Specifically we are going to explore what messages are, how channels control where messages go, how formatters are used to render the messages into “wire formats” and how the .NET Remoting infrastructure uses these elements to create a transparent programming experience with dynamic proxies.

What: MessagesWhere: ChannelsHow: FormattersMarshaling ConceptsProxies

Page 22: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

22 Context and Remoting

Section 2: Remoting Architecture

What to communicate: MessagesMessages are objects that implement IMessageFrom a programming standpoint, messages are objects that implement the IMessage interface.

IMessage: Simple dictionary of key/values pairsThe IMessage interface is a very simple dictionary of key/value pairs. The message dictionary may contain any number of entries, each individually keyed by a string. The values that are held in the message may be of any .NET object type. The Remoting infrastructures task is to remote these dictionaries across Remoting boundaries.

.NET Message TypesTo make implementation of method calls consistent, .NET defines a few additional message types that all implement the IMessage interface. The message types include construction call messages and responses as well as method call messages and responses. Internally, the only difference between a "plain" IMessage implementation and, say, a method call message is that the method call message uses a set of predefined dictionary entries.

Invocation StylesThere are two known invocation styles for method calls and therefore two "delivery modes" for messages: If messages are being delivered synchronously, they represent a request that expect an immediate response. If they are delivered asynchronously they represent a request that expects a delayed response or no response at all.

Page 23: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 23

Page 24: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

24 Context and Remoting

Section 2: Remoting Architecture

Where to communicate: ChannelsChannels transport messagesChannels are responsible for transporting messages. As such, they are an abstraction of a specific transport protocol and wrap the protocol to make it available to the .NET Remoting infrastructure.

The .NET Framework comes with three built-in sets of channels: A TCP channel that uses permanently-connected raw TCP/IP sockets and a HTTP channel that uses the .NET HTTP infrastructure.

The channel model is also extensible; if you require support for other transport protocols, you can implement your own channels and use them with all the parts of the .NET Remoting infrastructure.

Establish endpoint-to-endpoint communicationA channel is responsible for establishing endpoint-to-endpoint communication. The transport portion of the channel implementation is handed a formatted data stream and is responsible for getting that formatted data stream to the other side – reversely, it will receive a formatted data stream from another endpoint and is responsible to deliver that to its host application domain.

Channels can listen for and send messagesChannels can listen for messages and send messages. So, the Illustration that we are showing here maybe a bit misleading, because it may functions in both directions. A client may send a message one-way through the channel to the server, and for the response the channel effectively turns around.

Page 25: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 25

Although that may be a bit leaping ahead, we should already make clear at this point, that this model also supports callbacks. If you pass an object reference through a channel and the receiver holds on to that reference and uses it for callbacks at a later point in time, the call that messages are relayed through the original channel.

The listener portion of a channel implements the IChannelReceiver interface and the sender portion implements the IChannelSender interface. A channel is only bi-directional it implements both interfaces. If you want, for some reason, implement a receive-only channel you only need to implement the IChannelReceiver interface and IChannelSender for a send-only channel, respectively. A receive-only channel can, of course, not relay any callbacks.

Makes no assumptions about endpoint architectureThe most interesting point about the channel architecture is though, that makes no assumptions about how the opposite endpoint is implemented. If the remote endpoint uses a compatible SOAP implementation that runs on some UNIX variant, the channel will be just as happy to deliver the message as if the endpoint was a native .NET application.

Page 26: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

26 Context and Remoting

Section 2: Remoting Architecture

How to communicate: FormattersFormatters serialize .NET objects into wire formatsWe have learned that messages are dictionaries and channels are able to remote data streams. The formatter’s task is to convert dictionaries into data streams and vice versa. More precisely, it transforms the method call into the appropriate wire format message.

Used dynamically by channel architectureFormatters are dynamically used by the channel architecture. You configure a channel to transport messages in a certain wire format by associating it with a formatter other than its default through the Remoting configuration facility as you will learn later when we cover Remoting configuration files. The channel will then pick the associated formatter to render messages into the desired format.

Formatters are implemented through so-called channel sinks that we will also cover a bit later. Essentially, a channel employs a sequence of these sinks, which work hand-in-hand to inspect an IMessage for logging and security purposes, turn it into a wire-format and send it off to the receiver.

On the receiving end, the formatter acts as a deserializer component that understands a certain wire format and is able to translate that into a .NET message object implementing IMessage.

Built-in: SOAP and Binary FormatterThe .NET Framework has two built-in formatters. The binary formatter uses a very compact binary format that is

Page 27: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 27

designed for best performance in high-speed LAN environments and to interconnect .NET systems.

The SOAP formatter uses the XML-based Simple Object Access Protocol to transport object calls over the Internet and to integrate .NET systems with all other systems in the enterprise environment. The built-in formatter types are, of course, pre-registered with the system.

Custom Formatters allow talking to any endpointThe formatter model is extensible. If you want to integrate systems directly using other wire formats (to name a few: IIOP, RMI, ORPC, XP, XML-RPC) you could implement your own formatters and have .NET systems talk natively to any endpoint you want.

Page 28: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

28 Context and Remoting

Section 2: Remoting Architecture

Selecting Channels: TcpChannelUses plain TCP socketsAs aforementioned, the TCP channel uses plain TCP sockets and transmits, by default, a compact, binary wire format, provided by the BinaryFormatter.

If you want to use TCP sockets with another wire format you can plug your own formatter into the TCP channel by associating it with a different formatter in the Remoting configuration.

Transmits compact, binary wire formatThe default wire-format used by the TCP channel is a simple binary data stream that is a direct representation of the message dictionary and as such it is only interoperable with .NET Framework-based systems (or systems that can interpret these data streams).

However, if you want to link .NET Framework-based systems in a LAN environment, the TCP channel and binary formatter will yield the highest performance.

Best choice for LAN communication, not recommended for Internet communicationThe TCP channel is not recommended to be used on the Internet. First, it implements a connection-oriented protocol, which harms server scalability, and secondly, the binary format is not interoperable.

However, the TCP channel is a very good candidate for Internet based peer-to-peer communication and essentially anywhere else where you would use permanently connected TCP sockets today – in essence:

Page 29: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 29

If DCOM worked well for your COM solutions, the TCP channel will work just as well for your .NET solutions.

This is especially true if you want to interconnect systems within a server farm. For these purposes, a high-speed, permanently connected Remoting channel with a native data representation is certainly the best choice.

Page 30: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

30 Context and Remoting

Section 2: Remoting Architecture

Selecting Channels: HttpChannelUses HTTP 1.1 protocolThe HTTP channel uses the stateless HTTP 1.1 protocol.

Transmits SOAP 1.1 XML formatThe default wire format is an implementation of the SOAP 1.1 standard, which is provided by the SoapFormatter class located in the namespace System.Remoting.Serialization.Formatters.Soap.

SOAP is an open, multi-company standard that has been co-developed by Microsoft and is endorsed by virtually all major software vendors. The SOAP specification has been submitted to the W3C and lays the foundation for the XML protocol (XMLP) activity. More about SOAP can be learned in the SOAP module of the .NET Developer Tools Readiness Kit.

Custom Formatters are pluggable for other formatsJust as with the TCP channel, HTTP channel also allows plugging in your own formatters. If the remote endpoint does, for instance, not understand SOAP but expects data to be submitted using the same mechanism as HTML forms, you can write a formatter that implements this behavior and to be used with HTTP channel.

Best choice for Internet communication and integrationThe bottom line is that the HTTP channel is the best choice for Internet communication and also the best choice for interoperability and integrating other systems into .NET or integrating .NET systems into the context of a larger infrastructure.

Page 31: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 31

Moreover, using .NET Remoting with HTTP channels will provide you a complete platform for implementing Web Services. You can query an HTTP channel endpoint for a WSDL description by appending "?WSDL" to the endpoint URI and this will allow you to create proxies using the Microsoft SOAP Toolkit and many other SOAP Software Development Kits that will then be enabled to talk directly to an HTTP channel of a .NET Remoting Server.

Page 32: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

32 Context and Remoting

Section 2: Remoting Architecture

Selecting Channels: CustomBring your own Protocol (APPC,IPX,Pipes, ...)As previously mentioned, you can also write your own channels. If you need to transmit data over protocols not covered by the core .NET Framework, for instance, APPC, IPX or Windows Named Pipes.

For your own channel implementation you must implement either of the IChannelReceiver or the IChannelSender interfaces, or both, depending on whether the channel is going to be bi-directional or unidirectional.

Transmit any format that fitsCustom channels can of course transmit any format.

If you need to transmit a custom format, you can bring your own formatter and if you want to use SOAP or .NET's native binary format you can use the SoapFormatter or the BinaryFormatter.

The core channel architecture will help you select the correct formatter based on the MIME type and even invoke the formatter on your behalf. However, you can also wire in your own formatters directly.

Applies to integration scenariosYou will very rarely need to write your own channels unless you have a heterogeneous environment that does not use industry standard protocols.

It is quite realistic to assume that at some point Microsoft or third party tool vendors will provide additional channel

Page 33: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 33

classes that provide transport capabilities over the most popular Enterprise transfer protocols.

Page 34: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

34 Context and Remoting

Section 2: Remoting Architecture

The Message Box: IMessageSinkMessage Sinks are the .NET message drop-offBy now we have learned about messages that are key/value pair dictionaries and about channels that somehow receive these messages, pass them to formatters to render them into a wire format and then transport them to the destination.

On the receiving end, the wire format message is received by a channel and deserialized by the formatter into the message object.

The missing link in this chain is the message sink. To submit messages into a channel, you obtain a reference to the channel’s message sink from the IChannelSender interface using the method CreateMessageSink().

To use channels, client code drops off messages into the Remoting infrastructure using the SyncDispatchMessage() or AsyncDispatchMethod() method on the ChannelServices class, which resides in the System.Runtime.Remoting namespace.

Implemented by channels to accept messagesThe IMessageSink interface is implemented by channels and the Remoting infrastructure to accept messages.

Implemented by context properties for interceptionAnother use for the IMessageSink interface is interception. For this purpose, the interfaces implemented by context properties, which we will get to know a little later.

Page 35: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 35

Allows building chains of sinksThe IMessageSink interface has a NextSink property, which is designed for allowing building chains of message sinks. As you will learn in the following, message chains are a very common design pattern throughout the Remoting infrastructure.

When implement your own message sink you must therefore honor the property by passing any message, which you do not want to handle yourself, onward to the next sink.

It is, however, perfectly legal to intercept, modify or process any message received in a message sink implementation instead of passing it through to the ultimate destination.

Page 36: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

36 Context and Remoting

Section 2: Remoting Architecture

Objects To Go: MarshalingDefinition: Packaging Data for TransferNow we need to take a closer look at the message content. Since you ultimately want to remote method calls, the message will likely contain inbound and outbound arguments as well as return values.

The serialization of these arguments into the appropriate wire format is the job of the formatter. However, because we are dealing with an object-oriented system here, you will not want to flatly pass all object data by value only. Instead, you will want to be able to pass references to objects that reside in your own application domain or a context for other objects to make calls to them. Making this distinction is the objective of the marshaling rules.

The word "marshaling" has its roots in the military. The marshal is the military commander who gets the troops in proper order for parades. Likewise, in computing, the “marshaler” is the authority that orders data bytes for network transmission. A simple synonym for marshaling would be "packaging data for transfer".

For objects passed as arguments, return valuesMarshaling applies to all objects that are passed as input arguments or returned as return values or output arguments for an object’s fields, properties or methods.

Since everything is an object in .NET, marshaling also applies to everything if it is crossing a Remoting boundary.

As aforementioned, there is a certain set of rules that determines whether an object is passed by reference or by value. Note that these rules for marshal by value and

Page 37: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 37

marshal by reference are not equivalent to the basic rules of the Common Type System. Therefore and before we get to these rules, we will first inspect the fundamental differences between marshaling by value marshaling by reference.

Marshal-By-ValueWhen you marshal an object by value, the entire object is packaged as-is and the copy is transferred to the destination. With that, there is no link between the copy and the original.

Marshal-By-ReferenceMarshaling by reference just causes a reference to the object being packaged and sent to the destination.

Once a reference arrives at the destination, the Remoting infrastructure will automatically create a proxy object that mirrors the shape of the original object (it will actually create two proxies, but we will get to that later) and passes this proxy on to the receiver. The receiver can then make calls on the proxy as if it were a local object and the proxy translates and routes the call data through the channel back to the application domain hosting the object.

Page 38: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

38 Context and Remoting

Section 2: Remoting Architecture

Concepts: Agile and ContextfulNow we get to the marshaling rules. Classes fit into two categories: agile objects and contextful objects. The difference between the two is that contextful objects live inside a context and agile objects do not.

Agile ObjectsThere is never a Remoting boundary between a caller and “agile objects”. Within application domains, calls made to agile objects are always direct and dispatched through the stack. (Let us stress that this applies to calls to agile objects, not necessarily to calls from agile objects.)

If the class of the agile object is "unbound", it is always marshaled by value (or even never marshaled at all, if it cannot be serialized by a formatter). That means that as soon the object crosses a Remoting boundary, it is cloned. This behavior applies to all value types within the .NET Framework. While this is expected, all classes are also "unbound" by default. This concept is not entirely identical to the "value" and "reference" type difference made in the Common Type System (CTS).

The differentiation that the makes between by-value and by-reference objects applies to all method calls, independent of whether they are subject to Remoting or are dispatched through the stack. While value types are always marshal by value in Remoting as well, the respective equivalence is not true for reference types.

So when it is being said that all classes are "unbound" by default, it means that they are always marshaled by value once they hit a Remoting boundary. This concept is great

Page 39: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 39

to optimize distributed systems but must be used with utmost care.

Because unbound objects are the default, data is always replicated across boundaries. This reduces the round trips between client and servers, but may be a problem for your data integrity if you are not aware of this behavior.

The ADO.NET DataSet, for instance, is an unbound, agile class whose code is always executed locally. Therefore, the design pattern that you can find implemented in Visual Studio .NET is that there is always a retrieval function that returns an entire dataset and an "update" method that receives a dataset. With that, the dataset can be safely replicated to a remote client, managed there by only using local calls and is replicated back to the server when it is passed as an argument to the "update" method.

If an unbound class has no serialization support, it cannot be marshaled and will cause a remote method invocation to fail, if it as used as an argument or return value.

Adding serialization support to a class requires setting the "[serializable]" attribute on the class and, optionally, implementing the ISerializable interface of the class. This allows Formatters to use the serialization support of the Runtime to render the class content in XML or a binary data stream, which can then be translated into the formatter's native wire format.

Classes that are bound to an application domain (“AppDomain-bound”), are seen as to "live" within that application domain and have a distinct, unique identity. Therefore, they are always marshaled by reference.

You must signal this wanted behavior to the Remoting infrastructure by deriving your class from the base class System.MarshalByRefObject. Marshal by reference classes do not have or require serialization support.

Contextful ObjectsContextful objects fall into the second Remoting class category. A contextful object is bound to both its context and the application domain it is hosted in.

This is signaled to the Remoting infrastructure by deriving the class from the system-provided base class System.ContextBoundObject.

Contextful or context-bound objects are always remoted across context boundaries. Agile objects that are referenced by context-bound objects are always called directly, unless a reference to them has become known to the context-bound object through a Remoting boundary. Calls from agile objects to contextful objects are always passed through a Remoting boundary.

Page 40: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

40 Context and Remoting

Section 2: Remoting Architecture

Objects calling Objects: Proxies"Proxy" DefinitionThe term "proxy" has already been mentioned a couple of times. Here we want to take a closer look at this concept. In general, a proxy is an object that exists and acts locally on behalf of a remote object. The proxy looks like and accepts calls as if it where the “real” object.

The proxy exposes the same set of interfaces that original object exposes. However, the proxy does not process the calls locally, but sends them to the remote object it represents. The .NET Framework differentiates between two types of proxies: The “real proxy” and the “transparent proxy”.

Real ProxiesA real proxy is an instance of a class that inherits from the abstract base class RealProxy that is defined in the System.Runtime.Remoting namespace.

The real proxy accepts messages (IMessage) through its Invoke() method and forwards them to a remote object. With this functionality the real proxies are the transport layer for transparent proxies (discussed below). However, they do not only do the bulk of the work for the transparent proxies, they also are also the “factories” to create them. The RealProxy base class is able to dynamically create a transparent proxy for any arbitrary .NET class-type through metadata and .NET Reflection and have that transparent proxy call the real proxy's own Invoke() method.

Page 41: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 41

Transparent ProxiesA transparent proxy is a dynamically created block of code that exists in the client application domain (or context) on behalf of the remote object and exposes all of its features, including all fields, properties, events, delegates and methods.

When you call a method of the transparent proxy, the proxy formats all of the arguments and the method name into a message object and submits this through the real proxy's Invoke() method to the remote object. Once the method returns, it decodes the message elements and places them back on the local stack so that the calling code can pick them up.

Page 42: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

42 Context and Remoting

Section 2: Remoting Architecture

Proxies illustratedThis diagram illustrates the dependencies between the real proxy and the transparent proxy as well as the message sink and the channel.

Let us first assume we already have a transparent proxy that we can call. When we call the method "MethodA()" on the transparent proxy, it will format the method name and the arguments, if such are present, and forward them to the real proxy's Invoke() method.

The real proxy will then (typically) drop this message into the IMessageSink of the channel through the sink's SyncProcessMessage() method. Since .NET makes no assumptions about the endpoint architecture, we're not doing this either, and just assume that the message will somehow be responded to. Once the real proxy receives the response message, it will pass the response message on to the transparent proxy, which will push the return values on the stack. With that, the calling code will “believe” that it just called a local method.

How is the real proxy built? When a channel receives a message that contains an object reference (an instance of the ObjRef class), the reference information also contains the type of the referenced object. With that data type in hand, the channel will creating a new RealProxy instance and asks it to create a new transparent proxy based on the metadata of that data type. This transparent proxy object is then passed on to the called method.

Page 43: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 43

Section 2: Remoting Architecture

The DispatcherLocated at the channel endpointThe Dispatcher is the proxy's counterpart at the receiving end of the communication and located at the channel endpoint.

The Dispatcher’s capabilities are provided by the StackBuilderSink class that is located in the System.Runtime.Remoting.Messaging namespace.

Receives messages, builds stack-frame, invokes methodWhenever one of those two methods is called, the passed message object is decoded and the Dispatcher will locate the object it that is referenced in the call, will dynamically create a stack frame that contains all arguments and will execute the requested method. If the Dispatcher receives an object reference to will create a real proxy, ask the real proxy to create a transparent proxy and push the reference to the transparent proxy onto the stack.

Collects result and creates response messageWhen the method call returns, it will collect the output parameters and the return value and create a response message with them. The dispatcher will, of course, turn marshal by reference object references into references that are passed over the network and “proxied” on the receiving end. The response message is then being handed back to the caller.

Page 44: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

44 Context and Remoting

Section 2: Remoting Architecture

The Dispatcher illustratedHere's a graphical representation of what we just explained. The message arrives at the receiving end of a channel, is being the serialized and formatted into a message objects and this message object is passed to the StackBuilderSink.SyncDispatchMessage() method. The call is dispatched on the real object and all values that must be returned are being collected and sent back as a response through the channel.

Page 45: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 45

Section 2: Remoting Architecture

Channel SinksMost of the functionality that was explained up until this point is actually implemented in a chain of channel sinks. A channel sink is a pluggable component that is provided to the channel through a channel sink provider class.

A channel sink provider class is implementing the interface IClientChannelSinkProvider if it generates sinks for the client side of a channel and implements IServerChannelSinkProvider if it generates sinks for the server side. The sinks themselves implement IClientChannelSink and/or IServerChannelSink.

When a channel is created, you will, as in the case of the HttpChannel or TcpChannel, be able to pass an implementation of either or both interfaces to the channel, letting you install your own channel sink.

Channel sinks may implement interception, security checks, logging or whatever else you want to control or monitor regarding Remoting traffic.

A very special case are formatter sinks. These are provided by implementations of either IClientFormatterSinkProvider or the IServerFormatterSinkProvider interfaces and perform the conversion from and to the wire-format. A formatter sink implements IClientFormatterSink and/or IServerFormatterSink.

When a channel is constructed, the providers are asked to provide channel sinks, which are then linked into a chain of sinks. A call from a client will then be routed from the proxy to a formatter sink (or a custom sink that is placed before the formatter sink), then to possibly existing custom

Page 46: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

46 Context and Remoting

sinks and finally to the transport sink that will typically be provided by the channel implementation. On the receiving end, the channel architecture works similarly in the other direction.

Page 47: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 47

Section 2: Remoting Architecture

Some Advanced TopicsThe Remoting architecture contains much more than what we can cover in this one lesson without starting to confuse you. Therefore, we have picked out just two interesting advanced topics that may be generally useful and that you may want to look up in the .NET Framework SDK Reference.

Declaring Methods "One-Way"You can declare methods one-way using the [oneway] attribute on the message. The declaration works as shown on the slide. When this attribute is present on the method, the dispatcher will not collect any return value information and the proxies will not wait for such information to arrive and return immediately to the caller.

The Call ContextA very valuable tool is the call context. (Do not confuse this with the .NET Remoting context) The call context allows you to add "invisible" arguments to a method call. While there will only be rare uses in end-to-end communication, the call context is a true lifesaver when you are using context interception and take advantage of the extensibility mechanisms and the message chain that we are going to discuss in the now following section.

Each message object automatically contains a dictionary entry "__CallContext" that holds an instance of the type "CallContext".

Page 48: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

48 Context and Remoting

Section 3: Contexts and Interception

Section 3: Contexts and InterceptionNow that you know the fundamental Remoting infrastructure, it is time to take a closer look at the context concept. In this section we're going to look at the context rules and concepts, will investigate what context attributes and properties are and will then shed light on the interception mechanism that is available using contexts and that allows you to extend objects with functionality in a declarative manner.

Context Rules and ConceptsContext Attributes and PropertiesContext CharacteristicsInterception: Context and Message ChainsStandard Context AttributesCustom Context Attributes

Page 49: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 49

Section 3: Contexts and Interception

Context Rules and ConceptsContexts enclose "contextful" objectsLet us recap a couple of facts that you already know about contexts. The .NET Remoting Context encloses contextful objects. All contextful objects must be derived from the System.ContextBoundObject class and the class’s behavior is controlled by context properties that are declared for the class using attributes.

Common context boundary is sharedObjects share a common context boundary when they have identical attributes or when the context attributes “actively agree to deviations of attributes”. Simply speaking, each attribute is being asked whether it is "okay" with the context.

All objects in other contexts are "remote"All objects in other contexts are remote, regardless of whether they are located in the same application domain or not. The context boundary is conceptually similar to the application domain boundary.

Messages crossing boundary may be interceptedThe message is that the cross the context boundary may be intercepted and chains of IMessageSink interface implementations allow hooks at any stage.

Page 50: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

50 Context and Remoting

Section 3: Contexts and Interception

Context Attributes and PropertiesThis diagram illustrates the relationship between context attributes and context properties. When an instance of a context bound class is created, and the class is declared with attributes, the activation process for the new object works as follows:

At creation time (when you create the class using new or going directly through the “Activator”) and before the constructor code is executed, an instance of the context attribute class is created and its constructor is called. This behavior is different from simple attributes, whose constructor is only called when you explore them through Reflection.

All arguments that you have provided for the attribute at declaration time are passed to the new context attribute instance at this point.

In the next step (shown as step [1] in the illustration), the runtime calls the method "IsContextOk()" on the context attribute, passing a reference to the context object from which the object was created, if such a context exists. If no context exists, this step is skipped.

The context attribute can now decide, whether the existing context can be used for the behavior that the attribute describes. The attribute should specifically return "false", if a property exists on the context that conflicts with its own settings and the intended behavior.

If the response is "true" or if the object was created from outside an existing context, the new object instance will be placed into the existing context, otherwise a new context is being created.

Page 51: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 51

In the latter case [2], the Runtime will call the method GetPropertiesForNewContext() on the context attribute object, allowing it to install one or more properties into the newly created context.

If a new context is created, the Runtime will call this method regardless of whether an individual context attribute found the context to be acceptable -- this method is invoked for all attributes that exist on the class. If a single context attribute votes “false” on IsContextOk(), all attributes must provide a new property.

Finally [3], the runtime places the new instance of the context bound class into the new (or “recycled”) context.

Page 52: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

52 Context and Remoting

Section 3: Contexts and Interception

Interception: Message ChainsOne of the primary reasons why you may want to use the context paradigm for your applications is message interception.

We will get to the rationale a little while, but before that we need to know how interception works and what the extensibility mechanisms of .NET Remoting in conjunction with contexts are.

Every message passes a four chains of sinksWhen messages are being exchanged between objects that reside in two different contexts, they pass four different message chains. If the call is relayed between a contextful object of one application domain and an agile object that resides in a different application domain, the context chain is of course not available in the application domain of the agile object.

The message chains will be explained in detail in a short while.

Context properties contribute these sinksThe method sinks are installed into the message chains by the context attributes. For this a context attribute must implement one or multiple of the interfaces:

IContributeObjectSink

IContributeClientContextSink

IContributeServerContextSink

IContributeServerEnvoySink

Page 53: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 53

Special cases are dynamic properties that are not illustrated here. Dynamic properties can be installed at any time into a context and without using context attributes, so that you can always listen in to the traffic going in it out of a certain context whenever you need it.

Custom attributes allow intercepting all trafficAnd if it is not apparent by now: You can most certainly implement your own context attributes and use all these extensibility mechanisms.

Page 54: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

54 Context and Remoting

Section 3: Contexts and Interception

Chain Hooks: Message SinksServer Object SinkThe server object chain is a per-instance message interception mechanism, where an instance of an implementation of the IMessageSink interface can be installed for each individual object that resides in a context. Server object sinks are installed into the server object chain by returning a new sink implementation from IContributeObjectSink.GetObjectSink().

Server Context Sink, Client Context SinkThe server context chain is a per-context message interception mechanism, where such a message sink objects can be installed as a gatekeeper for the entire context. The sinks that are installed in the server context chain will see all messages directed to objects located within the context. Server context sinks are installed by returning a new IMessageSink implementation instance from the context property’s IContributeServerContextSink implementation through GetServerContextSink().

The client context chain is the exact equivalent of the server context chain on the client side. In fact, if the server calls a callback method on the client these two message chains switch roles and names. Server context sinks are installed by returning a new IMessageSink implementation instance from the context property’s IContributeClientContextSink implementation through GetClientContextSink().

Server Envoy SinkThe server envoy chain is a very powerful and interesting concept. It allows the server to inject code on the client

Page 55: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 55

side by means of interception, which allow it to control message flow and communication.

Imagine a remote component that requires you to set a couple of properties before you invoke a certain method as this is the case with many of today's ActiveX controls.

If you need to set five properties before you can invoke the method this will result in a total of six round trips to the server. Using server envoy chains you can reduce this to exactly one round-trip by queuing up the property set requests within the envoy sink and placing them into the call context once the method is called.

The server object sink may then extract the properties from the call context, set them appropriately on the target object, and invoke the method. The very cool thing about this is that neither the original client or server implementations need to be changed to achieve this behavior, but only the appropriate envoy and object sinks need to be the provided. All this occurs "under the hood".

Envoy sinks are installed by returning a new IMessageSink implementation instance from the context property’s IContributeEnvoySink implementation through GetEnvoySink().

Page 56: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

56 Context and Remoting

Section 3: Contexts and Interception

Attribute Driven BehaviourSample Context Attribute: CallTraceAttributeThe sample context attribute "CallTraceAttribute" that is provided with this lesson illustrates attribute driven behavior. It intercepts all calls crossing the context boundary and writes the methods and arguments to a log file.

How to establish interception?The illustration on the slide shows how a message sink is installed into the chain.

Page 57: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 57

Section 3: Contexts and Interception

Standard Context AttributesThe following two examples show context attributes that are part of the .NET Framework and modify the behavior of context bound classes through interception.

[Synchronization] AttributeThe [Synchronization] attribute is the reincarnation of the COM Apartment model in .NET – with a lot less hassle, though.

In COM, the Apartment model synchronizes concurrent requests that are made to a component from several threads through the Windows (windowing) Message Queue and allows components that execute in a multi-threaded environment to be written as if they were single-threaded.

When you apply this attribute on context-bound objects, the associated context property will intercept all incoming traffic into that particular context (which may host multiple objects) and will queue up the calls so that only a single call is handled at any given point in time.

COM+ Context RelationshipAs stated before, most of the behavior looks very much like the COM+ context behavior, but we really need to drive this point home: As of Beta1, the COM+ context boundary is different from the .NET Remoting context boundary. COM+ contexts and .NET Remoting contexts may or may not overlap and there is no relationship between the two.

The COM+ context management is part of the COM/Interop facility in the .NET Framework.

Page 58: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

58 Context and Remoting

Page 59: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 59

Section 3: Contexts and Interception

Context Characteristics.NET Remoting Contexts have some additional characteristics that we have not mentioned up to now:

Context Local StoreEach context has a “context local store” where you can store arbitrary data that is associated with the context. This is similar to the shared properties that you know from COM+ (or the predecessor technology MTS).

The context local store lets you store any reference or value type .NET objects and share them among all objects that reside in the context. You can place data into the context local store by calling SetData() on the current context and retrieve them through the GetData() method.

Context StaticsContext statics are static member variables of a class that are implemented on top of the context local store. The beauty of context statics is that they are automatically managed by the Runtime and only require you to use the [ContextStatic] attribute on a static member of a class.

Once you use this attribute, the .NET context implementation will automatically allocate a context local store data slot for this static variable and let all class instances residing in the same context share the same value.

Access to the current context via Thread classThe “current context” in which the current thread is executing can be accessed using the static method GetCurrentContext() that is implemented by the Thread class residing in System.Runtime.Threading.

Page 60: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

60 Context and Remoting

Section 4: Serving and Accessing Objects

Section 4: Serving and Accessing ObjectsAt this point, you know all the fundamentals about .NET Remoting; you know how objects communicate and what mechanisms are used to marshal calls across Remoting boundaries and you also know how contexts function. What we haven’t covered until now is how objects are actually instantiated and how running instances of objects can be accessed. This section covers how you serve up new or existing object instances and how you can access those from a client.

The topics covered in this section are:

Remoting ServicesExposing Well-Known ObjectsExposing Classes for Client-Side ActivationConfiguring Remoting and Registering ChannelsActivation and Access

Page 61: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 61

Section 4: Serving and Accessing Objects

Remoting ServicesThe System.Runtime.Remoting namespace contains a couple of so-called service classes that allow you to configure and tweak the runtime behavior of the Remoting system.

System.Runtime.Remoting.RemotingServices classThe most fundamental of these classes is the RemotingServices class, which provides facilities for connecting to and creating new remote object instances.

System.Runtime.Remoting.RemotingConfiguration classThe RemotingConfiguration class provides facilities for Remoting configuration as well as methods to register “well known objects" and client-activation objects. We will cover these aspects on the following pages.

System.Runtime.Remoting.ChannelServicesThe ChannelServices class serves to manage and register .NET Remoting channels. The Remoting architecture makes a very clear distinction between object endpoints and transport endpoints (that’s what channels are). You can register any number of channels with the channel services. These channels are global for you application domain and define the transport endpoints that your application exposes.

If you register a TCP channel on port 8085 and a HTTP channel on port 8080, all object endpoints that have been registered with RemotingServices will be equally available on both channels.

Page 62: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

62 Context and Remoting

System.Runtime.Remoting.LifetimeServicesThe Lifetime services provide control over the “distributed garbage collection” in .NET Remoting. Distributed garbage collection is a model that is somewhat similar to what DCOM does with its little loved “DCOM ping”, but it works differently. The goal of the lifetime services is to manage the lifetime (go figure!) of objects by giving them “leases on life”, essentially timeouts.

By default, each object that is only referenced by a remote client will be marked for garbage collection after 5 minutes. The lease will be renewed for another 2 minutes with each call made to that object. You can alter these settings on the LifetimeServices object.

If you know that a particular object will not be called for a longer period of time than the default timeouts but you do not want to change the mechanism globally, you can create a “sponsor” for that object and register it on the object’s ILease interface that you can obtain through the GetLifetimeService() method that every AppDomain bound, MarshalByRefObject derived class and every contextful class inherits.

If an object’s lease expires, the object is marked for garbage collection and all existing remote references to this object become invalid.

System.Runtime.Remoting.TrackingServicesThe tracking services serve to “track” most everything that is happening in the Remoting subsystem: Whenever an object becomes disconnected (after its lease has expired or a connection is broken) or when an object has been marshaled or unmarshaled (a proxy has been built), the tracking services will invoke a user provided implementation of the ITrackingHandler interface.

Page 63: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 63

Section 4: Serving and Accessing Objects

Exposing Well-Known ObjectsLet’s unravel the mystery of how an application can expose objects or classes to clients.

.NET's activation model is very unlike COM's

.NET’s preferred activation model is, surprisingly, very unlike COM’s activation model. It rather resembles, next surprise, the activation model of CORBA.

Unlike COM, the .NET Remoting infrastructure does neither need nor use the service control manager (SCM) that automatically acts in the background on a remote server machine in COM and automatically launches server processes or wraps components into “surrogate” processes like the “DLLHOST.EXE” wrapper for DLL-based components.

The model is as simple as this: If there is no actively listening endpoint, you cannot establish a connection to a server process. There is no “magic” instance that will launch a process for you and there are no automatic surrogates. You may consider that as a step back from the “careless” easiness of COM, but in fact, dropping these elements makes Remoting a lot easier to configure and program. Especially when you try to deploy security-enabled DCOM implementations, finding the proper parameters and configuration settings that avoid that the SCM behaves “erratically” and fires up a new server instance for each client request can turn into a nightmare.

Consequently and because there is no server to be activated by the runtime system, there is no longer a need to register locale of remote servers: The Windows Registry doesn’t play any role in .NET Remoting.

Page 64: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

64 Context and Remoting

In addition, this activation model also reflects the reality on the Internet a lot better: You connect to running servers.

Client-Activated objects are still available in .NET, but they behave quite a bit different – because the server needs to run.

Expose well-known object for clients to connect.To expose (or publish) objects to clients, you need to register them with the RemotingServices class using a “well-known” name. The RemotingServices itself bind any registered object to the channels registered on the ChannelServices, so that each object gets a “well-known” endpoint.

“Well-known” means that once you make that information available through your program documentation, web-site, DISCO documents (see the Web Services module for details) or UDDI, the clients can connect to an object using a published and, hence, well-known name.

Objects can only be published using these well-known names and therefore the COM concept of programmatic identifiers (ProgIDs) or class-identifiers (CLSIDs) is neither supported nor required.

There is, of course, an exception to this rule when you want to use .NET objects through COM/Interop services (which is covered by the module with the same name). However, COM/Interop will only bind to local objects based on local metadata and you would have to use .NET Remoting configuration to allow remote calls on such objects. From a .NET Remoting perspective, COM/Interop will always make calls to a local .NET object, which will then call a remote .NET object – therefore, the COM concepts do not apply to Remoting in any way.

Can expose "single call" or "singleton" objectsUsing well-known endpoints with “registered” objects, you can publish objects with two different activation characteristics: “single call” objects and “singleton” objects.

In addition, there are, as said, client-activated objects, but we will cover the well-known objects first before we get to those.

Page 65: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 65

Section 4: Serving and Accessing Objects

Single Call and SingletonsWhen you register well-known objects, there are two fundamentally different behaviors from which you can choose and which you can specify at registration time: Single Call Objects and Singleton Objects.

"Single Call" ObjectsSingle Call objects are entirely stateless and a new object instance is created for each call. This is essentially the same model that you know from COM+ or Microsoft Transaction Server (MTS) and provides the stateless model – and scalability – of the Web.

Note that there is currently no object-pooling available for single call objects – for each call a new instance of the object is created and the instance is discarded immediately after the call.

"Singleton" ObjectsSingletons exist exactly once and there is a single, shared object instance to which all clients connect. Singleton objects can serve as “gateways” into stateful applications that require “live” objects to exist for a longer period of time.

Singleton objects are very much like CORBA endpoints in this sense. You can connect to a live object and navigate into an existing pool of stateful objects through this gateway object. Caution: Calls to singletons may come in one random threads and, hence, thread synchronization using Monitors, Locks or Mutexes is not only recommended but required.

Page 66: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

66 Context and Remoting

The Singleton object is created as soon as you have registered its class with the RemotingConfiguration infrastructure.

RemotingServices.RegisterWellKnownServiceTypeSingleton or Single Call objects are registered on the RemotingServices class with a call to RegisterWellKnownServiceType(). That you register an object is, in fact, not entirely accurate. You register the “type” (or better: class) of the object and the RemotingConfiguration infrastructure will use the type information to either create a new instance of that class for every call or to immediately create a new instance to be used as a singleton object. In neither case you can pass arguments to the object at creation time – just as in COM.

Page 67: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 67

Section 4: Serving and Accessing Objects

Server Setup ExampleThe example shown here illustrates the registration of a well-known object and the resulting URI that a client can use to connect to the object’s endpoint.

Registering a well-known object and making it available for remote clients doesn’t take more than three simple steps:

Create a new channel object instance, providing an IP port to listen on or some other address information, if you have a custom channel.

Register the channel with the ChannelServices class.

Register the class of the object and the endpoint identifier, which must be unique for your application. The last argument for the call indicates whether the object shall be single call or singleton. Here, it’s a SingleCall object.

The result from these registration steps is that your .NET application exposes an object on the shown endpoint: “http://myserver:8080/MyEndpointURI”.

Look again –– yes, your .NET application, independent of whether it is a service process, a Windows Forms application or Console application is a full-blown HTTP server without using Internet Information Server or another HTTP infrastructure. You can hit this address with a standard web-browser appending “?WSDL” to the endpoint address and will see – the WSDL service contract.

This turns any .NET Remoting application using HTTP and SOAP into a Web Service – amazing, isn’t it?

Page 68: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

68 Context and Remoting

Channels and Objects are AppDomain-GlobalAll channels that you register with the ChannelServices and all objects that you register with RemotingConfiguration are globally scoped to the application domain. Each registered object is available on all channels.

Page 69: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 69

Section 4: Serving and Accessing Objects

Client Side ActivationClient-Side Activation is .NET’s reincarnation of the COM activation model, but with a very significant difference.

Client-Side Activation similar to COMJust as in COM, clients can instantiate new objects from a remote server using Client-Side Activation. This activation scenario is also where the lease-based lifetime control services apply. Just as with Singletons or Single Call objects, the request is pointed to a well-known, registered endpoint.

The important difference is that the server process is never launched automatically and must run for clients to connect and create new objects.

Server Side ImplementationOn the server-side, you only need to have a very minimal server process that can essentially be idle in terms of user provided code. If you look at the Remoting samples provided in the .NET Framework SDK (find the “MyHost.cs” file) or the simple object samples provided with this module, you will see that the hosting application domains for client activated objects are very minimal and do not implement much “self-activated” code.

The only code you need to write to provide client-activated objects is to register a class with the RemotingConfiguration class through the static RegisterActivatedServiceType() method and from there, the runtime will take care of object instantiation. The only job of the hosting application domain is to stay alive and in memory, because shutting down the application domain

Page 70: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

70 Context and Remoting

means to shut down the channels and garbage collect all active objects on the server side.

You can determine a proper time to shutdown your server (meaning: when no more clients are connected) by installing a tracking handler on the TrackingServices and track the number of actively served objects.

Client Side ImplementationOn the client-side, objects are created through the Activator, which we are going to discuss shortly. The Activator is responsible for establishing connections to existing remote objects or to create new, client-activated remote objects through a call to its CreateInstance() method.

An alternative to using the activator directly is to use the language bindings of C#, VisualBasic.NET and all other .NET languages whose “new” operators (or equivalents) result in an MSIL instruction “newobj”, which binds to the Activator class. Because Activator can be configured using configuration files, as you will see in a bit, you can therefore create remote objects simply using the “new” operator from your preferred .NET language.

Page 71: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 71

Section 4: Serving and Accessing Objects

Object Activation and ConnectionLet us look at the Activator in a bit more detail:

The Activator (System.Activator)The Activator class (residing in the System namespace) is .NET’s one and only way to create objects. Every object instantiation is performed through and by the Activator, independent of whether you call it directly or use your development language’s object creation operator (C#: new).

This allows the Activator to be configured and have it decide dynamically, whether an object is created locally or remotely.

To create objects, the Activator has a set of overloaded CreateInstance() methods with differing parameter lists that each expect an argument of type System.Type (or a string reference to such a type) to create a new object. The methods allow you to pass arguments to the newly created object to call its constructor and will also let you specify parameters to pick the correct implementation Assembly based on culture information (locale), version information and “evidence” (Evidence is a security concept, which is explained in the Security module).

If you want to connect to an existing, well-known object, you can call the GetObject() method on the Activator providing an endpoint URI like the one that was shown in the server setup example.

Page 72: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

72 Context and Remoting

RemotingServicesIf the activator has determined that an object needs to be created or accessed remotely, it forwards the call to the Connect() method on the RemotingServices class.

Connect() provides low-level access to Remoting and lets you activate objects remotely even if the class is not configured to be remote in your application domain. The Connect() method takes an argument of type System.Type (or a string representation thereof) and an endpoint URI as arguments. The return value is a properly proxied object, if the call succeeds.

The type information is used to extract the metadata from an Assembly to create the transparent proxy from the real proxy. Therefore, the metadata of the remote class must be available to the client at runtime. This does not mean, though, that the client must possess the actual server implementation Assembly. The client side may rather have a reduced copy of the metadata that only describes the full structure and that is sufficient for the proxy to build a structural image of the remote class.

One way to do this is to use the soapsuds utility that is included with the .NET Framework SDK. The easiest way to build a metadata-only Assembly is:soapsuds –ia:<inputAssemblyName> -oa:<outputFile>Refer to the documentation for details on how to use soapsuds.

Page 73: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 73

Section 4: Serving and Accessing Objects

Activation illustratedThe diagram shown here summarizes the Remoting activation concepts that have been presented up until this point.

Either using the Activator or the language binding through “new”, you create new objects or access existing well-known objects. If the Activator decides that an object is remote, it forwards the call to the RemotingServices, which establish an outbound channel based on the URI prefix and connect to a well-known endpoint on the server side.

All registered endpoint URIs are maintained in an identity table on the server side, which includes the activation type. For Singleton objects, the request is then routed to the only existing instance and for Single Call objects a new instance is created. If the object is client-activated, a new instance is created and returned and handed to the LifetimeService for lifetime management. Each client-activated object gets its own entry in the identity table so that clients can properly reconnect on stateless protocols like SOAP.

Page 74: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

74 Context and Remoting

Section 4: Serving and Accessing Objects

Configuring RemotingRemoting configuration was mentioned quite a few times in the context of the Activator, but now it’s time to take a closer look.

The configuration feature of .NET Remoting is truly remarkable and one of the strengths of the entire architecture, because you it allows you to pretty much forget about all the explicit calls that we have run by you in most of this section. Instead, you can simply write a configuration file, load it into your application domain and all registrations for whether objects are remote or local and what channels your application uses or makes available are done by the runtime.

Remoting Configuration ArchitectureSpecifically, the remoting configuration architecture allows you to define endpoints, well-known objects and client-activated objects at installation time (or later) and therefore provides maximum control for Administrators.

With that in mind, you can build applications whose code “does not worry” about Remoting except for picking the proper base classes like MarshalByRefObject and ContextBound object and an Administrator can later decide whether to run your application on a single machine or split across multiple machines. The only work that needs to be done is to write a proper configuration file and testing, but the code and, actually, the Assemblies do not need to be touched – remoting reconfiguration without recompiling.

Page 75: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 75

Configuration is file-basedThe entire configuration is file-based and resides in the application’s configuration file. The configuration format is be XML and integrated with the standard .NET configuration architecture. However, unlike most other configuration aspects of the .NET Framework, you must explicitly load the Remoting configuration through a call to the static method Configure() on the RemotingConfiguration class for those settings to have any effect.

Page 76: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

76 Context and Remoting

Section 4: Serving and Accessing Objects

Server System ConfigurationThe slide above shows sample definitions for how to construct a channel type for use with Remoting configuration.

Channels are configured within the <channels> tag below the <system.runtime.remoting> tag in the configuration XML file. Each <channel> type is configured with its own "id" identifier that can later be reference when applications are configured to use this channel type. The "type" references a channel implementation is a specific Assembly, in this case the HttpChannel that is provided with the .NET Framework. Using this syntax, you can also use your own channel implementations.

A sibling of the <channels> tag is the <channelSinkProviders> tag that configures the channel sink providers available to a applications. Using the <provider> tag (not shown here), you can configure "simple" sinks and associate them with an "id" and with the <formatter> tag, you can define formatters like the SoapFormatter as shown in this example.

The configuration file here does not configure the behavior of a certain application, but is more like an declarative assembly of channels. This also explains why the Remoting configuration must be explicitly loaded. Remoting configuration files are always additive. You can first load a file that defines certain channel setups or providers and associates them with an "id" and, as you will see on the following page, associate them with actual channel instances in another file that is loaded later. So, whenever you call RemotingConfiguration.Configure() with a file, the settings contained in the new file will be

Page 77: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 77

added to the configurations already existing and are also capable of referencing the existing settings.

Page 78: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

78 Context and Remoting

Section 4: Serving and Accessing Objects

Server Application ConfigurationThe second configuration file we are showing will actually configure an application and setup channels and well-known types.

Below the <application> tag, the <service> tag contains all well-known objects and activated types along with their endpoint URI and their object mode just as you have previously seen it with the explicit calls to the RemotingConfiguration class.

In the <channels> section, the channels can either be explicitly defined just as with the global settings that were discussed on the previous page or you can reference such a global definition as shown here. The global definition is referenced with the attribute "ref" whose value must be the same as the "id" of the channel type that is to be referenced.

You can refine the definition for the channel by specifying, which providers shall be used with this particular channel instance. In the shown case, the "soap" formatter provider is referenced.

Page 79: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 79

These two examples only showed the server-side of the configuration; however, the client side virtually the same with only minor differences. Essentially, the client side uses most of the same settings, but the client-side settings for well-known objects and activated types are located in the <client> tag and point to the server location, as shown in the following example:<configuration> <system.runtime.remoting> <application> <client url="http://localhost/RemotingHello"> <wellknown type="Hello.HelloService, Hello" url="http://localhost/RemotingHello/HelloService.soap"

/> </client> <channels> <channel type="System.Runtime.Remoting.Channels .Http.HttpChannel, System.Runtime.Remoting" /> </channels> </application> </system.runtime.remoting></configuration>

Page 80: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

80 Context and Remoting

Section 5: Putting it together

Section 5: Putting It TogetherIn this section we are going to look at some code snippets that put many of the illustrated concepts in context.

Variations of ObjectsWe will look at a couple of declarations of agile and contextful objects on the following slides. In addition, a simplistic remote “Hello” world application that is also provided with the .NET Framework SDK has been attached in the “samples” directory of this module to illustrate the channel and endpoint registration.

Context Attributes and InterceptionThen we will see a complete implementation of a simple context attribute. This sample, along with some additional code to demonstrate the synchronization and threadaffinity attributes is provided along with this module.

Page 81: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 81

Section 5: Putting it together

Variations of Objects (1/2)Agile (never marshaled)This declaration declares a simple class. By default, classes are not serializable and therefore this class cannot be passed to a remote client or server.

Agile (marshal-by-value)This declaration declares a simple class, but with the [serializable] attribute that signals that serialization for this object is permitted. Objects of this class can be passed to a remote client or server and are copied (marshal by value).

Page 82: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

82 Context and Remoting

Section 5: Putting it together

Variations of Objects (2/2)Agile (marshal-by-ref, AppDomain-bound)This declaration declares a marshal by value class, which means that the Remoting infrastructure will always generate and object reference and proxy for this object. This object is therefore AppDomain-bound.

Context-bound (marshal-by-ref)This declaration declares a context-bound class, which means that this object is always placed into a context. The object has a context attribute [CallTrace], which we are going to see implemented on the following slide.

Page 83: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 83

Section 5: Putting it together

Context Attributes & Interception (1/3)A Simple Context AttributeShown here is a simple context attribute, which shall intercept calls (with a little help from classes that we will see on the following pages) and print the IMessage dictionary contents to the console for each call.

To achieve this, we need to install the attribute and provide a context property, which is about the only task the attribute has, as you can see.

The property implementation follows on the next page.

Page 84: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

84 Context and Remoting

Section 5: Putting it together

Context Attributes & Interception (2/3)A Simple Context PropertyThe context property must implement the IContextProperty interface for the basic property “Name” and the methods “IsNewContextOK” and “Freeze”.

If you want to add custom data to your properties that can be queried by obtaining the context property through a Thread.CurrentContext.GetProperty() providing the property name returned by the “Name” property, you can do this here. This sample doesn’t provide custom data.

What it does is to install a server context sink through the “IContributeServerContextSink” interface, implementing GetServerContextSink().

Page 85: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

Context and Remoting 85

Section 5: Putting it together

Context Attributes & Interception (3/3)A Simple Message SinkThe message sink implementation looks quite busy here, but it is actually very simple. In its constructor, the sink remembers the “_nextSink” in the call chain and exposes this through the IMessageSink.NextSink property. Whenever a call passes the server context chain synchronously, the method SyncProcessMessage() is called by the Remoting infrastructure and our message sink can inspect the message or intercept and change it. In this example, we are simply dumping the context of the IMessage table to the console.

When we are done with this, we pass the call on to the next sink that will route the call on to the ultimate destination or intercept the message itself.

The implementation of AsyncProcessMessage is almost identical – the core difference is that this is invoked for asynchronous calls.

Page 86: Context and Remoting - .NET at JKUdotnet.jku.at/buch/CD-DE/DotNetDays/Webfiles/DNRK/Context... · Web view.net Developer Tools Readiness Kit Module 'Context and Remoting' by Clemens

86 Context and Remoting

Summary

SummaryAll in all, .NET Remoting is a whole new paradigm for remote invocation of code and for implementing behaviors by intercepting messages.

It is entirely open standards based by supporting W3C standards like SOAP, HTTP and XML and if that is not enough for your needs you can plug in your own extensions at virtually any level of the infrastructure.

.NET Remoting inherits and extends the COM+ context model and makes it available for your own behaviors and attributed programming ideas that allow you to separate the low-level plumbing from your business-code: just like COM+ handles the nitty-gritty details of handling Transactions form your COM+ components, you can now also add such behaviors through custom attributes.

And on top of it all, .NET Remoting is configurable at installation time and thereafter, letting Administrators configure and distribute applications for maximum efficiency. Not only that: the application configuration can be changed on application domain level for all related components (not global as in COM) and if you do side-by-side installations of the very same application on the same machine, you can have two, three or more different distribution scenarios on the same server – great for Application Service Providers, great for the Enterprise, great for the NET.