Sie sind auf Seite 1von 73

.

NET Framework Advanced Topics


Name Title Department Company

Prerequisites
This module assumes that you understand the fundamentals of:

Programming

Variables, statements, functions, loops, etc. Classes, inheritance, polymorphism, members, etc.

Object-oriented programming

C# .NET Framework Class Library

Learning Objective
Provide an overview on several advanced .NET Framework topics

Agenda
Reflection Remoting Serialization

Reflection
Looking back: Automation and COM type information Reflection core concepts Exploring metadata Detail information Attributes Putting it together

Reflection
Looking Back: Automation
TypeLibraries contain type information

Exploration through ITypeLib/ITypeInfo For example, directionality of parameters For example, method role (instance method, property)

Attributes describe behavior of elements


Dynamic Invocation using IDispatch Type system supports most popular simple types Dynamic types using VARIANT Arrays passed using SAFEARRAY Strings expressed as BSTR

Reflection
Core Concepts
Metadata

Single location for type information and code Code is literally contained within type information Every .NET object can be queried for its type Type metadata can be explored with Reflection Highly dynamic and language independent Types may be extended and built at run time Allows on-the-fly creation of assemblies .NET Compilers use .NET to emit .NET code

Dynamic Type System


Reflection
Exploring Metadata
System.Type Attributes Events Fields Properties Constructors Parameters Methods
[serializable] public class Person : { public event OnSaveChange onsv; public Date DOB; public string FirstName; public string LastName; public string Name { get { return FirstName + " " + LastName; } } public void Person(string First,string Last) { FirstName=First;LastName=Last; } public bool Save() { System.Type t = this.GetType(); foreach( FieldInfo f in t.GetFields() ) { ... } }

Reflection
MetaData Samples
// Test sample class public class Test { private int n; public Test(int a) { ... }

n=a;}

//Retrieve the Type object public static int Main(string[] args) { Type type1 = typeof(Test); Test t1 = new Test(0); Type type2 = t1.GetType(); Console.WriteLine(type of t1 is (0), type2); return 0 }

Reflection
System.Type
Provides access to metadata for any .NET type Returned by System.Object.GetType() Allows drilling down into all facets of a type

Category: Simple, Enum, Struct or Class Methods and Constructors, Parameters and Return Fields and Properties, Arguments and Attributes Events, Delegates, and Namespaces

Reflection
Type and Instances
Type Safety First! Type checking at run time

C#: if (o is Customer) { } VB: If TypeOf o Is Customer Then End If Support for late binding:

Dynamic Invocation through Reflection

MethodInfo.Invoke() FieldInfo.SetValue()

Reflection
GetMethods Example
//Get a list of methods supported by a class public static int Main(string[] args) { Type type1 = typeof(Test); MethodInfo[] minf = type1.GetMethods(); foreach (MethodInfo m in minf) //Print out the method name and whether it is public Console.WriteLine(Name: + m.Name + , + ((m.IsPublic) ? public ) + ((m.IsVirtual) ? virtual : ); //Get the list of paramerters ParamerterInfo[] pi = m.GetParameters(); foreach (ParameterInfo p in pi) Console.WriteLine( + p.ParameterType + + p.Name); return 0 }

Reflection
MemberInfo
Base class for all "member" element descriptions

Fields, Properties, Methods, etc.

Provides member kind, name, and declaring class MemberInfo


MethodBase ParameterInfo FieldInfo EventInfo PropertyInfo

MethodInfo

ConstructorInfo

Reflection
Dynamic Creation Example
public static int Main(string[] args) { Type type1 = typeof(Test); //Instantiate the Test Object object[] ctorParams = new object[] (1); object obj = Adtivator.CreateInstance(type1, ctorParams); //Invoke a method object[] ctorParams = new object[] (3); int res = (int)type1.InvokeMember(Amethod, BindingFlags.Default|BindingFlags.InvokeMethod, null, obj.methodParams); return 0 }

Reflection
Attributes
Custom attributes are the killer-app for Reflection! Attributes enable declarative behavior Attributes allow data augmentation

Reflection
Attributes
[dbcolumn("Address1")] string Street; [dbcolumn("Postcode")] string ZIP;

Map fields to database columns with FieldInfo.GetCustomAttributes() Mark class as serializable Type.GetCustomAttributes() [serializable] class Person { ...

Reflection
The Bigger Picture
Types know their module; modules know their types Modules know their assembly and vice versa Code can browse and search its entire context
Assembly Module Class
Constructor Method Method Field

Module Struct Class Interface Class

Module Delegate Class

Interface
Interface

Reflection
Introducing System.Reflection.Emit

Full representation of physical structure Allows building modules and assemblies at run time

Transient code only used at run time Persistent code for reuse

Create classes and types, and emit IL Used by .NET compilers to build .NET apps

Reflection
Visual Studio.NET and Reflection
Component Class Description DefaultValue Help Localizable ReadOnly Designers Properties Window Toolbox

ComponentModel Attributes

Help

Reflection
ASP.NET and Reflection
IIS ASP.NET runtime File exists? 1 No? 2a Compile
<%Page codebehind="pg"%> <html> <body> <asp:label/> <asp:textbox/> </html> </body>

2 3 Run

Assembly exists, same time stamp?

ASP.NET compiler

Reflection
class pg : Page { ... }

Page Assembly

Reflection
Summary
Reflection = System.Type + GetType() Explore type information at runtime Enables attribute-driven programming Use Emit classes to produce .NET assemblies Bottom line: Fully self-contained structural model

Agenda
Reflection .NET Remoting Serialization

.NET Remoting
Overview Remoting architecture Context and interception Serving and accessing objects Putting it together

.NET Remoting
Looking Back: Remoting in COM(+)
All Objects implement IUnknown interface

Dynamic exploration of object features Lifecycle control with reference counting

DCOM: Object-RPC based on DCE Wire Format Marshaling through MIDL generated Proxies/Stubs

Automation: Dynamic binding through IDispatch

Servers locally advertised in Registry Activation "on-demand".


Servers launched at client request Objects created through class factories

.NET Remoting
Scenarios
Web Services Anywhere

Expose Web Service endpoints from any process over any transport (pluggable channels) using any payload encoding (pluggable serialization formatters SOAP and Binary provided in the box) SOAP=HTTP+XML

.NET Remoting
Scenarios
CLR Object Remoting

Built on top of Web Services Anywhere Full Common Language Runtime type system fidelity Marshal by Value (make a copy) and Marshal by Ref (pass an ObjRef) objects between Web Services over the wire using any of the pluggable channels. Distributed Identity, Activation, Lease-based Lifetime and CallContext A TCP Channel (using sockets) with a Binary Encoding is provided

.NET Remoting
Core Concepts: Federated Service Model
XML EDIFACT X12 Trading Partners
.NET Building Block Services

Financial News B2B

WebService Providers

SQL Server .NET XML Enterprise BizTalk Servers Messaging Exchange WebStorage

Open Standards: TCP/IP XML HTTP SMTP SOAP

Enterprise Applications Website Knowledge Management Sales Procurement Accounting Organization

.NET Remoting
Application Domains
Isolated execution space for applications Independent of O/S concept of thread, process
AppDomain
Object

AppDomain
Object

AppDomain

Object

Object

Object

Process

Process

.NET Remoting
Remoting Context
Derived from COM+ context idea But: Remoting Context != COM+ Context Encloses objects with same functional context Carries shared properties that describe behavior
Object

Remoting boundary

Context
Object

Context
Object Object

Object

Object

Object

RqTx Sync

Thrd

AppDomain

Remote vs. Local


"Local" are all objects within the same AppDomain All other objects are "Remote"

.NET Remoting

Even objects in the same process!


"Local" if they share the same context "Remote" if they are in different contexts

Context-bound objects:

"Local": Not marshaled, immediate object calls "Remote": Marshaled, calls through proxies

.NET Remoting
Building a Remote Application Example

Writing a well-known Web service


using System; namespace HelloService { // Well Known WebService object public class Hello : MarshalByRefObject { // Return the name prefixed with a string public String HelloMethod(String name) { Console.WriteLine("Hello.HelloMethod : {0}" +, name); return "Hi there " + name; } } }

.NET Remoting
Hosting Example
ASP.NET hosting example

Creating an IIS root that points to the app directory Adding a "Remoting.cfg" configuration file

Remoting.cfg for the HelloService Name#HelloService WellKnownObject#HelloService.Hello#HelloService#HelloService /Hello.soap#SingleCall

NET Remoting
Hosting Example
MyHost (a managed console app) example
Name#HelloService WellKnownObject#HelloService.Hello#HelloService#HelloS ervice/Hello.soap#SingleCallChannel#System.Runtime.R emoting#System.Runtime.Remoting.Channels.HTTP.HTTPCh annel#ports=8085

.NET Remoting
Using Configuration and New Example
using System; using System.Runtime.Remoting; using HelloService; public class SimpleHello { public static void Main(String[] args) { String name = "Bill"; RemotingServices.ConfigureRemoting("MyHello.cfg"); Hello hello = new Hello(); String result = hello.HelloMethod(name); Console.WriteLine("Hello.HelloMethod returned: " + result); } } Contents of MyHello.cfg Name#MyHello Assembly#HelloService#HelloService#Hello=HTTP://local host:80/HelloService/Hello.soap RemoteApplication#HelloService#HTTP://localhost:80/He lloService Channel#System.Runtime.Remoting#System.Runtime.Remo ting.Channels.HTTP

.NET Remoting
Architecture
What: Messages Where: Channels How: Formatters Marshaling Concepts Proxies

.NET Remoting
What to Communicate: Messages
Messages are objects that implement IMessage IMessage: Simple dictionary of key/values pairs .NET Message Types:

Construction call messages, response messages Method call messages, response messages Synchronous: Request with immediate response Asynchronous: Request with delayed or no response

Invocation Styles

.NET Remoting
Where to Communicate: Channels
Channels transport messages

.NET built-in channels: TCP, HTTP, SMTP

Establish endpoint-to-endpoint communication Channels can listen for and send messages

Listener implements IChannelReceiver Sender implements: IChannelSender

Makes no assumptions about endpoint architecture


Client
"Proxy" Channel

Server
Dispatcher

.NET Remoting
How to Communicate: Formatters
Formatters serialize .NET objects into wire formats Used dynamically by channel architecture

Selection based on MIME type. Register globally: CoreChannel.RegisterChannel()

Built-in: SOAP and Binary Formatter Custom Formatters allow talking to any endpoint
SOAP, Binary, Custom Decode from wire format

Channel
Encode into wire format

.NET Remoting
Objects To Go: Marshaling
Definition: Packaging Data for Transfer For objects passed as arguments, return values Marshal-By-Value

Entire object is packaged as-is Copy is transferred to destination No link between copy and original

Marshal-By-Reference

Just a reference to an object is packaged Reference is transferred to destination "Proxy" object links destination with original

.NET Remoting
Concepts: Agile and Contextful
Agile Objects

Independent of Context Called directly from any AppDomain or Context Do not use channels Unbound Classes:

Travel between AppDomains, marshal-by-value Reside in a single AppDomain, marshal-by-reference

AppDomain-Bound Classes:

Contextful Objects

Bound to AppDomain and Context Marshal-by-reference outside of context

.NET Remoting
Proxies
"Proxy" Definition

Object that acts locally on behalf of a remote object Looks like and accepts calls as if it were "real" Forwards them to the remote object Inherit System.Runtime.Remoting.RealProxy Are the communication layer for transparent proxies Built dynamically by real proxy Exact pass-through mirror of the remote object

Real Proxies

Transparent Proxies

.NET Remoting
Proxies Illustrated
Client "Proxy" IMessageSink Channel Server

Transparent Proxy
MethodA()
MethodB() PropertyQ PropertyP Invoke() Builds

Real Proxy

FieldX
FieldY

SyncProcessMessage()

.NET Remoting
The Dispatcher
Located at the channel endpoint Receives messages Builds stack-frame from message content Invokes actual method on object Collects result and creates response message

.NET Remoting
The Dispatcher Illustrated
Client

Server Channel
Dispatcher

Actual method calls


MethodA() MethodB()

Object

Dispatcher (ChannelServices)

PropertyQ PropertyP FieldX

SyncDispatchMessage()

FieldY

.NET Remoting
Context Rules and Concepts
Contexts enclose "contextful" objects

Classes derived from System.ContextBoundObject Behavior for class declared using context attributes

Common context boundary is shared when


Objects have identical attributes or Context attributes actively agree to deviations


Conceptually similar to AppDomain boundary Chains of IMessageSinks allows hooks at any stage

All objects in other contexts are "remote"

Messages crossing boundary may be intercepted

.NET Remoting
Context Attributes and Properties
Yes! Use existing context
System. ContextBoundObject

No! Create new context 1 2 IsContextOK() ?

Attribute

ContextBound Class

Create object
Object

No! GetPropertiesForNewContext() !

Property

.NET Remoting
Remoting Services
System.Runtime.Remoting.RemotingServices class

Provides fundamental remoting infrastructure


Remoting configuration Connecting to remote object instances Exposing "well known objects"

System.Runtime.Remoting.ChannelServices

Channel registration and management

System.Runtime.Remoting.LifetimeServices

Lease-based lifecycle management for objects


Universal hooks for tracking remoting activities

System.Runtime.Remoting.TrackingServices

.NET Remoting
Exposing Well-Known Objects
.NET's activation model is very unlike COM's

.NET rather resembles CORBA model (!)


If there is no actively listening endpoint: no connection No surrogates, no registry, no location transparency EXE servers are not remotely activated

Simplifies remoting greatly Bound to known channels with known name. Does not use static registration, prog-ids or class-id.

Expose well known object for clients to connect.

Can only expose "single call" or "singleton" objects

.NET Remoting
Single Call and Singletons
"Single Call" Objects

Object instance is created for each call on channel. Implements the stateless model of the web.

"Singleton" Objects

One shared instance provided for all clients Serves as "gateway" into stateful application Can mirror COM's class factory concept Object is created at registration time
WellKnownObjectMode.SingleCall WellKnownObjectMode.Singleton

RemotingServices.RegisterWellKnownType

.NET Remoting
Server Setup Example
... HTTPChannel chan = new HTTPChannel(8085); ChannelServices.RegisterChannel(chan); RemotingServices.RegisterWellKnownType( "MyAssembleName", "MyNamespace.ServerClass", "MyEndpointURI", WellKnownObjectMode.SingleCall);

Channel registration

Object registration

Registers the single-call endpoint: http://myserver:8085/MyEndpointURI

Channels and Objects are AppDomain-Global

.NET Remoting
Activation Illustrated
tcp://server:8501/uriD http://server:8088/uriB HTTP 8088 TCP 8501

RemotingServices.Connect()

Identity Table
Activator.GetObject()

uriA

uriB

uriC

uriD

Language binding
o = Activator. GetObject("http://...") o = new myClass(); o.methodCall(); o.methodCall();

Context Object Object Object Object AppDomain

.NET Remoting
Channel Programming Examples
// Registering a Channel public class SomeClass { HTTPChannel httpChannel; public void SomeMethod() { httpChannel = new HTTPChannel(); ChannelServices.RegisterChannel(httpChannel); } // Lookup all the registered Channels } public class SomeClass { public void LookupAllChannels() { IChannel[] channels = ChannelServices.RegisteredChannels; for(int i=0;i<channels.Length;i++) { Console.WriteLine("ChannelName: " + channels[i].ChannelName); } } //. . . }

.NET Remoting
Proxy Programming Examples
Determining if an object is actually a proxy public class SomeClass { //. . . public void ProxyCheck(Object obj) { if (RemotingServices.IsTransparentProxy(obj) == true) Console.WriteLine("Is a proxy"); else Console.WriteLine("Is not a proxy"); } //. . . } Obtaining the RealProxy from a Proxy public class SomeClass { //. . . public void ObtainRealProxy (Object obj) { RealProxy realProxy = RemotingServices.GetRealProxy( obj); //. . . }

.NET Remoting
Context Programming Examples
Context Local Data Store Allocated Slots Foo foo = new Foo(); // Allocate data slot on all contexts LocalDataStoreSlot dataslot = Context.AllocateDataSlot(); // Store foo in the Context Local Store Context.SetData(dataslot, oFoo); / Retrieve foo from the Context Local Store Foo foo2 = Context.GetData(dataslot); Writing your own context attribute public class MyContextAttribute : ContextAttribute, IContributeServerContextSink { . . . public IMessageSink GetServerContextSink(IMessageSink nextSink) { return new MyContextServerSink(nextSink); } . . . };

Agenda
Reflection Remoting Serialization

Serialization
What is Serialization? System.Serialization Scenarios in Serialization Basic Serialization Custom Serialization

Serialization
What is Serialization
Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory, into a linear sequence of bytes Use the sequence of bytes in several ways:

Send it to another process Send it to the clipboard, to be browsed or used by another application Send it to another machine Send it to a file on disk

Serialization
Object Graph
What is an object graph?

An object graph is a set of objects with some set of references to each other The most obvious problem is how to represent the links between the objects in the Serialized stream
3 Dog

Cat

Cat

Mouse

Horse

Duck

Serialization
How Serialization Works
Because run-time metadata 'knows' about each object's layout in memory, and its field and property definitions, you can serialize objects automatically, without having to write code to serialize each field The serialized stream might be encoded using XML, or a compact binary representation The format is decided by the the Formatter object that you call:

Binary SOAP Custom

Serializaiton
FileStream Example
class SerializeExample{ public static void Main(String[] args) { ArrayList l = new ArrayList(); for (int x=0; x< 100; x++) { l.Add (x); } // create the object graph FileStream s = File.Create("foo.bin"); // create the filestream BinaryFormatter b = new BinaryFormatter(); // create the BinaryFormatter b.Serialize(s, l); // serialize the graph to the stream } // end main } // end class

Serializaiton
Deserialize Example
using using using using System; using System.IO; System.Collections; System.Serialization; System.Serialization.Formatters.Binary;

class DeSerialize { public static void Main(String[] args) { FileStream s = File.Open("foo.bin"); // open the filestream BinaryFormatter b = new BinaryFormatter(); // create the formatter ArrayList p = (ArrayList) b.Deserialize(s); // deserialize p.ToString(); // print out the new object graph } // end Main } // end Class DeSerialize

Serialization
Scenarios
Persistence Flat-File Persistence Remoting-By-Value Remoting-By-Reference Transacted Persistence

Serialization
Persistence
To Persist an object or collection of objects means to make them somehow survive beyond the life of the process that holds them in its memory. Conventionally, the objects are saved onto a hard disk, within a file, a storage stream, or a database. Within .NET runtime, we will use the terms Persist and Persistence in the stronger sense of saving the objects to disk, and retrieving them afterwards, under the protection of transactions

Serialization
Flat File Persistence
The runtime provides a default text formatter (e.g., generating XML stream) for serializing an entire object graph to a file
ArrayList l = new ArrayList(); for (int x=0; x< 10; x++) { l.Add (x); } Stream s = (new File ("foo.bin")).Open(FileMode.Create); BinaryFormatter b = new BinaryFormatter(); b.Serialize(s, l); s.Close(); Stream r = (new File ("foo.bin")).Open(FileMode.Open); BinaryFormatter c = new BinaryFormatter(); ArrayList p = (ArrayList) c.Deserialize(r);

Serialization
Remoting-By-Val and Remoting-By-Ref
Remoting-By-Val

Serialize a copy of a graph of objects and pass it to the remote process No guarantee that fields will be laid out in memory in the same order On the remote node, we establish a transparent proxy it behaves like the real object. However, any accesses of its fields are passed back to the original object. Serialization does not know how to create the proxy object. This is accomplished through the Remoting service using a Surrogate for that Remote-by-ref object.

Rmoting-By-Ref

Serialization
Transacted Persistence
Salesman Customer

Order

2 Order

Order

The customer order process, represented in the graph, is under transactional control Serialization is complicated process Transacted Persistence provides its own formatters and serializers, which would layer on the basic serialization service

Serialization
Basic Serialization
A Type is NOT Serializable unless Type is specifically marked as Serializable The Serializable Attribute
[Serializable] public class MyClass {}

The Non-Serializable Attribute


[Serializable] public class MyClass { [NotSerialized] int _cashSize; }

Serialization
Customize Serialization
Implementing ISerializable interface IDeserializationEventListener Custom Formatters

Serialization
ISerializable Interface
Customize the serialization process If a class implements ISerializable, that interface will always be called in preference to default serialization. The ISerializable interface is only contains one method:
void GetObjectData (SerializationInfo info, StreamingContext context); And an implied constructor that may be private. private <TypeName> (SerializationInfo info, StreamingContext)

Serialization
IDeserializationEventListener
If an object implements IDeserializationEventListener, the serialization infrastructure will call that class OnDeserialization method as soon as the entire graph has been deserialized and all fixups completed Provide a reasonable opportunity for objects that need to do fix-ups based on the state of their children

Serialization
Custom Formatter
Implementing IFormatter Interface:
public interface IFormatter: { //Properties SerializationBinder Binder { get; set; } StreamingContext Context { get; set; } ISurrogateSelector SurrogateSelector { get; set; } //Methods object Deserialize(Stream serializationStream); void Serialize(Stream serializationStream, object graph); }

Conclusion
Types' metadata can be explored with Reflection Reflection provides dynamic type system The Federated Services Model is one of the core concepts for designing .NET applications in Internet Key .NET Remoting scenarios are:

Web Services Anywhere CLR Object Remoting

Serialization is the process of converting an object, or a connected graph of objects, stored within computer memory, into a linear sequence of bytes

Resources
http://msdn.microsoft.com/net/ .NET Framework SDK

Das könnte Ihnen auch gefallen