Showing posts with label Reflection. Show all posts
Showing posts with label Reflection. Show all posts

Tuesday, May 10, 2016

TypeScript - Reflection ie create object from its class name in string

Reflection

Reflection is a mechanism to talk to the metadata of classes or other programming constructs in programming language and do things without coding it. For example to listing out all the methods of a class where the class name is in string, invoking a method name by accepting the method name from user. Also creating an object without new keyword etc... Refer what says wiki on reflection for more details.

Creating object by its name not using new

In this post, we are going to see how we can create an object by knowing its name in a string variable. Since the value/name of class can be changed runtime, we cannot use new keyword. If we want we can use a switch construct based on the value in the string and have new in the case blocks. But that will work only when all the possible class names are known in advance. In a plugin model where anyone can add implemented classes at a later point, this switch mechanism will not work.

This is the class, whose object we are going to create.
module Company.App.Module {
    export class Greeter {
        constructor() {
        }
        greet(message: string) {
            return "Hello, " + message;
        }
    }
}
Below is the con
import Greeter = Company.App.Module.Greeter;
var obj: any = ObjectFactory.create("Company.App.Module.Greeter");
var greeter: Greeter = <Greeter>obj;
alert(greeter.greet("Joy"));
Look at the argument to ObjectFactory.create(). Its a string. So the question is how do we write the create() function.

Forbidden,dangerous JavaScript method eval()

For some reason, there are some constructs in programming language which are taught to be dangerous and should not use. eval() is one among that. But in this scenario, we are going to use eval() to do our job easier.
class ObjectFactory {
    static create(className: string) {
        var obj;
        eval("obj=new " + className + "()");
        return obj;
    }
}
To be frank eval() is not a feature of TypeScript. Its there in JavaScript for long and TypeScript cannot take the credit for reflection. Since its demonstrated in TypeScript, the title of this post contains TypeScript.

Security warning

If the className is accepted from user, there are chances for attack. If they enter a string like below and we use that string as is to call this method, it will just execute malicious code.

String(); (function malicionsFunction(){//malicious code})();new String

Tuesday, March 18, 2014

.Net Assembly versioning in Plug-in framework

As everybody knows assembly versioning in .net is a good concept. It helps us to deliver upgraded versions very easily without affecting behaviour of old versions ie easier to maintain backward compatibility. It also helps us to sign our assemblies with strong name which means our delivered dlls are unique.

In normal cases, the assembly version contains 4 numbers separated by period "." . Those denote Major version,Minor version, Build number and Revision number respectively. When to change or increment the assembly version is a tough decision especially when it comes to applications which uses reflection extensively. As best practices some people changes the assembly version for the shipping builds only. Anyhow when we change the assembly version we need to make sure that all assemblies including dependent assemblies are loading correctly as those are signed and needs to be in same version.

In my current project we are changing the assembly version once in a year as we are using reflection in its maximum. Recently we had to deal with a versioning issue related to a plug-in architecture, we introduced last year. For simplicity I can explain the plug-in architecture using simple drawing application framework which uses IShape and its implemented classes.

Problem

The aim is to have a plug-in architecture in place where there will be a framework which will be always latest. There will be an interface IShape with a method Draw().The framework creates the object of IShape implemented classes based on configuration using reflection and calls its Draw() method. We released it in 2013 and the structure was as follows
  • Core.dll {Version:1.0.0.0}
    • Contains IShape interface
  • Framework.exe{1.0.0.0}
    • The controller class which creates the object of IShape using reflection and call Draw()
  • Impl10.dll{Verion:1.0.0.0}
    • Contains Circle class which implements IShape.Draw() method to draw circle shape.
In 2014 we are not supposed to release Impl10.dll as there is no change. But the Framework.exe might have feature improvements and it's version needs to be incremented. Similarly the version of Core.dll needs to be incremented as its always expected to be latest.

The problem starts from here. If we deliver the new version of Core and Framework with incremented assembly version 2.0.0.0 for Core.dll and Framework.dll, the Impl10.dll will not get loaded as its in old version.

Dlls present after new release.
  • Core.dll {Version:2.0.0.0}
    • Contains IShape interface
  • Framework.exe{2.0.0.0}
    • The controller class which creates the object of IShape using reflection and call Draw()
  • Impl10.dll{Verion:1.0.0.0}
    • Contains Circle class which implements IShape.Draw() method to draw circle shape
  • Impl20.dll{Version 2.0.0.0}
    • Contains Rectangle class which implements IShape.Draw() method to draw rectangle shape

Possible solutions

  1. Assembly binding redirection 
    Using this technique we are forcing the .net runtime to use latest version of Core.dll even for Impl10.dll which is pointing towards previous version of Core.dll .But needs to maintain list of all old versions.
  2. Manual Assembly resolution
    This technique loads the assembly by writing the assembly loading code in the AppDomain.AssemblyResolve event.
  3. Constant version for Core.dll
    Simple one. Don't change the version of Core.dll even there are changes for new features. So that always the classes are implementing same interface. The assembly version of implementing classes can be incremented.
We opted the 3rd solution as its simple. Attached a sample which explains the plug-in scenario.


Things to remember

When we select any of these options we need to make sure below points
  1. Never remove any method or change the method signature in interface methods. If we do so .net runtime verification will fail and it will throw method not found exceptions if we try to load old assemblies.
  2. If we want to add more methods to the interface, we need to create new interface inheriting from IShape and have new methods there. When creating objects in framework.exe make sure we cast to respective interfaces to invoke operations. Since deployed framework.exe will be always latest, it can be done easily.

Tuesday, October 4, 2011

ControlledSingleton pattern

Some months back I had written a post to describe how to get the name of the calling method programmatically. ie to get the call stack entry just below the current method. That post was born in relation with one of our requirement to create controlled singleton pattern which I described in it’s previous post.

Why we need ControlledSingleton pattern?

This is needed when you plan to make a class Singleton after so much code is written using that class and you have technical and managerial limitations to change all the existing code.The normal singleton pattern with private constructor will not be applicable here since it needs full inspection in your code base for compilation as well as usage of reflection. You can easily fix the compilation issues but reflection cannot be caught that much easily.Also if you are serializing the Singleton class to persist its state or pass through WCF, certainly you cannot make it as singleton otherwise the serializer will fail.

If your company management in case of product development or you client in case of projects are really adamant on quality and are ready to give you enough time to refactor code,just go with that and implement the real singleton. Also if you are developing a new project you can decide on which class to be singleton and make that as normal singleton class.Unfortunately I didn’t had this luxury which lead me to the ControlledSingleton pattern.

What is ControlledSingleton

According to me it’s same as normal singleton but giving permission to some components to create the object of singleton class.The components may be some classes,some methods or some assemblies.That depends on the requirements of the developer who implements the pattern. I am not sure whether there are any other pattern in different name which is same as this.

Implementing ControlledSingleton

This depends upon the environment / programming language you are using.Since I am a .net developer I can see 2 methods to implement the pattern

  1. Validating the caller using call stack
    This can be achieved by inspecting the current call stack and checking whether the caller has the permission to create the object.Please refer my previous posts to get detailed idea.
    http://joymonscode.blogspot.com/2011/02/how-to-get-calling-method-name.html

    Characteristics:-The draw back of this method is we cannot ensure singleton at compile time.Each and every time before inspecting the call stack will cause performance impacts. This is applicable only in managed languages where we have the method name at runtime.
  2. InternalsVisibleTo attribute
    The InternalsVisibleToAttribute defined on assembly tells the system that there are some more assemblies which can see it’s internal members. That means if we make a class Singleton using internal constructor the assemblies which are specified in the InternalsVisibleTo attribute can create the object of the singleton class.

    Characteristics:-The advantage of this is we can ensure at the compile time itself. This idea can also extend to unmanaged languages too since it works at compile time.

About attached sample

The sample contains 3 projects. “ControlledSingleton” project contains the singleton class PersonsContext. The class is made as Singleton using internal constructor which means any class inside that project can create the instance of the singleton class. The InternalsVisibleTo attribute is pointing to the second assembly named “SingletonPermitted”.ie it can create object of PersonContext.The “ControlledSingleton_Demo” is a console application which don’t have permission to create the object of singleton class. It cannot even try to use reflection to create the object.

Download the sample from here.

Recommended changes

The above methods allows so many objects of the singleton class in the system at same time.If you don’t have serialization on your singleton candidate you can think about a ReInitializeSingleton method which is internal to modify/replace the single ton object.

internal ReinitializeSingleton(params)

Sunday, February 6, 2011

How to get the calling method name

This is continuation to my last post on finding the name of the method inside the same method. As I told in that post,my original requirement was to find out who is calling one method and handle the call appropriately.After spending some more time ,I was able to find a way.Its nothing but getting the call stack programmatically.Here is the code.

Console.WriteLine(new StackFrame(1).GetMethod().Name);
Console.WriteLine(new StackFrame(1).GetMethod().DeclaringType.FullName);



Now its possible to check the caller method and do operations based on the caller.ie block callers ,return different results etc…



Is there any sense in doing like this where anybody can create an assembly with required name and bypass this



Normally speaking there is no sense.But of course YES based on some scenarios especially in our project.We have a class present for years used to keep the context which we would like to make SingleTon now, to avoid memory leaks and improve performance. There is no chance that we can put a private constructor or rewrite the entire code due to serialization of the context and practicability.If we start rewriting the code we cannot deliver on time.So the last option is to find out the classes which really needs to instantiate the context class and give permission to them only.For other classes expose a static property which returns the current context object.



But if we think from performance aspects, its time consuming as each and every call needs a comparison.



Really speaking I am compromising performance for the practicability.

Saturday, February 5, 2011

How to get the method name inside same method programmatically

You may find it waste.Why somebody need to find out the name of the method by writing code inside the same method? But I have a scenario where I need to find out who is calling one method inside it. In other words from a method’s perspective I need to know who (method name ,class & assembly)called me and based on that I want to do some actions.Something like prevent calls from some particular classes & assemblies.

Still I didn’t get any luck in this.But during the google I found out another thing. How to know the name of the method through the code written inside the same. It was interesting to me and here are the 2 ways.

static void PrintMyName()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
Console.WriteLine(new StackFrame(0).GetMethod().Name);
}



This will display the method name to which the code belongs “PrintMyName”.

Friday, February 4, 2011

Powershell to find version of .net assemblies

Las week we upgraded our application version from 2010 to 2011.This involved a lot of changes in the configuration files along with UI changes such as logos ,images etc...One of the change was in the assembly version and correction of config files to reflect the version. Most of our code is relying on .net reflection so the config files should be updated properly to get the fully qualified name of classes.

Till then everything was fine. We got problems when the build came. The build script failed to build the dlls in the new assembly version. The product have around 400 DLLs and we are not using GAC. How to find out which dll is in wrong version?

One solution is to put the assemblies into GAC and see the version.Another is to open the DLL in reflector and check the version. Since the number of DLLs is somewhat huge ,it is better to write a program to find out the assemblies which are in wrong version.The next question came C# or VB.Net?

But keeping mind the principle of architecture finally decided to write a small windows power shell to find out the version.Code below.

Windows Power shell code to find out the .Net assembly / .dll version

#--------Script to find out .net assembly version mismatches---------
$curDir=$("C:\Binaries")
$pattern=($curDir + $("\*.dll"))
Foreach ($file in Get-Childitem $pattern)
{
$fp=($curDir+"\"+$file.name)

#Load the assembly
$asm=[Reflection.Assembly]::LoadFrom($fp)
$asmName=$asm.GetName()
$ver=$asmName.Version

#Create required version object to compare
$reqVer=new-object Version -arg "
4.0.0.0"

#if the version is not matching show a warning
if($ver -ne $reqVer) {
Write-Warning $fp
Write-Warning $ver.ToString(4)
}
}

Wednesday, August 25, 2010

Applications of Extension methods

Extension methods was introduced some time back with C#3.0 .The feature is great we can attach one more function to the existing classes and can call those methods with the object of those classes itself.It is very helpful for architects to write all the required methods and attach with the existing classes as well.

We all might have surprised by seeing so many methods suddenly in our favorite IEnumerable derived classes such as List and observable collection when the linq is introduced.Did they wrote all these methods inside the List class? absolutely not.Instead they wrote extension methods for IEnumerable and from the user point of view they looks like normal methods because the methods can be invoked  just by using the objects.

I was looking for some uses of the extension methods like this.The option is to replace all most all the helper classes by extension methods. While looking through the helper classes I struck around the reflection helper. The code was written to get the value of property using reflection.If the developer is familiar with the code base he probably knows that there is a helper library and can use it.But what about a fresher.He will surely struck on this and may think about changing the design.If he is coming from the true object oriented world where there is no chance to invoke private properties he is done. The GetProperty and SetProperty really comes helpful here.

Don’t feel so much complicated .Its so simple .Write 2 extension methods which internally gets and sets the value of properties by getting the name of property in string.Now it comes very easy to the end developer as the method will be shown when they type the magic key dot(.)

public static class MyExtensions 
{
    /// <summary>
    /// Gets the value of property mentioned in propertyName.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <param name="propertyName"></param>
    /// <returns></returns>
    public static T GetProperty<T>(this object obj, string propertyName)
    {
        PropertyInfo pi = obj.GetType().GetProperties().FirstOrDefault((p) => string.Equals(p.Name,propertyName));
        T t = default(T);
        if (pi != null && typeof(T) == pi.PropertyType)
        {
            t = (T)pi.GetValue(obj, new object[] { });
        }
        return t;
    }
    /// <summary>
    /// Sets the value of property mentioned in propertyName.Returns true on success.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    /// <param name="propertyName"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool SetProperty<T>(this object obj, string propertyName,T value)
    {
        PropertyInfo pi = obj.GetType().GetProperties().FirstOrDefault((p) => string.Equals(p.Name, propertyName));
        if (pi != null && typeof(T) == pi.PropertyType)
        {
            pi.SetValue(obj,value, new object[] { });
            return true;
        }
        return false;
    }
}

Before using extension methods make sure that the assembly is referred and using the namespace.

SampleVM vm = new SampleVM();
vm.StringProperty = "Joy";
string s = vm.GetProperty<string>("StringProperty");
vm.SetProperty<string>("StringProperty", "Joymon");

Thursday, June 28, 2007

Call private function / method using reflection!!!

Dont wonder.Its possible to call a private function is .Net using reflection.

If you run the below program you could see Joy n Code displayed on your screen eventhough that is in a private function called getstr in class pvt.

using System;
using System.Reflection;

namespace ConsoleApplication1 {
class Class1{
STAThread
static void Main(string[] args)
{
pvt b=new pvt();
MethodInfo mi=b.GetType().GetMethod("getstr", BindingFlags.Instance | BindingFlags.NonPublic );
Console.WriteLine ( mi.Invoke(b,null));
Console.ReadLine();
}
}
public class pvt {
private void getstr()
{
Console.WriteLine("Joy n Code");
}
}
}