mardi 1 décembre 2015

Failed to set property using reflection

I'm creating a dynamic class and using reflection to assign the property values, the class has two properties

public int Tipo_Pension {set;get;}
public bool Novedad_TDP {set;get;}

And I use the following code to set the values. VariableName is the name of the property and Value the real value of the property to set, and ruleMeta.Evaluator is the binder.

private void SetVariable(string VariableName, object Value, RuleMeta ruleMeta)
{
    o = ruleMeta.EvaluatorType.InvokeMember(
        VariableName,
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
        Type.DefaultBinder,
        ruleMeta.Evaluator,
        new object[] { Value }
    );
}

The fist property, the Integer, works fine, but when its executed for the Boolean it fails and throws the next error

Method 'Cenet.RulesManager.Rule360788846.Novedad_TDP' not found

Any idea what could be happening?

Note: the object Value for the Boolean comes as a string: "false"





grails reflection - Calling a dynamic tag

I know this is odd, but I'm trying to provide a pass through interface in a taglib that allows the caller to pass in any other tag to be displayed in a container with additional processing.

To this effect, I'm trying to dynamically call an arbitrary tag in an arbitrary namespace. This may be clearer by example.

GSP:

<myLib:myTag someProp="blah" anotherProp="blah2" size="80" namespace="g" tag="textField">

In my taglib, I'm trying to display the tag they pass.

Taglib:

def myTag = {
  String id = //some processing, not specified by caller
  attrs.put("id", id)
  def namespace = attrs.remove("namespace")
  def tag = attrs.remove("tag")
  out << ?????
}

The problem comes after the out... I'm having trouble calling the tag. I've tried the following with the following errors

namespace.tag(attrs) //No signature of method: java.lang.String.tag()
namespace."${tag}"(attrs) //No signature of method: java.lang.String.textField()
"${namespace}"."${tag}"(attrs) //No signature of method: java.lang.String.textField()

This seems to work, but the method needs to support tags in other namespaces

g."${tag}"(attrs)

So the question is How can I use reflection to use a dynamically defined taglib?

I don't have them pass the fully formed tag in the body() because I need to interact with it in the taglib.





Is there any way to get the list of attributes of a class without any instantiated object?

I already know that we can get the list of attributes of a object using reflection in Swift, but all the examples that I found and have implemented so far uses a instantiate object. Something like that:

func attributeList() -> [String] {

    var attributeList = [String]()
    let serializableMirror = Mirror(reflecting: self) //using instantiate object

    for childMirror in serializableMirror.children {            
        if let label = childMirror.label {
            attributeList.append(label)
        }
    }
    return attributeList
}

My question is, there is any way to get the attributes of a class without any reference to it? Some kind of static method where I pass my desired class type and get the attributes list of it.





TargetInvocationException in SetValue(Reflection) inside of Thread

I'm getting this exception:

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll

When I insert extension method 'SetProperty' inside of ThreadStart:

Object temp = element;

PropertyInfo currentProperty = temp.GetType().GetProperty("FontSize");

object currentValue = currentProperty.GetValue(temp);

threads[i] = new Thread(
new ThreadStart(() => 
{ currentProperty.SetValue(temp, Convert.ChangeType(58, currentProperty.PropertyType), null); }));

threads[i].Start();

But when I use SetValue without Threading, everything works without any exceptions or errors.

PropertyInfo currentProperty = temp.GetType().GetProperty("FontSize");

object currentValue = currentProperty.GetValue(temp);

currentProperty.SetValue(temp, Convert.ChangeType(58, currentProperty.PropertyType), null);

Where could be a problem with using Thread? I'm using C# 6, .NET 4.5.6.





Julia: invoke a function by a given string

Does Julia support the reflection just like java?

What I need is something like this:

str = ARGS[1] # str is a string
# invoke the function str()





lundi 30 novembre 2015

Passing value from a different app domain to the primary (Main) app domain

From this post, I am able to load a dll into an app domain and get the types in that dll and print them in the temporary domain's function if I want to. But I now want to pass these types back to the primary domain (which has Main). I found this thread which says I need to wrap my object in a MarshalByRef type of class and pass it as an argument, and I tried that but I get an exception. Here is what I have (slightly modified from the example given by @Scoregraphic in the first linked thread)

    public class TypeListWrapper : MarshalByRefObject
    {
            public Type[] typeList { get; set; }
    }

    internal class InstanceProxy : MarshalByRefObject
    {
        public void LoadLibrary(string path, TypeListWrapper tlw)
        {
            Assembly asm = Assembly.LoadFrom(path);

            var x = asm.GetExportedTypes();//works fine

            tlw.typeList = x;//getting exception on this line
        }
    }

    public class Program
    {

        public static void Main(string[] args)
        {
            string pathToDll = Assembly.GetExecutingAssembly().Location;
            string path = "/path/to/abc.dll";

            try
            {
                AppDomainSetup domainSetup = new AppDomainSetup
                {
                    PrivateBinPath = pathToDll
                };
                AppDomain domain = AppDomain.CreateDomain("TempDomain", null, domainSetup);
                InstanceProxy proxy = domain.CreateInstanceFromAndUnwrap(pathToDll, typeof(InstanceProxy).FullName) as InstanceProxy;
                TypeListWrapper tlw = new TypeListWrapper();
                if (proxy != null)
                {
                    proxy.LoadLibrary(path, tlw);
                }


                AppDomain.Unload(domain);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
            }

            Console.ReadLine();
        }
    }

I get the exception:

Could not load file or assembly 'abc, Version=1.0.0.5, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

If I remove the tlw argument from the function and remove this assignment, it works just fine. I'm completely stumped on this.





Reflection on swing components

I'm trying to assign a value to a swing component through reflection. Let's use a JCheckBox for example. I have the following class:

public class JCheckBoxTest
{
    private JCheckBox test;

    public JCheckBoxTest()
    {
        this.test = new JCheckBox();
    }

    public reflectionTest()
    {
        Field field;
        Method method;

        field = this.getClass().getDeclaredField("test");
        method = field.getType().getSuperclass().getDeclaredMethod("setSelected");

        method.invoke(field, "true");
    }
}

This code fails at:

method = field.getType().getSuperclass().getDeclaredMethod("setSelected");

because it cannot find the specified "setSelected" method since it is located inside the inner class "ToggleButtonModel" of the superclass "JToggleButton" which is extended by the "JCheckBox" class.

What would be the best approach to solve this?

Thanks.

Edit: Corrected typo in code.