Giter Club home page Giter Club logo

reflectionmagic's Introduction

ReflectionMagic

Build Status

Private reflection allows you to access private and internal members in other assemblies. Generally, it’s considered to be a bad thing to do, as it ties you to undocumented implementation details which can later break you. Also, it’s not usable in medium trust.

The purpose of this library is not to encourage anyone to use private reflection in situations where you would not have done it anyway. Instead, the purpose is to allow you to do it much more easily if you decide that you need to use it.

Putting it a different way, I’m not telling you to break the law, but I’m telling you how to break the law more efficiently if that’s what you’re into!

The scenario

Assume you are using an assembly that has code like this:

public class Foo1 
{
    private Foo2 GetOtherClass() 
    { 
        // Omitted
    }
}

internal class Foo2 
{
    private string SomeProp { get { /* Omitted */ } }
}

And assume you have an instance foo1 of the public class Foo1 and your evil self tells you that you want to call the private method GetOtherClass() and then get the SomeProp property off that.

Using reflection

Using plain old reflection this would be something like this:

object foo2 = typeof(Foo1).InvokeMember("GetOtherClass", 
                BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
                null, foo1, null);
                
PropertyInfo propInfo = foo2.GetType().GetProperty("SomeProp",    
                BindingFlags.Instance | BindingFlags.NonPublic);

string val = (string)propInfo.GetValue(foo2, null);

Which works, but is pretty ugly.

Using ReflectionMagic

Doing the same but using the ReflectionMagic library:

string val = foo1.AsDynamic().GetOtherClass().SomeProp;

Download

This library is available through NuGet.

More info

For more information look at the original blog post by David Ebbo: https://blogs.msdn.microsoft.com/davidebb/2010/01/18/use-c-4-0-dynamic-to-drastically-simplify-your-private-reflection-code/

Known limitations

Support for 'out' and 'ref' parameters is not available on .NET Core 1.x runtimes. This is a runtime limitation and results in a PlatformNotSupportedException.

reflectionmagic's People

Contributors

0xced avatar configurator avatar davidebbo avatar jvandertil avatar lbargaoanu avatar proff avatar vuplea avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

reflectionmagic's Issues

A more permissive license

Would it be possible to switch to the MIT license? That seems to be more permissive than MSPL. Projects with an MIT license: Newtonsoft.Json, Nunit, AutoMapper, Autofac, .Net Core, jQuery. Apache 2.0 seems even more permissive, but I'm no lawyer.

Calling a generic method that varies only by number of generic parameters throws exception

Consider two methods:

public void Foo<T>(T t);

public void Foo<T, T2>(T t, T2 t2);

Trying to call Foo when passing 2 parameters could fail with:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: The type or method has 1 generic parameter(s), but 2 generic argument(s) were provided. A generic argument must be provided for each generic parameter.

The number of arguments is not checked in InvokeMethodOnType.

Restore strong naming

In #6 the strong naming build step was removed, this should be restored. This will probably coincide with #7.

Debug Assembly in NuGet package

Hi David!

It seems that your nuGet package of ReflectioMagic contains a debug assembly of your library. Would it be possible to include a release assembly instead or as well?

Best regards,
Simon

Is there a possibility to set auto generated backing fields?

Lets assume I want to set a read only property with the name Path. The compiler generates a backing field name with something like:
k__BackingField

of course these brackets can't be used to set the field using dynamic coding. Do you have some code conventions that allow me to set that backing field?

Migrate project.json to new .csproj

Since project.json is being deprecated in favor of the improved .csproj files, we should follow along,

Since the format and tooling are currently in alpha state, I'm holding this off until things stabilize.

Add public helper method for unwrapping

We are using ReflectionMagic for a method returning object (whose runtime type can be both a primitive or a complex type).
The problem is that "string".AsDynamic().RealObject fails because of the wrapper skipping.

I am proposing to expose a helper method for the unwrapping (the code is already present in PrivateReflectionDynamicObjectBase.Unwrap).

call method with ref

When you wanna call dynamicControl.DefWndProc(ref m); it does not work. So I add to method ParametersCompatible the follow workarround:

               if (params1[i].ParameterType.IsByRef) {
                    var p2 = params2[i].GetType().MakeByRefType();
                    //TODO support derivation
                    if (params1[i].ParameterType != p2) {
                        return false;
                    }
                }
                else {
                    if (!params1[i].ParameterType.IsInstanceOfType(params2[i])) {
                        // Parameters should be instance of the parameter type.
                        return false;
                    }
                }

Calling a method that does not exists doesn't throw explicit exception

Hi

I was using the code directly in my application and I just migrated to use the Nuget, all my tests seem to pass except this one: (it was green before updating to use the Nuget)

        [TestMethod]
        public void it_should_throw_an_exception_if_the_method_does_not_exist()
        {
            var originalObject = new SimpleObject();
            var sut = originalObject.AsDynamic();
            Action a = () => sut.DoesNotExistMethod("dede");

            a.ShouldThrow<MissingMethodException>().WithMessage("*DoesNotExistMethod*");
        }

Instead it throws:

Result Message: 
Expected a <System.MissingMethodException> to be thrown, but found a <System.ApplicationException>: System.ApplicationException with message "Error in the application."
     at ReflectionMagic.PrivateReflectionDynamicObjectBase.InvokeMethodOnType(Type type, Object target, String name, Object[] args, IList`1 typeArgs)
     at ReflectionMagic.PrivateReflectionDynamicObjectBase.InvokeMethodOnType(Type type, Object target, String name, Object[] args, IList`1 typeArgs)
     at ReflectionMagic.PrivateReflectionDynamicObjectBase.InvokeMethodOnType(Type type, Object target, String name, Object[] args, IList`1 typeArgs)
     at ReflectionMagic.PrivateReflectionDynamicObjectBase.TryInvokeMember(InvokeMemberBinder binder, Object[] args, Object& result)
     at CallSite.Target(Closure , CallSite , Object , String )
     at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)

It's not high severity, I just wanted to let you know

Good job, I love this tool

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.