Understanding Reflection  Tamir Khason Technology Consultor ¹ mPrest Systems http://blogs.microsoft.co.il/blogs/tamir   Session Code: DVP307 ¹ con·sul·tor  (kən sult ′ ər) - one of a group of priests appointed to advise and assist a bishop
CLR – compilation and execution Execution Compilation Source code Language compiler JIT compiler Before installation or the first time each method is called MSIL Metadata Code Native code
Reflection overview All types in the CLR are self-describing  CLR provides a reader and writer for type definitions System.Reflection & System.Reflection.emit You can ‘read’ programs  You can map between type systems  You can interrogate objects and types inside a running program
What is “Reflection”? “ Reflection provides objects that encapsulate assemblies, modules, and types. ”   (MSDN) “ You can use reflection to dynamically create an instance of a type... ”   (MSDN) “ You can then invoke the type's methods or access its fields and properties. ”   (MSDN) “ Reflection.Emit namespace contains classes that allow a compiler or tool to emit metadata and Microsoft intermediate language (MSIL) ”   (MSDN)
Where is “Reflection”? System.Reflection namespace contains most Reflection classes. System.Type is Reflection class used to  access type metadata. … more…
How to “Reflection”? Viewing metadata  Performing type discovery  Late binding to methods and properties (Dynamic Invocation) Creating types at runtime (Reflection Emit)
How to… perform type discovery You can use reflection to explore and examine the contents of an assembly programmatically   You can find  methods, fields, properties, and events associated with a type signatures of each of the type's methods; interfaces supported by the type;  type's base class. …
What are you? Value, Interface or Class? IsValueType, IsInterface, IsClass Public, Private or Sealed ? IsNotPublic, IsSealed Abstract or Implementation? IsAbstract
What you have? Finding and Exploring Members MemberInfo: GetMembers(), FindMembers() Exploring Fields and Properties FieldInfo: GetFields(), PropertyInfo: GetProperties() Exploring Constructors, Methods and Events GetConstructors(), GetMethods(), GetEvents() Exploring attributes, determining implemented interfaces, enumerating nested types, … Everything you may ever want to know
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
MethodInfo vs. ConstructorInfo MethodInfo Return type and attributes List of all parameters as ParameterInfo array Detail implementation information through flag-field Can invoke method through Reflection ConstructorInfo Same features as MethodInfo, just for constructors
FieldInfo vs. PropertyInfo FieldInfo Field data type and attributes Static or Instance field, protection level Can set value through reflection  Provides low-level, direct access with SetValueDirect() PropertyInfo Property type and attributes Test methods for readability, writeability "get" and "set" MethodInfo Indexer ParameterInfo Can invoke "set" and "get" through Reflection
We can clone it… Type kidType = oldKid.GetType(); Kid newKid = new Kid();   foreach (var m in kidType.GetProperties()) { m.SetValue(newKid ,    m.GetValue(oldKid, null), null); } Unknown object GetType().GetMembers() For Each Member FieldInfo.Copy old value to new Object
Clone optimization Kid CloneKid(Kid) { newKid.Height = oldKid.Height   newKid.Weight = oldKid.Weight } Unknown object GetType().GetMembers() For Each Member Create Code that copies members Save as Method for later Invocation
Clone optimized Unknown object Has custom method? Execute Yes Copy Members No
What is… attributes An  attribute  is an object that represents data you want to associate with an element in your program.  Two Kinds of Attributes: Intrinsic : Supplied as part of the Common Language Runtime (CLR) Custom : Attributes you create for your own purposes
Code generation Using Dynamic Invoke Create and compile source code in runtime Persistent in disk Invoke Compiler to generate IL Using Reflection Emit Emit IL code directly Temporarily stored in memory Better performance Kid CloneKid(Kid) { newKid.Height = oldKid.Height   newKid.Weight = oldKid.Weight }
 
CodeDOM CodeEntryPointMethod  start = new CodeEntryPointMethod();  CodeMethodInvokeExpression  cs1 =  new CodeMethodInvokeExpression(  new  CodeTypeReferenceExpression ("System.Console"),  "WriteLine",  new  CodePrimitiveExpression ("Hello World!") );  start.Statements.Add(cs1);  public static void Main() { System.Console.WriteLine(“Hello World!”); }
CodeDOM CodeArgumentReferenceExpression CodeArrayCreateExpression CodeArrayIndexerExpression CodeAssignStatement CodeAttachEventStatement CodeAttributeArgument CodeAttributeArgumentCollection CodeAttributeDeclaration CodeAttributeDeclarationCollection CodeBaseReferenceExpression CodeBinaryOperatorExpression CodeCastExpression CodeCatchClause CodeCatchClauseCollection CodeComment CodeCommentStatement CodeCommentStatementCollection CodeCompileUnit CodeConditionStatement CodeConstructor CodeDelegateCreateExpression CodeExpressionCollection CodeExpressionStatement CodeFieldReferenceExpression CodeGotoStatement CodeIndexerExpression CodeIterationStatement CodeLabeledStatement CodeLinePragma CodeMemberEvent CodeMemberField CodeMemberMethod CodeMemberProperty CodeMethodInvokeExpression CodeMethodReferenceExpression CodeMethodReturnStatement CodeNamespace CodeNamespaceCollection CodeNamespaceImport CodeNamesapceImportCollection CodeObject CodeObjectCreateExpression
CodeDOM – even more CodeCompiler CodeDomProvider CodeGenerator CodeGeneratorOptions CodeParser CompilerError CompilerErrorCollection CompilerParameters CompilerResults Executor IndentedTextWriter TempFileCollection ICodeCompiler ICodeGenerator ICodeParser CodeBinaryOperatorType FieldDirection MemberAttributes  CodePropertySetValueReferenceExpression CodeRemoveEventStatement CodeSnippetCompileUnit CodeSnippetExpression CodeTypeMemberCollection CodeTypeOfExpression CodeTypeReference CodeTypeReferenceCollection CodeTypeReferenceExpression CodeVariableDeclarationStatement CodeVariableReferenceExpression CodeCatchClause CodeCatchClauseCollection CodeComment CodeCommentStatement CodeCommentStatementCollection CodeCompileUnit CodeConditionStatement CodeConstructor CodeDelegateCreateExpression CodeDelegateInvokeExpression CodeDirectionExpression CodeEntryPointMethod CodeEventReferenceExpression CodeExpression CodeSnippetStatement CodeSnippetTypeMember CodeStatementCollection CodeThisReferenceExpression CodeThrowExceptionStatement CodeTryCatchFinallyStatement CodeTypeConstructor CodeTypeDeclaration CodeTypeDeclarationCollection CodeTypeDelegate CodeTypeMember
Dynamic Invocation with Brut force compilation Dynamic Invocation with Brut force CodeDOM Dynamic Invocation with CodeDOM
CodeDOM – Bottom line A lot of goodies, but very complicated yet limited … also you can write your own CodeDomProvider … however, if you can generate the CodeDom, it does not mean you can generate code with it
 
IL introduction IL – The language for execution Independent of CPU and platform Created by Microsoft, external commercial and academic language/compiler writers Stack based virtual machine: 5 + 10 - 3    IL_0001:  ldc.i4  5 IL_0002:  ldc.i4  10  IL_0003:  add IL_0004:  ldc.i4 3 IL_0005:  sub Evaluation Stack 0000 005 0000 0010 0000 0015 0000 0003 0000 0012
IL introduction IL storage opcodes Locals of a method Fields in a class string str = “Hello, World!” IL_0001: ldstr  “Hello, World!” IL_0002:  stloc str IL_0003:  ldloc str  Foo.f = “Hello, World!” IL_0001:  ldstr  “Hello, World!” IL_0002:  stfld string  Foo::f IL_0003:  ldfld string  Foo::f
IL introduction IL control flow opcodes if (b) { ... } else { ... }  IL_0001:  ldloc b IL_0002:  ldc.i4.1 IL_0003:  ceq IL_0004:  brfalse  IL_00020 // if true statements IL_0010:  ... IL_0011: br  IL_00025 // else statements IL_0020:  ... // rest of method IL_0025: ...
Reflection.Emit Assemblybuilder ConstructorBuilder CustomAttributeBuilder EnumBuilder EventBuilder FieldBuilder ILGenerator Label LocalBuilder MethodBuilder ModuleBuilder ParameterBuilder PropertyBuilder TypeBuilder
Code Emitting public  class MyClass { public static void Main()  { string str  = “Hello World!”; Console.WriteLine (str); } } AssemblyBuilder ModuleBuilder TypeBuilder MethodBuilder LocalBuilder ILGenerator OPCodes
Lightweight Code Generation DynamicMethod Kid CloneKid(Kid) { newKid.Height = oldKid.Height   newKid.Weight = oldKid.Weight } DynamicMethod ILGenerator OPCodes
Dynamic Invocation with Emit
 
HackMe All types in the CLR are self-describing  DynamicMethod dm =… dm.GetMethodBody(). GetILAsByteArray (); MethodInfo mi = .. mi.GetMethodBody(). GetILAsByteArray ();
What's new in .NET 3.5? Lambdas .Compile() for code generation Expression Trees Parse and understand
From delegate to Lambda Delegate void SomeDelegate(EventsArgs e); Object.SomeEvent += new SomeDelegate(SomeMethod); Delegate Object.SomeEvent += delegate(EventArgs e)    { //work here } Anonymous delegate  Object.SomeEvent += (e) => { //work here }; Lambda
Expression Tree Use Expression<T> Parse Lambdas at runtime Compile at runtime (Expression.Compile()) Use the Expression Tree Debug Visualizer http://code.msdn.microsoft.com/csharpsamples
Parse and visualize trees Compile Lambdas
Related Content Today 14:45 – Team Foundation Server – Brian Randell – Session room 06 16:45 – Data Protection with CryptoAPI – Rafael Lukawiecki – Session room 06 or Optimizing your WPF application by me – Session room 09 19:30 – BEACH PARTY! Tomorrow 9:00 – Best Practicies for the VB.NET and C# – Lisa Feigenbaum – Session room 07 10:15 – Making your test lab obsolete – Brian Randell – Session room 07
Resources www.microsoft.com/teched   Tech·Talks Tech·Ed Bloggers Live Simulcasts Virtual Labs http://microsoft.com/technet   Evaluation licenses, pre-released products, and MORE! http://microsoft.com/msdn   Developer’s Kit, Licenses,  and MORE!
Please complete an evaluation
 
© 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation.  Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation.  MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Understanding Reflection

  • 1.
  • 2.
    Understanding Reflection Tamir Khason Technology Consultor ¹ mPrest Systems http://blogs.microsoft.co.il/blogs/tamir Session Code: DVP307 ¹ con·sul·tor (kən sult ′ ər) - one of a group of priests appointed to advise and assist a bishop
  • 3.
    CLR – compilationand execution Execution Compilation Source code Language compiler JIT compiler Before installation or the first time each method is called MSIL Metadata Code Native code
  • 4.
    Reflection overview Alltypes in the CLR are self-describing CLR provides a reader and writer for type definitions System.Reflection & System.Reflection.emit You can ‘read’ programs You can map between type systems You can interrogate objects and types inside a running program
  • 5.
    What is “Reflection”?“ Reflection provides objects that encapsulate assemblies, modules, and types. ” (MSDN) “ You can use reflection to dynamically create an instance of a type... ” (MSDN) “ You can then invoke the type's methods or access its fields and properties. ” (MSDN) “ Reflection.Emit namespace contains classes that allow a compiler or tool to emit metadata and Microsoft intermediate language (MSIL) ” (MSDN)
  • 6.
    Where is “Reflection”?System.Reflection namespace contains most Reflection classes. System.Type is Reflection class used to access type metadata. … more…
  • 7.
    How to “Reflection”?Viewing metadata Performing type discovery Late binding to methods and properties (Dynamic Invocation) Creating types at runtime (Reflection Emit)
  • 8.
    How to… performtype discovery You can use reflection to explore and examine the contents of an assembly programmatically You can find methods, fields, properties, and events associated with a type signatures of each of the type's methods; interfaces supported by the type; type's base class. …
  • 9.
    What are you?Value, Interface or Class? IsValueType, IsInterface, IsClass Public, Private or Sealed ? IsNotPublic, IsSealed Abstract or Implementation? IsAbstract
  • 10.
    What you have?Finding and Exploring Members MemberInfo: GetMembers(), FindMembers() Exploring Fields and Properties FieldInfo: GetFields(), PropertyInfo: GetProperties() Exploring Constructors, Methods and Events GetConstructors(), GetMethods(), GetEvents() Exploring attributes, determining implemented interfaces, enumerating nested types, … Everything you may ever want to know
  • 11.
    MemberInfo Base classfor all &quot;member&quot; element descriptions Fields, Properties, Methods, etc. Provides member kind, name and declaring class MemberInfo MethodBase ParameterInfo FieldInfo EventInfo PropertyInfo MethodInfo ConstructorInfo
  • 12.
    MethodInfo vs. ConstructorInfoMethodInfo Return type and attributes List of all parameters as ParameterInfo array Detail implementation information through flag-field Can invoke method through Reflection ConstructorInfo Same features as MethodInfo, just for constructors
  • 13.
    FieldInfo vs. PropertyInfoFieldInfo Field data type and attributes Static or Instance field, protection level Can set value through reflection Provides low-level, direct access with SetValueDirect() PropertyInfo Property type and attributes Test methods for readability, writeability &quot;get&quot; and &quot;set&quot; MethodInfo Indexer ParameterInfo Can invoke &quot;set&quot; and &quot;get&quot; through Reflection
  • 14.
    We can cloneit… Type kidType = oldKid.GetType(); Kid newKid = new Kid(); foreach (var m in kidType.GetProperties()) { m.SetValue(newKid , m.GetValue(oldKid, null), null); } Unknown object GetType().GetMembers() For Each Member FieldInfo.Copy old value to new Object
  • 15.
    Clone optimization KidCloneKid(Kid) { newKid.Height = oldKid.Height newKid.Weight = oldKid.Weight } Unknown object GetType().GetMembers() For Each Member Create Code that copies members Save as Method for later Invocation
  • 16.
    Clone optimized Unknownobject Has custom method? Execute Yes Copy Members No
  • 17.
    What is… attributesAn attribute is an object that represents data you want to associate with an element in your program. Two Kinds of Attributes: Intrinsic : Supplied as part of the Common Language Runtime (CLR) Custom : Attributes you create for your own purposes
  • 18.
    Code generation UsingDynamic Invoke Create and compile source code in runtime Persistent in disk Invoke Compiler to generate IL Using Reflection Emit Emit IL code directly Temporarily stored in memory Better performance Kid CloneKid(Kid) { newKid.Height = oldKid.Height newKid.Weight = oldKid.Weight }
  • 19.
  • 20.
    CodeDOM CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression (&quot;System.Console&quot;), &quot;WriteLine&quot;, new CodePrimitiveExpression (&quot;Hello World!&quot;) ); start.Statements.Add(cs1); public static void Main() { System.Console.WriteLine(“Hello World!”); }
  • 21.
    CodeDOM CodeArgumentReferenceExpression CodeArrayCreateExpressionCodeArrayIndexerExpression CodeAssignStatement CodeAttachEventStatement CodeAttributeArgument CodeAttributeArgumentCollection CodeAttributeDeclaration CodeAttributeDeclarationCollection CodeBaseReferenceExpression CodeBinaryOperatorExpression CodeCastExpression CodeCatchClause CodeCatchClauseCollection CodeComment CodeCommentStatement CodeCommentStatementCollection CodeCompileUnit CodeConditionStatement CodeConstructor CodeDelegateCreateExpression CodeExpressionCollection CodeExpressionStatement CodeFieldReferenceExpression CodeGotoStatement CodeIndexerExpression CodeIterationStatement CodeLabeledStatement CodeLinePragma CodeMemberEvent CodeMemberField CodeMemberMethod CodeMemberProperty CodeMethodInvokeExpression CodeMethodReferenceExpression CodeMethodReturnStatement CodeNamespace CodeNamespaceCollection CodeNamespaceImport CodeNamesapceImportCollection CodeObject CodeObjectCreateExpression
  • 22.
    CodeDOM – evenmore CodeCompiler CodeDomProvider CodeGenerator CodeGeneratorOptions CodeParser CompilerError CompilerErrorCollection CompilerParameters CompilerResults Executor IndentedTextWriter TempFileCollection ICodeCompiler ICodeGenerator ICodeParser CodeBinaryOperatorType FieldDirection MemberAttributes CodePropertySetValueReferenceExpression CodeRemoveEventStatement CodeSnippetCompileUnit CodeSnippetExpression CodeTypeMemberCollection CodeTypeOfExpression CodeTypeReference CodeTypeReferenceCollection CodeTypeReferenceExpression CodeVariableDeclarationStatement CodeVariableReferenceExpression CodeCatchClause CodeCatchClauseCollection CodeComment CodeCommentStatement CodeCommentStatementCollection CodeCompileUnit CodeConditionStatement CodeConstructor CodeDelegateCreateExpression CodeDelegateInvokeExpression CodeDirectionExpression CodeEntryPointMethod CodeEventReferenceExpression CodeExpression CodeSnippetStatement CodeSnippetTypeMember CodeStatementCollection CodeThisReferenceExpression CodeThrowExceptionStatement CodeTryCatchFinallyStatement CodeTypeConstructor CodeTypeDeclaration CodeTypeDeclarationCollection CodeTypeDelegate CodeTypeMember
  • 23.
    Dynamic Invocation withBrut force compilation Dynamic Invocation with Brut force CodeDOM Dynamic Invocation with CodeDOM
  • 24.
    CodeDOM – Bottomline A lot of goodies, but very complicated yet limited … also you can write your own CodeDomProvider … however, if you can generate the CodeDom, it does not mean you can generate code with it
  • 25.
  • 26.
    IL introduction IL– The language for execution Independent of CPU and platform Created by Microsoft, external commercial and academic language/compiler writers Stack based virtual machine: 5 + 10 - 3 IL_0001: ldc.i4 5 IL_0002: ldc.i4 10 IL_0003: add IL_0004: ldc.i4 3 IL_0005: sub Evaluation Stack 0000 005 0000 0010 0000 0015 0000 0003 0000 0012
  • 27.
    IL introduction ILstorage opcodes Locals of a method Fields in a class string str = “Hello, World!” IL_0001: ldstr “Hello, World!” IL_0002: stloc str IL_0003: ldloc str Foo.f = “Hello, World!” IL_0001: ldstr “Hello, World!” IL_0002: stfld string Foo::f IL_0003: ldfld string Foo::f
  • 28.
    IL introduction ILcontrol flow opcodes if (b) { ... } else { ... } IL_0001: ldloc b IL_0002: ldc.i4.1 IL_0003: ceq IL_0004: brfalse IL_00020 // if true statements IL_0010: ... IL_0011: br IL_00025 // else statements IL_0020: ... // rest of method IL_0025: ...
  • 29.
    Reflection.Emit Assemblybuilder ConstructorBuilderCustomAttributeBuilder EnumBuilder EventBuilder FieldBuilder ILGenerator Label LocalBuilder MethodBuilder ModuleBuilder ParameterBuilder PropertyBuilder TypeBuilder
  • 30.
    Code Emitting public class MyClass { public static void Main() { string str = “Hello World!”; Console.WriteLine (str); } } AssemblyBuilder ModuleBuilder TypeBuilder MethodBuilder LocalBuilder ILGenerator OPCodes
  • 31.
    Lightweight Code GenerationDynamicMethod Kid CloneKid(Kid) { newKid.Height = oldKid.Height newKid.Weight = oldKid.Weight } DynamicMethod ILGenerator OPCodes
  • 32.
  • 33.
  • 34.
    HackMe All typesin the CLR are self-describing DynamicMethod dm =… dm.GetMethodBody(). GetILAsByteArray (); MethodInfo mi = .. mi.GetMethodBody(). GetILAsByteArray ();
  • 35.
    What's new in.NET 3.5? Lambdas .Compile() for code generation Expression Trees Parse and understand
  • 36.
    From delegate toLambda Delegate void SomeDelegate(EventsArgs e); Object.SomeEvent += new SomeDelegate(SomeMethod); Delegate Object.SomeEvent += delegate(EventArgs e) { //work here } Anonymous delegate Object.SomeEvent += (e) => { //work here }; Lambda
  • 37.
    Expression Tree UseExpression<T> Parse Lambdas at runtime Compile at runtime (Expression.Compile()) Use the Expression Tree Debug Visualizer http://code.msdn.microsoft.com/csharpsamples
  • 38.
    Parse and visualizetrees Compile Lambdas
  • 39.
    Related Content Today14:45 – Team Foundation Server – Brian Randell – Session room 06 16:45 – Data Protection with CryptoAPI – Rafael Lukawiecki – Session room 06 or Optimizing your WPF application by me – Session room 09 19:30 – BEACH PARTY! Tomorrow 9:00 – Best Practicies for the VB.NET and C# – Lisa Feigenbaum – Session room 07 10:15 – Making your test lab obsolete – Brian Randell – Session room 07
  • 40.
    Resources www.microsoft.com/teched Tech·Talks Tech·Ed Bloggers Live Simulcasts Virtual Labs http://microsoft.com/technet Evaluation licenses, pre-released products, and MORE! http://microsoft.com/msdn Developer’s Kit, Licenses, and MORE!
  • 41.
  • 42.
  • 43.
    © 2008 MicrosoftCorporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Editor's Notes

  • #2 06/07/09 17:53 © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.