NET Framework Advanced Topics
NET Framework Advanced Topics
Prerequisites
This module assumes that you understand the fundamentals of:
Programming
Variables, statements, functions, loops, etc. Classes, inheritance, polymorphism, members, etc.
Object-oriented programming
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)
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
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:
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
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
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
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
DCOM: Object-RPC based on DCE Wire Format Marshaling through MIDL generated Proxies/Stubs
.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
WebService Providers
SQL Server .NET XML Enterprise BizTalk Servers Messaging Exchange WebStorage
.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
.NET Remoting
Context-bound objects:
"Local": Not marshaled, immediate object calls "Remote": Marshaled, calls through proxies
.NET Remoting
Building a Remote Application Example
.NET Remoting
Hosting Example
ASP.NET hosting example
Creating an IIS root that points to the app directory Adding a "Remoting.cfg" configuration file
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
Establish endpoint-to-endpoint communication Channels can listen for and send messages
Server
Dispatcher
.NET Remoting
How to Communicate: Formatters
Formatters serialize .NET objects into wire formats Used dynamically by channel architecture
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:
AppDomain-Bound Classes:
Contextful Objects
.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
Object
Dispatcher (ChannelServices)
SyncDispatchMessage()
FieldY
.NET Remoting
Context Rules and Concepts
Contexts enclose "contextful" objects
Classes derived from System.ContextBoundObject Behavior for class declared using context attributes
.NET Remoting
Context Attributes and Properties
Yes! Use existing context
System. ContextBoundObject
Attribute
ContextBound Class
Create object
Object
No! GetPropertiesForNewContext() !
Property
.NET Remoting
Remoting Services
System.Runtime.Remoting.RemotingServices class
Remoting configuration Connecting to remote object instances Exposing "well known objects"
System.Runtime.Remoting.ChannelServices
System.Runtime.Remoting.LifetimeServices
System.Runtime.Remoting.TrackingServices
.NET Remoting
Exposing Well-Known Objects
.NET's activation model is very unlike COM's
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.
.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
.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();
.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:
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 {}
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:
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