Presentation is loading. Please wait.

Presentation is loading. Please wait.

.NET Framework Advanced Topics Name Title Department Company.

Similar presentations


Presentation on theme: ".NET Framework Advanced Topics Name Title Department Company."— Presentation transcript:

1 .NET Framework Advanced Topics Name Title Department Company

2 Prerequisites  This module assumes that you understand the fundamentals of: Programming Variables, statements, functions, loops, etc. Object-oriented programming Classes, inheritance, polymorphism, members, etc. C#.NET Framework Class Library

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

4 Agenda  Reflection  Remoting  Serialization

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

6 Reflection Looking Back: Automation  TypeLibraries contain type information Exploration through ITypeLib/ITypeInfo  Attributes describe behavior of elements 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

7 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  Dynamic Type System 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

8 Reflection Exploring Metadata [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() ) {... } } System.Type Attributes Fields Properties Constructors Methods Events Parameters

9 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 }

10 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

11 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  Dynamic Invocation through Reflection Support for late binding: MethodInfo.Invoke() FieldInfo.SetValue()

12 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 }

13 Reflection MemberInfo  Base class for all "member" element descriptions Fields, Properties, Methods, etc.  Provides member kind, name, and declaring class MemberInfo MethodBaseParameterInfoFieldInfoEventInfoPropertyInfo MethodInfoConstructorInfo

14 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 }

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

16 Reflection Attributes [dbcolumn("Address1")] string Street; [dbcolumn("Postcode")] string ZIP; [serializable] class Person {... Map fields to database columns with FieldInfo.GetCustomAttributes() Mark class as serializable Type.GetCustomAttributes()

17 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 Struct Constructor Method Field Class Interface Class Delegate Class Interface

18 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

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

20 Reflection ASP.NET and Reflection ASP.NET compiler Reflection Page Assembly IIS ASP.NET runtime 1 2 2a 3 File exists? Assembly exists, same time stamp? No? Compile Run class pg : Page {... }

21 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

22 Agenda  Reflection .NET Remoting  Serialization

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

24 .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

25 .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

26 .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

27 WebService Providers Trading Partners.NET Building Block Services.NET Remoting Core Concepts: Federated Service Model Financial News B2B.NET Enterprise Servers SQL Server XML BizTalk Messaging Open Standards: TCP/IP XML HTTP SMTP SOAP Enterprise Applications Accounting Organization Sales Procurement Knowledge Management Website XML EDIFACT X12 Exchange WebStorage

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

29 .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 RqTxSyncThrd Remoting boundary Object AppDomain Context Object

30 .NET Remoting “Remote” vs. ”Local”  "Local" are all objects within the same AppDomain  All other objects are "Remote" Even objects in the same process!  Context-bound objects: "Local" if they share the same context "Remote" if they are in different contexts  "Local": Not marshaled, immediate object calls  "Remote": Marshaled, calls through proxies

31 .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; }

32 .NET Remoting Hosting Example Remoting.cfg for the HelloService Name#HelloService WellKnownObject#HelloService.Hello#HelloService#HelloService /Hello.soap#SingleCall  ASP.NET hosting example Creating an IIS root that points to the app directory Adding a "Remoting.cfg" configuration file

33 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

34 .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

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

36 .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  Invocation Styles Synchronous: Request with immediate response Asynchronous: Request with delayed or no response

37 Server.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 Channel "Proxy"Dispatcher

38 .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 Channel Encode into wire format Decode from wire format SOAP, Binary, Custom

39 .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

40 .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 AppDomain-Bound Classes: Reside in a single AppDomain, marshal-by-reference  Contextful Objects Bound to AppDomain and Context Marshal-by-reference outside of context

41 .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  Real Proxies Inherit System.Runtime.Remoting.RealProxy Are the communication layer for transparent proxies  Transparent Proxies Built dynamically by real proxy Exact pass-through mirror of the remote object

42 ClientServer.NET Remoting Proxies Illustrated Channel "Proxy" IMessageSink Transparent Proxy MethodA() MethodB() PropertyQ PropertyP FieldX FieldY Real Proxy Builds Invoke() SyncProcessMessage()

43 .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

44 Server Dispatcher.NET Remoting The Dispatcher Illustrated Client Channel Object MethodA() MethodB() PropertyQ PropertyP FieldX FieldY Dispatcher (ChannelServices) SyncDispatchMessage() Actual method calls

45 .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  All objects in other contexts are "remote" Conceptually similar to AppDomain boundary  Messages crossing boundary may be intercepted Chains of IMessageSinks allows hooks at any stage

46 .NET Remoting Context Attributes and Properties Property Object System. ContextBoundObject Attribute Create object IsContextOK() ? 1 No! GetPropertiesForNewContext() ! 2 3 New Yes! Use existing context No! Create new context ContextBound Class

47 .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  System.Runtime.Remoting.TrackingServices Universal hooks for tracking remoting activities

48 .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  Expose well known object for clients to connect. Bound to known channels with known name. Does not use static registration, prog-ids or class-id.  Can only expose "single call" or "singleton" objects

49 .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  RemotingServices.RegisterWellKnownType WellKnownObjectMode.SingleCall WellKnownObjectMode.Singleton

50 .NET Remoting Server Setup Example  Channels and Objects are AppDomain-Global... HTTPChannel chan = new HTTPChannel(8085); ChannelServices.RegisterChannel(chan); RemotingServices.RegisterWellKnownType( "MyAssembleName", "MyNamespace.ServerClass", "MyEndpointURI", WellKnownObjectMode.SingleCall); Registers the single-call endpoint: http://myserver:8085/MyEndpointURI Channel registration Object registration

51 o = Activator. GetObject("http://...") o.methodCall();.NET Remoting Activation Illustrated AppDomain Context Object TCP 8501 HTTP 8088 Identity Table uriAuriBuriCuriD tcp://server:8501/uriD http://server:8088/uriB RemotingServices.Connect() Activator.GetObject() Language binding o = new myClass(); o.methodCall();

52 .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); } } //... }

53 .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); //... }

54 .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); }... };

55 Agenda  Reflection  Remoting  Serialization

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

57 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

58 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 Cat Mouse Duck Dog 2 1 3 4 9 7 Horse

59 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

60 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

61 Serializaiton Deserialize Example using System; using System.IO; using System.Collections; using System.Serialization; using 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

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

63 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

64 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);

65 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  Rmoting-By-Ref 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.

66  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 Transacted Persistence Salesman Order Customer Order 2 1 3

67 Serialization Basic Serialization  A Type is NOT Serializable unless Type is specifically marked as Serializable  The Serializable Attribute  The Non-Serializable Attribute [Serializable] public class MyClass {} [Serializable] public class MyClass { [NotSerialized] int _cashSize; }

68 Serialization Customize Serialization  Implementing ISerializable interface  IDeserializationEventListener  Custom Formatters

69 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 (SerializationInfo info, StreamingContext)

70 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 fix- ups completed  Provide a reasonable opportunity for objects that need to do fix-ups based on the state of their children

71 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); }

72 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

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


Download ppt ".NET Framework Advanced Topics Name Title Department Company."

Similar presentations


Ads by Google