Effective C# 50 Specific Way to Improve Your C# Item 42, 43.

Slides:



Advertisements
Similar presentations
Lists Chapter 4 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
Advertisements

Attributes Programming in C# Attributes CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Writing Object Oriented Software with C#. C# and OOP C# is designed for the.NET Framework  The.NET Framework is Object Oriented In C#  Your access to.
.NET Attributes and Reflection “What a developer needs to know……” Dan Douglas Blog:
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Tutorial: Introduction to ASP.NET Internet Technologies and Web Application 4 th February 2010.
Pittsburgh Java User Group– Dec Java PureFaces: A JSF Framework Extension.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Using the Actions Pane, Host Controls, and Smart Tags
11 Updating a Database Table Textbook Chapter 14.
Reflection in.Net Siun-Wai Seow. Objective Explain.NET Reflection When to use it? How to use it? Topic is in the final exam.
© FPT Software Code Review with VS © FPT Software Agenda What is Code review? Run Code analysis in VS 2012 Configuring Code Analysis rule set.
Chapter 8: Writing Graphical User Interfaces
Parsley Introduction Kui Huang Oct. 13, Topics Background Dependency Injection Object Lifecycle Message Bus Sample FW Extensions.
Database Programming Dr. John Abraham. Data Sources Data source specifies the source of the data for an application. Click on Data from Menu Choose show.
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’
V 1.0 Programming III. Automatic notifications (…Changed, INofityPropertyChanged, ObservableCollection ) Data formatters Data conversions Resources.
Utilities (Part 2) Implementing static features 1.
1 Classes and Controls CE-105 Spring 2007 By: Engr. Faisal ur Rehman.
Effective C#, Chapter 1: C# Language Elements Last Updated: Fall 2011.
ABHISHEK BISWAS.NET Reflection Dynamically Create, Find and Invoke Types.
E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی.
Customizing Autodesk® Navisworks® 2013 with the .NET API
Visual C# 2012 How to Program © by Pearson Education, Inc. All Rights Reserved.
© Keren Kalif Advanced Java Topics Written by Keren Kalif, Edited by Liron Blecher.
2/26/021 Pegasus Security Architecture Author: Nag Boranna Hewlett-Packard Company.
Programming in Java CSCI-2220 Object Oriented Programming.
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.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
Attributes C#.Net Software Development Version 1.0.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
From C++ to C# Part 5. Enums Similar to C++ Similar to C++ Read up section 1.10 of Spec. Read up section 1.10 of Spec.
Special Features of C# : Delegates, Events and Attributes.
DEV394.NET Framework: Migrating To Managed Code Adam Nathan QA Lead Richard Lander Program Manager Microsoft Corporation.
Effective C# 50 Specific Way to Improve Your C# Item 22, 23.
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Building Custom Controls with ASP.NET and the Microsoft ®.NET Framework Rames Gantanant Microsoft Regional Director, Thailand
Kyung Hee University Class Diagramming Notation OOSD 담당조교 석사과정 이정환.
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.
Introduction to Inversion Of Control (IOC). IOC Definition (based on Wikipedia)  Consider the way in which an object obtains references to its dependencies.
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 7 th Lecture Pavel Ježek
Modern Programming Tools And Techniques-I
Actions and Behaviours
/* LIFE RUNS ON CODE*/ Konstantinos Pantos Microsoft MVP ASP.NET
Advanced Object-Oriented Programming Features
Advance OOP in PHP.
Delegates and Events 14: Delegates and Events
CSE 413, Autumn 2002 Programming Languages
Chapter 3: Using Methods, Classes, and Objects
Reflection SoftUni Team Technical Trainers C# OOP Advanced
Reflection SoftUni Team Technical Trainers C# OOP Advanced
Advanced .NET Programming I 7th Lecture
Lua Scripting in C#.
C# Event Processing Model
.NET and .NET Core 10. Enabling Contracts Pan Wuming 2017.
AOP in .NET Business Rules + Plumbing = Enterprise Software
Constructors, GUI’s(Using Swing) and ActionListner
How to organize and document your classes
CIS 199 Final Review.
Objects with ArrayLists as Attributes
Jim Fawcett CSE775 – Distributed Objects Spring 2006
C# COM Interoperability
Advanced .NET Programming I 8th Lecture
Presentation transcript:

Effective C# 50 Specific Way to Improve Your C# Item 42, 43

Agenda Item 42: Utilize Attributes to Simplify Reflection Item 42: Utilize Attributes to Simplify Reflection Item 43: Don't Overuse Reflection Item 43: Don't Overuse Reflection

Item 42: Utilize Attributes to Simplify Reflection Item 42: Utilize Attributes to Simplify Reflection

Example: create a add-in framework Target: Add menu items and command handlers to a running software system Target: Add menu items and command handlers to a running software system – Drop an assembly into a directory – Find out about it – Add new menu items for the new command

Code (1) // Find all the assemblies in the Add-ins directory: string AddInsDir = string.Format("{0}/Addins", Application.StartupPath); string[] assemblies = Directory.GetFiles(AddInsDir, "*.dll"); foreach (string assemblyFile in assemblies) { Assembly asm = Assembly.LoadFrom(assemblyFile); // Find and install command handlers from the assembly. }

Code (2) Use attributes to figure out which exported types contain command handlers and which methods are the command handlers Attribute class marks the types that have command handlers Use attributes to figure out which exported types contain command handlers and which methods are the command handlers Attribute class marks the types that have command handlers // Define the Command Handler Custom Attribute: [AttributeUsage(AttributeTargets.Class)] public class CommandHandlerAttribute : Attribute { public CommandHandlerAttribute() { }

Code (3) // Find all the assemblies in the Add-ins directory: string AddInsDir = string.Format("{0}/Addins", Application.StartupPath); string[] assemblies = Directory.GetFiles(AddInsDir, "*.dll"); foreach (string assemblyFile in assemblies) { Assembly asm = Assembly.LoadFrom(assemblyFile); // Find and install command handlers from the assembly. foreach(System.Type t in asm.GetExportedTypes()) { if (t.GetCustomAttributes( typeof(CommandHandlerAttribute), false).Length > 0) { // Found the command handler attribute on this type. // This type implements a command handler. // configure and add it. } // Else, not a command handler. Skip it. }

Code (4) [AttributeUsage(AttributeTargets.Property) ] public class DynamicMenuAttribute : System.Attribute { private string _menuText; private string _parentText; public DynamicMenuAttribute(string CommandText, string ParentText) { _menuText = CommandText; _parentText = ParentText; } public string MenuText { get { return _menuText; } set { _menuText = value; } } public string ParentText { get { return _parentText; } set { _parentText = value; } }

Code (5-1) // Expanded from the first code sample: // Find the types in the assembly foreach(Type t in asm.GetExportedTypes()) { if (t.GetCustomAttributes(typeof(CommandHandlerAttribute), false).Length > 0) { // Found a command handler type: ConstructorInfo ci = t.GetConstructor(new Type[0]); if (ci == null) // No default ctor continue; object obj = ci.Invoke(null); PropertyInfo [] pi = t.GetProperties();

Code (5-2) // Find the properties that are command // handlers foreach(PropertyInfo p in pi) { string menuTxt = ""; string parentTxt = ""; object [] attrs = p.GetCustomAttributes( typeof (DynamicMenuAttribute), false); foreach (Attribute at in attrs) { DynamicMenuAttribute dym = at as DynamicMenuAttribute; if (dym != null) { // This is a command handler. menuTxt = dym.MenuText; parentTxt = dym.ParentText; MethodInfo mi = p.GetGetMethod(); EventHandler h = mi.Invoke(obj, null) as EventHandler; UpdateMenu(parentTxt, menuTxt, h); }

Code (5-3) private void UpdateMenu(string parentTxt, string txt,EventHandler cmdHandler) { MenuItem menuItemDynamic = new MenuItem(); menuItemDynamic.Index = 0; menuItemDynamic.Text = txt; menuItemDynamic.Click += cmdHandler; //Find the parent menu item. foreach (MenuItem parent in mainMenu.MenuItems) { if (parent.Text == parentTxt) { parent.MenuItems.Add(menuItemDynamic); return; } // Existing parent not found: MenuItem newDropDown = new MenuItem(); newDropDown.Text = parentTxt; mainMenu.MenuItems.Add(newDropDown); newDropDown.MenuItems.Add(menuItemDynamic); }

Code (6) [ CommandHandler ] public class CmdHandler { [DynamicMenu("Test Command", "Parent Menu")] public EventHandler CmdFunc { get { if (theCmdHandler == null) theCmdHandler = new System.EventHandler(this.DynamicCommandHandler); return theCmdHandler; } private void DynamicCommandHandler( object sender, EventArgs args) { // Contents elided. }

Summary Tag each type that provided a dynamic command handler with an attribute Tag each type that provided a dynamic command handler with an attribute – Easier to find the command handlers Apply AttributeTargets (another attribute) Apply AttributeTargets (another attribute) – limit where the dynamic command attribute can be applied – simplifies the difficult task of finding the sought types in a dynamically loaded assembly Without attributes, you need to define some naming convention to find the types and the elements Without attributes, you need to define some naming convention to find the types and the elements – Naming convention is a source of human error

Item 43: Don't Overuse Reflection Item 43: Don't Overuse Reflection

Reflection Benefits Benefits – Enables you to write software that is much more dynamic – Using reflection, an application can be upgraded with new capabilities by adding new components Defects Defects – C#'s type safety  the Invoke members use parameters and return values typed as System.Object

Usage 1: default constructor // Usage:Create a new object using reflection: Type t = typeof(MyType); MyType obj = NewInstance(t) as MyType; // Example factory function, based on Reflection: object NewInstance(Type t) { // Find the default constructor: ConstructorInfo ci = t.GetConstructor(new Type[ 0 ]); if (ci != null) // Invoke default constructor, and return // the new object. return ci.Invoke(null); // If it failed, return null. return null; } public MyType NewInstance() { return new MyType(); }

Usage 2: access function member // Example usage: Dispatcher.InvokeMethod(AnObject, "MyHelperFunc"); // Dispatcher Invoke Method: public void InvokeMethod (object o, string name) { // Find the member functions with that name. MemberInfo[] myMembers = o.GetType().GetMember(name); foreach(MethodInfo m in myMembers) { // Make sure the parameter list matches: if (m.GetParameters().Length == 0) // Invoke: m.Invoke(o, null); }

Usage 3: access function member // Example usage: object field = Dispatcher.RetrieveField (AnObject, "MyField"); // elsewhere in the dispatcher class: public object RetrieveField (object o, string name) { // Find the field. FieldInfo myField = o.GetType().GetField(name); if (myField != null) return myField.GetValue(o); else return null; }

Simpler alternatives for Reflection IMyInterface foo = obj as IMyInterface; if (foo != null) { foo.DoWork(); foo.Msg = "work is done."; }

public class MyType : IMyInterface { [FactoryFunction] public static IMyInterface CreateInstance() { return new MyType(); } #region IMyInterface public string Msg { get { return _msg; } set { _msg = value; } public void DoWork() { // details elided. } #endregion }

Summary Reflection is a powerful late-binding mechanism Reflection is a powerful late-binding mechanism – The.NET Framework uses it to implement data binding Creating code using class factories, delegates, and interfaces will produce more maintainable systems. Creating code using class factories, delegates, and interfaces will produce more maintainable systems.