1 / 73

.NET Framework Advanced Topics

.NET Framework Advanced Topics. Name Title Department Company. 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#

kathleen
Download Presentation

.NET Framework Advanced Topics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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. ReflectionLooking 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 Events Fields Properties Constructors Parameters Methods

  9. // Test sample classpublic 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 MetaData Samples

  10. ReflectionSystem.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. ReflectionType 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. //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 } ReflectionGetMethods Example

  13. ReflectionMemberInfo • 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

  14. 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 Dynamic Creation Example

  15. ReflectionAttributes • Customattributes are the killer-app for Reflection! • Attributes enable declarative behavior • Attributes allow data augmentation

  16. ReflectionAttributes [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{ ...

  17. Types know their module; modules know their types Modules know their assembly and vice versa Code can browse and search its entire context ReflectionThe Bigger Picture Assembly Module Module Module Struct Delegate Class Constructor Class Class Method Interface Interface Method Field Interface Class

  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. ReflectionVisual Studio.NET and Reflection Toolbox Component Class Description Properties Window DefaultValue Help Localizable Designers ReadOnly Help ComponentModel Attributes

  20. ReflectionASP.NET and Reflection IIS ASP.NET runtime Assembly exists, same time stamp? File exists? 1 2 3 No? Compile 2a Run <%Page codebehind="pg"%><html><body> <asp:label/> <asp:textbox/></html></body> ASP.NET compiler Page Assembly Reflection class pg : Page{ ... }

  21. ReflectionSummary • 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 RemotingLooking 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. .NET RemotingCore Concepts: Federated Service Model Trading Partners XML .NETBuilding Block Services EDIFACT X12 Open Standards: TCP/IP XML HTTP SMTPSOAP WebServiceProviders Financial News B2B Enterprise Applications Website Sales Procurement SQL ServerXML .NETEnterprise Servers BizTalkMessaging Knowledge Management Accounting Organization ExchangeWebStorage

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

  29. Derived from COM+ context idea But:Remoting Context != COM+ Context Encloses objects with same functional context Carries shared properties that describe behavior Object Object Object .NET RemotingRemoting Context AppDomain Context Context Remoting boundary Object Object Object Object RqTx Sync Thrd

  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. Writing a well-known Web service .NET RemotingBuilding a Remote Application Example 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. ASP.NET hosting example Creating an IIS root that points to the app directory Adding a "Remoting.cfg" configuration file .NET RemotingHosting Example Remoting.cfg for the HelloService Name#HelloService WellKnownObject#HelloService.Hello#HelloService#HelloService/Hello.soap#SingleCall

  33. NET RemotingHosting Example • MyHost (a managed console app) example Name#HelloService WellKnownObject#HelloService.Hello#HelloService#HelloService/Hello.soap#SingleCallChannel#System.Runtime.Remoting#System.Runtime.Remoting.Channels.HTTP.HTTPChannel#ports=8085

  34. .NET RemotingUsing 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://localhost:80/HelloService/Hello.soap RemoteApplication#HelloService#HTTP://localhost:80/HelloService Channel#System.Runtime.Remoting#System.Runtime.Remoting.Channels.HTTP

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

  36. .NET RemotingWhat 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. 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 .NET RemotingWhere to Communicate: Channels Channel Server Client "Proxy" Dispatcher

  38. 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 .NET RemotingHow to Communicate: Formatters SOAP, Binary, Custom Decode from wire format Channel Encode into wire format

  39. .NET RemotingObjects 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 RemotingConcepts: 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 RemotingProxies • "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. .NET RemotingProxies Illustrated Channel Client Server "Proxy" IMessageSink Transparent Proxy Builds MethodA() MethodB() RealProxy Invoke() PropertyQ PropertyP FieldX SyncProcessMessage() FieldY

  43. .NET RemotingThe 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. .NET RemotingThe Dispatcher Illustrated Client Server Channel Dispatcher Actual method calls Object MethodA() Dispatcher(ChannelServices) MethodB() PropertyQ PropertyP FieldX SyncDispatchMessage() FieldY

  45. .NET RemotingContext 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. Object .NET RemotingContext Attributes and Properties Yes! Use existing context New System.ContextBoundObject No! Create new context Attribute 1 IsContextOK() ? ContextBound Class 2 Create object 3 No! GetPropertiesForNewContext() ! Property

  47. .NET RemotingRemoting 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 RemotingExposing 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 RemotingSingle 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. Channels and Objects are AppDomain-Global .NET RemotingServer 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

More Related