Reflection in.Net Siun-Wai Seow. Objective Explain.NET Reflection When to use it? How to use it? Topic is in the final exam.

Slides:



Advertisements
Similar presentations
Generating Data Access Assemblies with IronRuby Rob Rowe Blog: rob-rowe.blogspot.com.
Advertisements

Lecture 5 Sept 15 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Attributes Programming in C# Attributes CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
.NET IL Obfuscation Presented by: Sarath Chandra Dorbala.
Lecture 7 Sept 16 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
C# Structs, operator overloading & attributes. Structs ~ Structures Structs are similar to classes: they represent data structures with data and functions.
Lecture 6 Feb 12 Goals: stacks Implementation of stack applications Postfix expression evaluation Convert infix to postfix.
Run-Time Storage Organization
Reflection Leveraging the Power of Metadata
.NET Attributes and Reflection “What a developer needs to know……” Dan Douglas Blog:
Reflection, Conversions, and Exceptions Tom Roeder CS fa.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Managed Code Generics Language Integrated Query Dynamic + Language Parity C# VB 11.0 Windows Runtime + Asynchrony C# VB 7.0 C# VB.
C# vs. C++ What's Different & What's New. An example C# public sometype myfn { get; set; } C++ public: sometype myfn { sometype get (); void set (sometype.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Other Types in OOP Enumerations, Structures, Generic Classes, Attributes Svetlin Nakov Technical Trainer Software University
Topic 3 The Stack ADT.
Kalpesh Padia Reflection in.Net. OVERVIEW 9/19/
C# Programming Fundamentals of Object-Oriented Programming Fundamentals of Object-Oriented Programming Introducing Microsoft.NET Introducing Microsoft.NET.
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’
© FPT Software Advanced features in C# 1. © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda.
Reflection Leveraging the Power of Metadata. Objectives Provide an introduction to.NET Reflection Explain how applications can use Reflection to explore.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Module 3: Working with Components. Overview An Introduction to Key.NET Framework Development Technologies Creating a Simple.NET Framework Component Creating.
ABHISHEK BISWAS.NET Reflection Dynamically Create, Find and Invoke Types.
Effective C# 50 Specific Way to Improve Your C# Item 42, 43.
Created By: Kevin Cherry. A library that creates a display to run on top of your game allowing you to retrieve/set values and invoke methods.
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
© Keren Kalif Advanced Java Topics Written by Keren Kalif, Edited by Liron Blecher.
1 The Stack Class Final Review Fall 2005 CS 101 Aaron Bloomfield.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Reflection.NET Support for Reflection. What is Reflection Reflection: the process by which a program can observe and modify its own structure and behavior.
Module 14: Attributes. Overview Overview of Attributes Defining Custom Attributes Retrieving Attribute Values.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Static. 2 Objectives Introduce static keyword –examine syntax –describe common uses.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Attributes C#.Net Software Development Version 1.0.
OOP Basic Topics Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Wel come To Seminar On C#.
.NET Mobile Application Development XML Web Services.
Bruno Cabral “Reflection, Code Generation and Instrumentation in the.NET platform” University of Coimbra.
Presented by Ted Higgins, SQL Server DBA An Introduction to Object – Oriented Programming.
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Delivering Excellence in Software Engineering ® EPAM Systems. All rights reserved. Reflection and Attributes.
.Net Reflection Taipan Tamsare. Overview Reflection core concepts Exploring metadata Detail information Attributes Building Types at runtime.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
CLASSES IN JAVA Primitive Types Example of a Class Allocating Objects of a Class Protecting Class data Constructors Static data and Static Methods.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 7 th Lecture Pavel Ježek
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
VBA - Excel VBA is Visual Basic for Applications
Future of C#
Reflection SoftUni Team Technical Trainers C# OOP Advanced
Advanced .NET Programming I 7th Lecture
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Indexer AKEEL AHMED.
Chapter 4 – Control Structures Part 1
CS360 Windows Programming
Chapter 3 The .NET Framework Class Library (FCL)
.NET and .NET Core 9. Towards Higher Order Pan Wuming 2017.
Conditional Statements
.NET and .NET Core 10. Enabling Contracts Pan Wuming 2017.
Domain Classes Chapter 9.
Quiz Points 1 Rules Raise your hand if you know the question
Chapter 5 Stack (part 1).
List Iterator Implementation
Advanced .NET Programming I 8th Lecture
Presentation transcript:

Reflection in.Net Siun-Wai Seow

Objective Explain.NET Reflection When to use it? How to use it? Topic is in the final exam

Overview Reflection.Net Execution Model Show how applications can use Reflection to explore type information and how they can build types at runtime Demo for each sub-topic

What is Reflection A way to acquire important information at run time about the assemblies it loads.

Uses of Reflection Viewing metadata (Attributes) Performing type discovery Late binding to methods and properties Dynamic Loading/Creating types at runtime (Reflection Emit) How is it done?

.Net Execution Model Cobol VB C++ C# CIL code (+ metadata) Loader/verifier Managed Code Uncompiled method call Execution Language compilers.NET languages JIT compiler

Metadata –Single location for type information and code –Types' metadata can be explored with Reflection –Code is literally contained within type information –Every.NET object can be queried for its type

Uses of Metadata Dynamic Type System –Allows on-the-fly creation of assemblies –.NET Compilers use.NET to emit.NET code

MetaData: Type Info at Runtime [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 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

Viewing metadata Add custom attributes to a compiled executable’s metadata Why/When to use this?

Scenario Suppose that your organization wants to keep track of bug fixes. You already keep a database of all your bugs, but you'd like to tie your bug reports to the fixes in the code. How do implement this?

[BugFixAttribute(121, "Jesse Liberty", "01/03/05")] [BugFixAttribute(107, "Jesse Liberty", "01/04/05", Comment = "Fixed off by one errors")] public class MyMath { …………………… } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] public class BugFixAttribute : System.Attribute { ………………… }

public static void Main() { ……………….. object[] attributes; attributes = inf.GetCustomAttributes(typeof(BugFixAttribute), false); // iterate through the attributes, retrieving the // properties foreach (Object attribute in attributes) { BugFixAttribute bfa = (BugFixAttribute)attribute; Console.WriteLine("\nBugID: {0}", bfa.BugID); Console.WriteLine("Programmer: {0}", bfa.Programmer); Console.WriteLine("Date: {0}", bfa.Date); Console.WriteLine("Comment: {0}", bfa.Comment); }

Demo1 demo1.doc Project Programming_Csharp

Performing type discovery This allows you to examine the types in an assembly. Project Programming_Csharp2

Reflecting on an assembly using System; using System.Reflection; public class Tester { //Reflecting on an assembly public static void Main() { // what is in the assembly Assembly a = Assembly.Load("Mscorlib.dll"); Type[] types = a.GetTypes(); foreach (Type t in types) { Console.WriteLine("Type is {0}", t); } Console.WriteLine( "{0} types found", types.Length); }

Reflecting on a Type public static void Main() { // examine a single object Type theType = Type.GetType( "System.Reflection.Assembly"); Console.WriteLine( "\nSingle Type is {0}\n", theType); }

Reflecting on the members of a type public static void Main() { // examine a single object Type theType = Type.GetType( "System.Reflection.Assembly"); Console.WriteLine( "\nSingle Type is {0}\n", theType); // get all the members MemberInfo[] mbrInfoArray = theType.GetMembers(); foreach (MemberInfo mbrInfo in mbrInfoArray) { Console.WriteLine("{0} is a {1}", mbrInfo, mbrInfo.MemberType); }

Finding type methods public static void Main() { // examine a single object Type theType = Type.GetType( "System.Reflection.Assembly"); Console.WriteLine( "\nSingle Type is {0}\n", theType); MemberInfo[] mbrInfoArray = theType.GetMethods(); foreach (MemberInfo mbrInfo in mbrInfoArray) { Console.WriteLine("{0} is a {1}", mbrInfo, mbrInfo.MemberType); }

Late binding to methods and properties Performing late binding by dynamically instantiating and invoking methods on types. Done in homework 3 (application domain/stack walk/permission).

Creating types at runtime The ultimate use of reflection is to create new objects/types at runtime and then to use those objects to perform tasks. You might do this when a new class, created at runtime, will run significantly faster than more generic code created at compile time.

Static Method Wrote before runtime (before compilation) public int DoSumLooping(int initialVal) { int result = 0; for(int i = 1;i <=initialVal;i++) { result += i; } return result; } Summation of N : …..+N

Dynamic Method created at run time // Push zero onto the stack. For each 'i' // less than 'theValue', // push 'i' onto the stack as a constant // add the two values at the top of the stack. // The sum is left on the stack. generator.Emit(OpCodes.Ldc_I4, 0); for (int i = 1; i <= theValue;i++) { generator.Emit(OpCodes.Ldc_I4, i); generator.Emit(OpCodes.Add); }

Demo Programming_CSharp3

Problems Reflection APIs are known to cause problem on obfuscated assemblies.

References chapter/ch18.htmlhttp:// chapter/ch18.html online.net/Introduction_to_CLI%E2%80%9 4Execution_and_Deployment_Modelshttp://en.csharp- online.net/Introduction_to_CLI%E2%80%9 4Execution_and_Deployment_Models potsdam.de/teaching/componentVl05/slide s/Net_VL2_02_Reflection.pdfhttp:// potsdam.de/teaching/componentVl05/slide s/Net_VL2_02_Reflection.pdf

Reference medialab.di.unipi.it/web/AP/Reflection.ppt Programming Microsoft.NET by Jeff Prosise

Questions

Thank you