jeudi 31 août 2017

Bundle existing classes together inside a parent class Java

I have a usecase in Java, where I have a custom Annotation. Certain classes are annotated with this annotation. Now I need to find all these classes in my package, then either at compile time or when the application comes up, create a new class with these fields along with some other fields. Expect this class as part of the request body at an end point which gets populated to its subclasses whenever a request comes.

For Instance:-

   @CustomAnnotation
    class User{
        String name;
        Integer id;
    }

    @CustomAnnotation 
    class Product{
        String id;
        String description;
        String name;
    }

These are the two classes which user creates and annotates it with @CustomAnnotation.

Now I want to write a piece of code which looks for all the classes marked with @CustomAnnotation and create another class:-

class Custom{
     String assignedTo;
     User users[];
     Product products[];
}

map this to an endpoint say localhost:8080/assign Now every time a request comes to localhost:8080/assign class Custom gets populated and returns arrays of Users and Products respectively back to the main control for further logic.

I believe with a language like Nodejs it would have been easy because of it's dynamic nature. What would be the right approach towards solving this problem in Java, using reflections would be the right approach or should I have a look at Groovy? can I export groovy code as a jar file which could be imported into any project and create the endpoint inside that application? Is it possible to write code which creates classes at compile time or runtime in Java?

I think spring framework does something similar.

Thanks





Avoid using reflection to enhance performance

Can we completely avoid reflection using Generics and Delegates? what's the cases we have to use reflection? can we pin all cases where we have to use reflection or there is far to many?





Get all properties of an implemented interface

I have the following setup:

public interface IInput
{
}

public class SomeInput : IInput
{
    public int Id { get; set; }
    public string Requester { get; set; }
}

Now I want to write a function that can take anything that implements IInput and use reflection to give me the properties :

public Display(IInput input)
{
    foreach (var property in input.GetType().GetProperties())
    {
        Console.WriteLine($" {property.Name}: {property.GetValue(input)}");
    }
}

Where

var test = new SomeInput(){Id=1,Requester="test"};
Display(test);

shows

Id: 1
Requester: test





Java Reflection Issure resulting in Read Only Transaction Error

I have two data sources (persistent contexts) one is Read Only, and one is for Read-Write, everyone pointing to a different database.

Read-Only is configured to be outside of JTA, as I going to only read from it.

So in this way, we're migrating all related to reads/fetch/gets from database to retrieve data from the read only DB.

Take a look at this code:

ActionItem item = pEm.find( ActionItem.class, pActionItemViewModel.getId() );
item.setActionTimestamp( new LocalDateTime( pActionItemViewModel.getActionDate() ) );
ActionItem itemTemp = pEm.merge( item );

pEm is the entity manager, as you know the find searches for the ActionItem, then it updates with the LocalDateTime, then it use the 'merge' function...

Problem is, in pEm.find inside of the function (that i've overrided) i use the read only entity manager, so it fetch from the read DB, problem is with the merge, because it's giving me an ERROR saying:

Caused by: org.postgresql.util.PSQLException: ERROR: cannot execute UPDATE in a read-only transaction

And it's because inside of the merge, i use reflection to get the same object from the read-write entity manager, to enabled transaction to commit in the read-write, but for some reason it's not working, this is the merge function:

public <T> T merge(T t) {
    try {
        return (T) this.readWriteEntityManager.merge(this.readWriteEntityManager.getReference(t.getClass(), t.getClass().getMethod("getId").invoke(t)));
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
        return null;
    } catch (IllegalAccessException e) {
        e.printStackTrace();
        return null;
    } catch (InvocationTargetException e) {
        e.printStackTrace();
        return null;
    }
    // return this.readWriteEntityManager.merge(t);
}

Thing is, if i perform the get reference outside the merge, it works, like this...

ActionItem itemT = pEm.find( ActionItem.class, pActionItemViewModel.getId() );
ActionItem item = pEm.getReference(itemT.getClass(),itemT.getId());
item.setActionTimestamp( new LocalDateTime( pActionItemViewModel.getActionDate() ) );
ActionItem itemTemp = pEm.merge( item );

Any idea would be appreciated... (help help help)





mercredi 30 août 2017

Cast object from PropertyInfo.GetValue to the type returned by PropertyInfo.GetType

As described in the title, I would like to be able to get the actual object referenced by a PropertyInfo to be passed to a generic method.

I've tried Convert.ChangeType(propInfo.GetValue(baseObj, null), propInfo.GetType() with no luck, is there any way to do this?





Unity reflecting bullets

I am trying to reflect my bullets that I fire, like light would but currently the bullets just go to the slide along and then carry on in the same direction.

could it be any project settings I am using?

here is my code:

public float speed;
private Vector3 oldVelocity;

private void Start()
{
    Rigidbody rigidbodyTemp = GetComponent<Rigidbody>();
    rigidbodyTemp.freezeRotation = true;
    rigidbodyTemp.isKinematic = false;
    rigidbodyTemp.detectCollisions = true;

}

// Update is called once per frame


// Update is called once per frame
void FixedUpdate () {
    Rigidbody rigidbodyTemp = GetComponent<Rigidbody>();

    transform.Translate(Vector3.forward * speed * Time.deltaTime);
    oldVelocity = rigidbodyTemp.velocity;


}

private void OnCollisionEnter(Collision collision)
{
    Rigidbody rigidbodyTemp = GetComponent<Rigidbody>();

    // Used for contact point
    ContactPoint contact = collision.contacts[0];

    Vector3 reflectedVelocity = Vector3.Reflect(oldVelocity, contact.normal);

    rigidbodyTemp.velocity = reflectedVelocity;
    Quaternion rotation = Quaternion.FromToRotation(oldVelocity, reflectedVelocity);
    transform.rotation = rotation * transform.rotation;

    if(collision.gameObject.tag == "Box")
    {

    }
}

}





How to Check if type of Map extends Number

I'm trying to check if a Map<String, T> contains Objects (T) of type Double or Integer.

I don't want to use the actual Objects in the map for checking the class since It's not certain that the Map contains Objects at all.

I can achieve this by doing the following (Assuming the field is containing a Map):

ParameterizedType type = (ParameterizedType) field.getGenericType(); 

isNumeric(type);

/**
 * @param type
 * @return Returns true if type is numeric
 */
private static boolean isNumeric(ParameterizedType type) {
    return  type.getActualTypeArguments()[1].toString().equals("? extends java.lang.Number");
}

It's sufficient for me but it doesn't feel like a clean solution.

However, I can retrieve the Type of the getActualTypeArguments()[1] by doing the following:

Type typeOfSecondGeneric = type.getActualTypeArguments()[1]; // equals '? extends java.lang.Number'

I can't use Number.class.isAssignableFrom(typeOfSecondGeneric); // Class expected

After I researched a bit, I didn't came up with a better solution than doing the String comparison.

What am I getting wrong?

Help is appreciated!





Java Reflection Issue: java.lang.ClassNotFoundException

I have one class which takes classname in runtime and creates instance of that class. I have done this with reflection. Please see my code below

//Interface

   public interface DDInterface {
     public void process();
     }

// class which implements the interface

   package com.dd.august;
   public class DDClass implements DDInterface 
       {
       public void process()
        {
        System.out.println("Hello All");
         }
       }

//the main class [This works fine if I hard code inside Class.forName()] - scenario 1

        DDInterface ddInterface = 
           Class.forName("com.dd.august.DDClass").newInstance();
          ddInterface.process();

// But this way it does not work if I pass classname dynamically - scenario 2

        String className="com.dd.august.DDClass";
         DDInterface ddInterface = 
           Class.forName(className).newInstance();
          ddInterface.process();

The error I am getting from this is java.lang.ClassNotFoundException: com/dd/august/DDClass. All the 'packagename.classname' is changing in 'packagename/classname' which doesn't happen in scenario 1.

Anyone know how to resolve this?

Regards, Sharmi





How to use java reflection to assign a generic instance's field with an object?

I'd like to write an util method to cast a json object to a kind of model.

public static <T> T getModelFromJson(Class<T> cls,JSONObject json)

And the part of the method is:

T model = cls.newInstance();
Field []fields = cls.getDeclaredFields();
for (Field field : fields) {
    Object o = json.get(field.getName());
    if(o == null){
        logger.error("no field:{}",field.getName());
    }
    //how to assign model's field with o
}

So....how to assign the model's field with Object o?





C# Casting an object returned from invocation and invoking a method on that object

I am trying to invoke a method that is within the returned class of another invoked method.

I am trying to call the GetConnectionCost() method from the ConnectionProfile class. The ConnectionProfile object was returned by Invoking the GetInternetConnectionProfile method from NetworkInformation class.

Below is my code so far:

using System.Reflection;

var t = Type.GetType("Windows.Networking.Connectivity.NetworkInformation, Windows, ContentType=WindowsRuntime");

var profile = t.GetTypeInfo().GetDeclaredMethod("GetInternetConnectionProfile").Invoke(null, null);

var cost = profile.GetTypeInfo().GetDeclaredMethod("GetConnectionCost").Invoke(null, null); //This does not work of course since profile is of type object.

I rarely use reflection in my code so I am not an expert in the matter but I am trying to find a way to case the profile object and invoke the GetConnectionCost method on it.

Any suggestions





C# Reflection test if member is an interface implementation

Suppose I have the following interface and implementing class:

public interface IInterface
{
    string MyMember { get; }
}

public class Class : IInterface
{
    public string MyMember
    {
        get
        {
            return "foo";
        }
    }
}

Now I get the member via reflection

var member = typeof(Class).GetMember("MyMember").Single();

How can I test if the member is the implementation of an interface?





org.xeustechnologies.jcl.JarClassLoader ClassNotFoundException

I need to use two different versions of jar of same package in my code. So that i have used JarClassLoader to achieve the same

But I ended with ClassNotFoundException

I have given below my code

Below is the executable Main class file

import java.lang.reflect.Method;

import org.xeustechnologies.jcl.JarClassLoader;
import org.xeustechnologies.jcl.JclObjectFactory;
import org.xeustechnologies.jcl.JclUtils;

public class Sam {

    public static void main(String args[]) {
        try{
            JarClassLoader jcl = new JarClassLoader();
            jcl.add("/Users/sd/Downloads/hbase-1.2.6/lib/");
             Object obj1 = JclObjectFactory.getInstance().create(jcl, "sample.InsertData");
             Insert mig = JclUtils.cast(obj1, Insert.class);
            Thread.currentThread().setContextClassLoader(jcl);
            Method method = Insert.class.getMethod("insert", new Class[]{});
             method.invoke(mig, args);
        }catch(Exception e) {
            e.printStackTrace();
        }

        }    

}

InsertData.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

public class InsertData implements Insert{



    public  void insert() throws IOException {
        for (int j = 0; j < 1; j++) {

            Configuration config = HBaseConfiguration.create();

On executing Sam I ended with below java.lang.ClassNotFoundException

java sample/Sam

java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at sample.Sam.main(Sam.java:21) Caused by: java.lang.reflect.UndeclaredThrowableException at com.sun.proxy.$Proxy0.insert(Unknown Source) ... 5 more Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.xeustechnologies.jcl.proxy.JdkProxyProvider$JdkProxyHandler.invoke(JdkProxyProvider.java:56) ... 6 more Caused by: java.lang.NoClassDefFoundError: org/apache/hadoop/hbase/HBaseConfiguration at sample.InsertData.insert(InsertData.java:27) ... 11 more Caused by: java.lang.ClassNotFoundException: org.apache.hadoop.hbase.HBaseConfiguration at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 12 more

Please help





mardi 29 août 2017

using reflection to set up inner class member

I have 2 class (i've simplified my sample, its not really my classes)

class Father {
    private Child child;

    public Father() {
          child = new Child();
    }
}

class Child {
    private int age;
}

In order to make unit tests, i need to set the value of age, ONLY from Father class, using reflection.

Basically, i have a problem setting the final value in age, and its generating an exception.

1st, i'm retrieving Father class, and then from it, taking child field, which works well. My problem is calling ageField.set(ageField, 15); since ageField is a field and not the actual age member.

Field field = Father.class.getDeclaredField("child");
field.setAccessible(true);
Object value = field.get("child");

Child child = (Child) value;
Field ageField = value.getClass().getDeclaredField("age");
ageField.setAccessible(true);
ageField.set(ageField, 15);

Fyi, i've looked at the following links, so this is not a duplicate.





Why are Reflection's GetProperty() or GetField() not instance or extension methods?

I'm fairly new to Reflection in C#, and I think I understand how to use it to solve some problems.

However, what I find confusing is the syntax for methods like GetProperty() or GetField().

To get an instance field, you have to do typeof(MyClass).GetField("fieldName").GetValue(myClassInstance). Which is not the most straightforward thing.

Wouldn't it make more sense to get instance fields or properties by using something like an extension method? Something like:

myClassInstance.GetField("fieldName").Value

And use the previous example for things like static fields/properties/methods.

It just feels more natural than the first example, where you must pass your class instance.

Again, I am new to Reflection, so there might be some disadvantages I'm overlooking.





Comparing generic parameter type using reflection

I want to get a method definition that accepts an Action<T> parameter using reflection. I'm using .NET core 1.1.

Since the class has two methods with the same name, I'm trying to check the type of the accepted parameters to make sure that I'm getting the correct method definition (and not the other overload), but the comparison does not seem to work.

Here is some code that shows this problem:

using System;
using System.Linq;
using System.Reflection;

class ReflectMe {
    public void SomeMethod<T>(Action<T> action) {
        action(default(T));
    }
    public T SomeMethod<T>() {
        return default(T);
    }
}

class Program {
    static void Main(string[] args) {
        var reflectedMethod = typeof(ReflectMe).GetTypeInfo().GetMethods(BindingFlags.Public | BindingFlags.Instance)
            .Where(m => m.Name == "SomeMethod" && m.IsGenericMethodDefinition)
            .Where(m => {
                var parameters = m.GetParameters();
                if (parameters.Count() != 1) {
                    return false;
                }
                var actionType = typeof(Action<>);
                var parameterType = parameters[0].ParameterType;
                if (parameterType == actionType) { // this is always false
                    return true;
                }
                return false;
            })
            .FirstOrDefault();
    }
}

The problem is that parameterType and actionType are not equal, yet when I check in the debugger they look identical.

Why is that comparison failing?





c# How to get enum from custom attribute?

This is MyEnum

public class CountryCodeAttr : EnumAttr
{
    public string Code { get; set; }
    public string Description { get; set; }
}

public enum CountryCode
{
    [CountryCodeAttr(Code = "Unknown", Description = "Unknown")]
    Unknown,
    [CountryCodeAttr(Code = "CH", Description = "Swiss", Currency="CHF")]
    CH
....

}

How can I, get the enum with a specific CountryCodeAttr? for example from attribute Currency?





Invoke Public function in Private field using Reflection C#

I need to access the public function in Private field.

Example

 public partial class Form1 : Form
{
    MainControl mainControl = new MainControl();
    public Form1()
    {
        InitializeComponent();
        var frame = mainControl.GetType().GetField("CustomControl", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        frame.GetType().GetMethod("Display").Invoke(mainControl, new object[] { });
    }
}

public class MainControl
{
    public MainControl()
    {
        CustomControl = new CustomControl();
    }

    CustomControl CustomControl;
}

public class CustomControl
{
    public CustomControl()
    {

    }

    public void Display()
    {
        MessageBox.Show("Displayed");
    }
}

Here i need to invoke the Display function in CustomControl class.

But i am getting exception with the above approach. Can anyone help me on this?





lundi 28 août 2017

Get method name of a delegate passed as a parameter (Compact Framework)

I have a function that takes a Func as a parameter, invokes it, and writes some results to a log. For logging purposes, it would be nice to be able to be able to access the name of the function that is actually being called when the lambda expression executes. Is there a way to do this in compact framework?

    Private Function tryWithLogging(ByVal moveFunc As Func(Of Boolean), ByVal maxRetries As Integer) As Boolean
        Dim attemptsRemaining As Integer = maxRetries

        While True
            Try
                If moveFunc.Invoke() Then
                    Return True
                Else
                    Dim name as String = '??????
                    WriteToLog(_CLASS_NAME, name, "Failed while moving")

                    If attemptsRemaining > 0 Then
                        'try again
                        attemptsRemaining -= 1
                        Continue While
                    Else
                        'exceeded retries
                        Return False
                    End If
                End If
            Catch ex As Exception
                If attemptsRemaining > 0 Then
                    'try again
                    attemptsRemaining -= 1
                    Continue While
                Else
                    'exceeded retries
                    Return False
                End If
            End Try
        End While
    End Function

Example usage:

tryWithLogging(Function() someXYZMove(x,y,z), 2) 

Here's what I have attempted to retrieve the name:

moveFunc.Method.Name 'returns whatever the compiler decided to name the lambda

New StackTrace().GetFrame(1).GetMethod().Name 'works, but is not available on CF

I have also tried passing an Expression(Of Func(Of Boolean)) instead and getting the name from that, but that is also not available on CF.

Is there any way to retrieve the name of a function being invoked by a lambda within the shackles of compact framework?





Get the value of a Swift variable from a constructed name

I am stuck at a problem which i am trying to figure out in Swift 4.

Let say, i have the below variables

let var1 = "One"
let var2 = "Two"
let var3 = "Three"

var counter = 1

// Loop Start

let currentVariable = "var" + "\(counter)"

//Fetch the value of variable stored under currentVariable

counter += 1

//Loop end

I am trying to get the value based on variable name stored under currentVariable.





The value for annotation attribute Test.enabled must be a constant expression

Basically, I wanted to use a constant boolean attribute of Context class which I have changed via reflection so that I can dynamically set the @annotated enabled for a testNG method in a TestNG class. The TestNG class has a static final attribute which is the same as the Context.DISBLE_TEST_CASES_IF_OLD_STACK. I have pasted the code below for the TestNG class and its method. The end goal for me is to toggle the enabled value or basically disable the test based on the the context if its old environment or new environment

 package com.abc.api.core.context;

    import java.lang.reflect.Field;
    import java.lang.reflect.Modifier;


    public class Context {
        public static final boolean DISBLE_TEST_CASES_IF_OLD_STACK = getConstantReflection();


        public static boolean getConstantReflection()
        {
            System.out.println(DISBLE_TEST_CASES_IF_OLD_STACK);
            try {
                setEnableFlagBasedOnStackForTestCases();
            } catch (NoSuchFieldException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(Context.DISBLE_TEST_CASES_IF_OLD_STACK);
            try {
                final Field fld = Context.class.getDeclaredField("DISBLE_TEST_CASES_IF_OLD_STACK");
                return (Boolean) fld.get( null );
            } catch (NoSuchFieldException e) {
                return (Boolean) null;
            } catch (IllegalAccessException e) {
                return (Boolean) null;
            }
        }

        private static void setEnableFlagBasedOnStackForTestCases() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{


            Field f = Context.class.getDeclaredField("DISBLE_TEST_CASES_IF_OLD_STACK");
            f.setAccessible(true);

            //'modifiers' - it is a field of a class called 'Field'. Make it accessible and remove
            //'final' modifier for our 'CONSTANT' field
            Field modifiersField = Field.class.getDeclaredField( "modifiers" );
            modifiersField.setAccessible( true );
            modifiersField.setInt( f, f.getModifiers() & ~Modifier.FINAL );

            if (TestcaseContext.getContext().equalsIgnoreCase(Context.OLD_STACK)) {
                f.setBoolean(null, false);
            }else {
                f.setBoolean(null, true);
            }
        }

    }

TESTNG CLASS AND METHOD example:

package com.abc.api.test.tests.TestA;

import com.abc.api.core.context.Context;

public class TestA extends TestCommon {

    private static final boolean ENABLE_DISABLE = Context.DISBLE_TEST_CASES_IF_OLD_STACK;

    /**
     * 
     */
    @BeforeTest
    void setPropertiesFile() {
      ......

    }

    /**
     * PATCH Positive Test Cases
     * 
     */

    @Test(priority = 11, enabled=ENABLE_DISABLE)
    public void testPositive1() {
        ......
    }
}





GetAssemblies() throws LoaderExceptions after some changes in project

I have a method in a reflection helper class referenced in some points of the app:

public static IEnumerable<TypeInfo> GetControllersWeb()
{
    return AppDomain.CurrentDomain
                    .GetAssemblies()
                    .First(x => x.FullName.StartsWith("MyProject.Web,", StringComparison.CurrentCultureIgnoreCase))
                    .DefinedTypes
                    .Where(x => x.Name.EndsWith("Controller", StringComparison.CurrentCultureIgnoreCase));
}

Somebody made a change(removed some classes) in the project couple days ago and now this methods throws an exception. The exceptions is the following:

Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

And in the LoaderExceptions it describes one of the removed classes.

If I change the linq query to:

AppDomain.CurrentDomain
         .GetAssemblies()
         .First()
         .DefinedTypes;

It works fine. I want to know what in that First() method could be causing this? Perhaps something that broke the project settings?





How to copy properties from one object to another?

I am implementing a audit service and I want to copy properties of the auditing object to the log object. The log object contains the same properties as the auditing object and some additional properties like timestamp, modifiedBy etc. I want to copy the common properties from the auditing object to log object. I tried with reflection but it allows copy only for similar type of objects. How to do this? Is there a way to use reflection with xml file mapping? I'm using java by the way





Class.forName() takes too long to return a Class in JUnit

ClassLoader classLoader = getClass().getClassLoader();
ImmutableSet<ClassInfo> classInfoSet = ClassPath.from(classLoader)
          .getTopLevelClassesRecursive("com.example");
for (ClassInfo classInfo : classInfoSet) {
  Class<?> clazz = classInfo.load();
  doSomething();
}

I'm trying to process 20,00 classes to check if annotation usage is correct. The problem is classInfo.load() takes too much time for specific classes (approx. 20% of all classes).

I replaced this method by the following code for debug and confirmed that Class.forName() takes more than a few minutes for specific classes.

String className = classInfo.getName();
Class<?> clazz = Class.forName(className);

I've run this program many times and it always slows down at the same classes and speeds up at other classes. Those slow classes have normal amount of codes and couldn't find a problem.

I thought it's a memory issue and added the setting below to VM arguments, but nothing changed.

-XX:MaxPermSize=2048M
-XX:-UseGCOverheadLimit

Is there anything I can do to solve this problem?





How to dynamically determine the Class a List must contains

I wrote this generic method, but I don't know how to programmatically tell the List the kind of objects it must contain.

I read that I can't know the <T> object class, so I added another parameter (returnClass) to the method.

public <T extends IModel> List<T> getIModel(Cursor cursor, Class<T> returnClass){

   //returnClass is the class that List must contains.

   //I need something like this
   List<returnClass.getClass()> list;     

}





How to perform reflection call to a method carries String, String, String... as parameters? [duplicate]

I'm facing an issue where I need to use reflection call to invoke method which carries parameters String, String, String... . My code is as below

public void testArrayParams(String first, String second, String... strings) {

    System.out.println("First: " + first);
    System.out.println("Second: " + second);

    System.out.println("Size of String... strings: " + strings.length);
    for(int i = 0; i < strings.length; i ++) {
        System.out.println(i + ": " + strings[i]);
    }

}

And below is the main method

public static void main(String[] args) {
    Dummy dummy = new Dummy();
    //dummy.testArrayParams("Hello", "World", "This is ", "passed in ", "format String... strings.");

    String[] params = {"Hello", "World", "This is ", "passed in ", "format String... strings."};
    String method = "testArrayParams";

    try {
        Class<?> clazz = Class.forName("com.bt.testafix.utils.Dummy");
        Method[] methods = clazz.getMethods();

        for (Method m : methods) {
            if (m.getName().equalsIgnoreCase(method)) {
                //m.invoke(clazz, (Object[]) params);
                m.invoke(clazz, new Object[]{params});
                break;
            }
        }

    } catch (ClassNotFoundException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

It throws below exception when I run the code

java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)

I have tried change to m.invoke(clazz, (Object[]) params);, which is a casting but still giving the same exception. Any idea I can resolve this issue?





dimanche 27 août 2017

Issue with increasing amount of time spent in static property that is using reflection

In this example I have:

internal class SomeClass
{

    private static PropertyInfo[] properties = typeof(SomeCustomClass).GetProperties();

    internal static SomeReturnType SomeMethod()
    {
        System.Diagnostics.Stopwatch s = System.Diagnostics.Stopwatch.StartNew();

        foreach (PropertyInfo property in properties)
        {
         // Nothing
        }
        s.Stop();
        Console.WriteLine(s.Elapsed);
    }
}

I have narrowed down my issue to this piece of code where my console output shows an increasing amount of time almost like there is a leak of some sort. I am executing SomeMethod() in a high volume multithreaded scenario. Any ideas what the problem may be? I assume it has something to do with the static property using reflection but I figured it would only happen once.





How can I find out the external dependencies in a piece of C# code to restrict what it calls?

I'm extending the functionality of a platform that I'm building to include user written components. I could develop a language and write a compiler but since .Net makes it so easy to build and link code I'm exploring just using .net. It would mean compiling them on the fly, which is fine, but I need to know that they're not making any System.IO calls to create files, for instance, or using [unsafe] code to trash memory or calling sockets to communicate with the world. Insuring against bad actors may be too difficult but its at least work looking at. How do I find out what external dependencies a piece of code has?

thanks, john





samedi 26 août 2017

System.NullReferenceException while trying to create a reference type of an already existing class

so I'm creating an console application and I've decided to build it using the command pattern. So simply I have an interface /*ICommand */, an abstract class that inherits the interface called AbstractCommand and several classes that inherits the abstract one with names of type {commandName}Command (for example the command to quit the app is QuitCommand). I'm not quite sure whether you got what I'm trying to say, however, I'll just give the code I get an error with.

private string ProcessInput(List<string> arguments)
    {
        string command = arguments[0];
        arguments.RemoveAt(0);

        Type commandType = Type.GetType(command + "Command");
        var constructor = commandType.GetConstructor(new Type[] { typeof(IList<string>), typeof(IManager) });
        ICommand cmd = (ICommand)constructor.Invoke(new object[] { arguments, this.fighterManager });
        return cmd.Execute();
    }

So the main problem is that when I get to the line "Type commandType = ...", for some reason commandType just gets set to null, not for let's say QuitCommand and therefore the next line just throws an "System.NullReferenceException: 'Object reference not set to an instance of an object.'"

I don't have enough reputation to post images, so here is the link : http://ift.tt/2xD2ppw !

I tried to mark that the "command" has saved the command name, however, commandType is still null :(





Generate a class based on table schema

I want to dynamically generate a class based on the results from a query that user submits. For instance, if the user enters Select name, age from tbl, the result is a name column which is string and age which is an int. The resulting class should be:

public class Test
{
   public string Name { get; set; }
   public int Age { get; set; }
}

Is there an efficient way to do this via EntityFramework or features in C# or I have to use maybe reflection to create a new type and instantiate it.

PS: My purpose is to run this query on the database and show the results in a Grid to the user and run some filter/sort/etc. on it.





Get a type of variable and declare an other variable with this type in Swift

I currently exploring the JSON world in swift and I've some trouble to make a clean code.

Let's say I've the following structure

struct Foo {
  var a: String = ""
  var b: Int = 0
}

I use reflection to get a dictionary of the label : value of this struct with this function:

static func dictionaryRepresentation() -> [String : AnyObject] {
  var dictionnary = [String : AnyObject]()

  for child in Mirror(reflecting: self).children {
    dictionnary[child.label!] = child.value as AnyObject
  }

  return dictionnary
}

Now I have a dictionary of [String : AnyObject] and here comes the issue.

I would like to be able to do something like this

let representation = T.dictionaryRepresentation()
for jsonItem in json { // json is a dictionary [String : Any]
  for (label, value) in object {
    let type = Mirror.init(reflecting: value).subjectType // The type of the item
    let item = jsonItem[label] as? type // This line doesn't work I cannot cast here
  }
}

Any idea about how to achieve this?





Generic test in TypeScript that asserts each property on a class has a value assigned

I have a TypeScript +2.4 project where I'm using Jest for my unit tests. The project has a lot of poco models, without a default value. For example:

export class Foo {
    public id: number
    public name: string;
    public when: Date;
}

Each of these models is mapped from raw json to this class. It is a requirement for my tests that all properties are assigned, e.g. have values. This leads to the following test that has to be written for all models:

test('Foo() should have its properties assigned', () => {
    const target: Foo = {
        id: 1001, name: 'whatever', when: new Date()
    };

    // manually assert each propertie here
    expect(target.id).toBeDefined();
    expect(target.name).toBeDefined();
    expect(target.when).toBeDefined();
}

To me, that's not so DRY to do for each test. Not to mention error prone and cumbersome. What I would like to do is create a helper that iterates through each property and asserts that it has a value assigned.

Example 1 - Object.keys
This example is incorrect because Object.keys only iterates through the already assigned properties, ignoring the non-set properties (and thus always is positive):

public static AssertAllPropertiesAreAssigned(target: object): void {
    Object.keys(target).forEach((key, index) => {
        expect(target[key]).toBeDefined();
});

Example 2 - Object.getOwnPropertyNames()
The same as example 1:

public static AssertAllPropertiesAreAssigned(target: object): void {
    Object.getOwnPropertyNames(target).forEach((name, index) => {
        expect(target[name]).toBeDefined();
});

Example 3 - Set default values
By assigning a default value to each poco, like null, I can make the earlier samples work. But I'd sure like to avoid that at all cost:

export class Foo {
    public id: number = null;
    public name: string = null;
    public when: Date = null;
}

The question: is there a way to create a helper that asserts that each property of my TypeScript poco object is actually assigned a value, in my test? Or, as an alternative, does Jest have some util for this?

There are similar questions on SO, but they are not related to asserting the values in a test. This makes this question, as far as I've looked around, differ from the others:

Also, I'm aware that the Javascript compiled output of my poco will probably leads to that the unset properties are simply not available:

var Foo = (function() {
    // nothing here...
}());

But with TypeScript's strong typing power and recent changes and/or Jest helpers, there might be some additional options to get this done?





How to run GetMethod.Invoke ? I got error

System.Reflection.TargetException: Object does not match target type.

public class Parameter : BaseEntity
{
    public string Key { get; set; }
    public string Value { get; set; }

    public override void Map(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Parameter>(opt =>
        {
            opt.ToTable("Parameter");
            opt.HasKey(x => x.Id);
            opt.Property(x => x.AutoId).UseSqlServerIdentityColumn();
            opt.HasAlternateKey(x => x.AutoId);
        });
    }
}


public class DataContext<T> : DbContext where T : BaseEntity
{
    private string _connectionString;

    public DataContext(string connectionString)
    {
        _connectionString = connectionString;
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        Type t = typeof(T);
        t.GetMethod("Map").Invoke(this, new object[] { modelBuilder }); // this line *****
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder.UseSqlServer(_connectionString);

}

T is called as Parameter class. And (// this line *****) side gives me error.

System.Reflection.TargetException: Object does not match target type.

How can i run this ?





vendredi 25 août 2017

Clear/add to a properties/fields on an object whose type is ICollection

Let's say I have a simple class like so:

public class SimpleClass
{
    public List<SomeOtherClass> ListOfStuff { get; } = new List<SomeOtherClass>();
}

SimpleClass itself is unimportant, let's say I've interrogated the type and determined it's of interest for some reason, so all I have is the System.Type object. Now say that I want to access any non static properties/fields on the class that implement ICollection<T> (i.e. ListOfStuff on SimpleClass). I can access/create instances of SimpleClass and I can also dynamically create instances of whatever the collection is made of, but how do I dynamically (and as efficiently as possible) clear or add items to ListOfStuff.

Basically I want to be able to create delegates that I can call later that I can pass an instance of the interested type to, and the method will clear a specific property/field on a class, and then similarly I want another which I can also pass a instance of the collection's item to (e.g. SomeOtherClass), and it will add it to the collection on the property.

I have the System.Type of the class I'm interested in, I have the PropertyInfo/FieldInfo of the field(s) I'm interested in, and I can create instances of the class and the item used in the collection.

e.g. (this is not real code!)

Type type = typeof(SimpleClass);
...
// CreateNew is a method that somehow returns a new instance of a type
object test = CreateNew(type);

// GetCollections somehow returns properties/fields that implement ICollection<>
foreach(var collection in GetCollections(type))
{
    // CreateNewCollection somehow returns a new instance of the item used in the collection
    object newItem = CreateNewCollectionItem(collection);

    // how do I implement these two lines?
    var clear = Delegate.CreateDelegate(...);
    var add = Delegate.CreateDelegate(...);
    ...
    clear(test);
    add(test, newItem);
}

How can I make these delegates?





Getting info about inheritance chain in Crystal

Just out of curiosity and to learn a little bit about the general structure of Crystal, I was looking for some reflection features that would allow me to better understand how the inheritance chain is built.

I was thinking something like ruby's superclass, ancestors or included_modules methods.

Is there something like that available in Crystal language?

Moreover, it would be useful to have some kind of diagram that could show me the big picture.





Calling Class By Name or Select Case?

VB.NET, but C# would also do.

I have a MustInherit base class and 170 inherited classes based on that. Why so many? Because each inherited class does something different in Sub New(). The inherited types do not add any new properties, but do have different private fields. They simply process different sets of known variables differently. So think like this:

Public MustInherit Class Base
     Public Property Width
End Class

Public Class Child1
     Inherits Base
     Private z as Integer = 7
     Public Sub New(x as integer)
           Width = 20 * x * 7
     End Sub
End Class

Public Class Child170
     Inherits Base
     Private y as Integer = 4
     Public Sub New(x as integer)
           Width = 5 * x / y
     End Sub
End Class

In reality, what's in the Sub New is a ton of processing instructions based on what is sent in (e.g. X as Integer). Those processing instructions will work with a large number of private variables that sit in the inherited class.

Also, I'll know which child I need to create based on a string variable that is named the same thing like child1 or child170.

So, with so many inherited children, what's the best approach here (fastest, shortest amount to write, best performance, etc.)

Options:

  1. Use a Select Case to call and create one of 170 different classes, like:

    Dim b as Base Select Case childName Case "child1" b = New Child1(x) Case "child74" b = New Child74(x) Case "child103" b = New Child103(x) End Select

  2. Somehow reflect my call to create a generic one (pseudo as I don't know much about this):

    Dim b as Base = Activator.CreateInstance(Type.GetType("MyProjectName" & childName)) wherein "childName" is one of 170 children and then b.Process(x) - this assumes I use a routine called Process as I haven't seen any examples of sending values in a constructor in the CreateInstance thing.

  3. Something else?

Any help/advice/best practice would be welcome (except those that say "why do you need 170 thing? don't use 170 things").





Reflection - Getting New Instance of unknown classes with unknown number of constructor parameters

First of all, I am new to Reflection. I have been working on a large project and I needed to use reflection on some parts (Yes I definitely need it). So I thought, I should create a Reflection Helper class which will be able to create new instances of any class with any number of parameters within my project.

As an example to my question: Normally(as far as I know), to create an instance of a class which has 2 strings as parameters in its constructor;

Class.getConstructor(String.class, String.class).newInstance("Arg_1", "Args_2");

will do the job. However, in my case I need a method which will work for any class with any constructor. So I created these methods but it doesn't seem to work, I keep getting NoSuchMethodException. I need help at making it work.

private static String packagePrefix = "com.***";

@SuppressWarnings("rawtypes")
public static Class getClass(String className) throws ClassNotFoundException {
    return Class.forName(packagePrefix + "." + className);
}

@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object getClassInstance(String className, Object... args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
    Class[] cArgs = new Class[args.length];
    for (int i = 0; i < args.length; i++) {
        cArgs[i] = args[i].getClass();
    }
    return getClass(className).getConstructor(cArgs).newInstance(args);
}





ios - Objective - C.. insert a new line of code in a method during runtime

I wanted to add a set of codes in a existing method during runtime in Objective C. Is this possible in Objective C??? I checked for reflection in Objective C. But it has features to add a class, add a method and also modify the method selector during RunTime. But I just want to insert a set of code during runtime.





Clarification about how reflection works internally

As stated in the title i need some clarification about how reflectoin works internally. I doesn't need deep detail about implementation but only an overview of how that mechanism works bheind the scene.

So far i have imagined that all object in the memory is more or less like an XML (sure with a complete different structure and syntax but the concept is the same) with a structure that describe the object and some datas. So in my view reflection is a tool to read and manipulate this object representation (conceptually xml-like).

Recently i have worked in a project where i have two dll, the first dll (i call it A.dll) with some base types (i use BaseA when i refer to them); the second dll (i call it B.dll) with some derived types (i call them DerivedBFromA because all the type here are derived from some BaseA). My project reference's chain is that A.dll does not reference nothing (except some system libraries) and B.dll has a reference to A.dll (and other system libraries).

When i debug the project i can see (using immediate window) every DerivedBFromA object's istantiated and right described by reflection. But opposite to what i'm expecting that is true until the scope is inside B.dll, when the scope goes down to A.dll i can't see the original structure of my object neither with reflection (i see only the strucutre of the corresponding BaseA).

So i start supposing that the object description (that reflection use to read structure and manipulate datas) is not attached to object instance (as i image in my XML-like model of reflection mechanism) but instead objects contains only datas and somewhere typedescriptors (detached from object and stored in dlls) contains only structure description.

For those reason i would like to ask you if somebody could give to me more detail about reflection, so that i can make that topic more clear to me.





Cast object to generic list where type T taken from variable

var typeArgument = Type.GetType(mapping.TypeName);
var method = _dbAccessor.GetType()
                            .GetMethod("GetViewData")
                            .MakeGenericMethod(new Type[] { typeArgument });
var viewData = method.Invoke(_dbAccessor, new object[] { mapping.SourceName });

GetViewData is generic method. It get string data by mapping.SourceName, deserializes to List of typeArgument and returns List. viewData has type "object". But I know that viewData is List of objects of type "typeArgument". So how could i cast object to List to allow iteration by foreach for var viewData?





C# reflection - can't check nested base type

I have a problem with checking if in the inheritance of my class, the inherited class implements some interface

public interface IUserClass : IBaseInterface<T, K> { }
public class UserClass : BaseClass<A, B>, IUserClass { }

and I check

typeof(UserClass).IsAssignableFrom(typeof(IBaseInterface <,>))

and I get false. Even if I do

typeof(UserClass).IsSubclassOf(typeof(BaseClass<,>))

i get the same result Why ?





How to get the interface Methodinfo, based on concrete implementation's MethodInfo?

I have an interface IClass:

public interface IClass
{
    [MyAttribute]
    int Hello();

    [MyAttribute]
    int Farewell();
}

And an implementation Class1:

public class Class1 IClass
{
    public int Hello() { Console.WriteLine("Hi there") };

    int IClass.Farewell() { Console.WriteLine("Goodbye!") };
}

I have a handle on Class1's MethodInfo's for Hello() and IClass.Farewell() by means of interception, but I need to find the MethodInfo of the interface definition in order to discover the usage of the attribute MyAttribute; something like this:

MethodInfo mi = context.Descriptior.CurrentMethod;
MethodInfo imi = GetInterfaceMethodInfo(mi) // ???
var mas = GetCustomAttributes<MyAttribute>();
if (mas.Count > 0)
{
    // Profit!
}





C#: creating partial functions dynamicly

I have a 3rd party scripting engine contained in a session in my code. The engine takes any delegate and makes it available to it's script with the same signature.

Now i want to have plugins that provide these delegates for the engine, but I also want extra data from the session without it showing up in the script.

The script consuming the delegate should have no idea about the session, but the plugin implementing it does. The plugin writer should be free to use any number or types of arguments for the plugin delegates, so i need to do this dynamically at run time.

For example:

//from available plugin delegates
delegate bool SendMessage(Session info, string ip, int port, string message);
delegate void LogMessage(Session info, string message);

//to create script delegates
delegate bool SendMessage(string ip, int port, string message);
delegate void LogMessage(string message);

So when the script engine calls LogMessage("Test") it should invoke LogMessage(mysession, "Test") in the plugin.

I found information on curry for adding defaults to delegates and Reflection could create the delegates, but how can they be fit together to accomplish this?





jeudi 24 août 2017

Validation: Fluentvalidation vs. Reflection - best practise / performance

I have an inventory application that uses an agent installed on a computer to read some information and pass it on to the server for further processing. Also, it will be stored in a database.

Now I wonder about validation of that information (like the name of the computer, operating system, installed software etc).

I do want to prevalidate the data on the agent side to avoid sending data to the server that might harm the database or the later processing classes and cause errors. Of course, I will validate the data on the server side as well, to prevent anyone from sending harmful code to the server. Thus, I don't need a super exact validation on the agent.

Also, to know about validation errors, the data has to be sent to the server in some way anyhow, but I wanted to be sure that I know about that and so can process it differently in the first place. My plan was to send it to the server who just stores it in a log file for further analysis.

I stumbled onto reflection and found that I can use a short piece of code in the marked answer to just validate all integers, strings etc against a regex:

Automate the validation process on properties using FluentValidation Library

public class Validator<T> : AbstractValidator<T>
{
public Validator(Func<PropertyInfo, bool> filter) {
    foreach (var propertyInfo in typeof(T)
        .GetProperties()
        .Where(filter)) {
        var expression = CreateExpression(propertyInfo);
        RuleFor(expression).NotEmpty();
    }
}

private Expression<Func<T, object>> CreateExpression(PropertyInfo propertyInfo) {
    var parameter = Expression.Parameter(typeof(T), "x");
    var property = Expression.Property(parameter, propertyInfo);
    var conversion = Expression.Convert(property, typeof(object));
    var lambda = Expression.Lambda<Func<T, object>>(conversion, parameter);

    return lambda;
}
}

And it can be used as such:

private static void ConfigAndTestFluent()
{
    CustomerDto customer = new CustomerDto();
    Validator<CustomerDto> validator = new Validator<CustomerDto>(x=>x.Name!="Remarks"); //we specify here the matching filter for properties
    ValidationResult results = validator.Validate(customer);
}

I would use that with a differentiation for string/integers etc and be done. But I read that reflection is super slow and should be avoided if possible.

Following JeremySkinner's manual of FluentValidation I would do something as he shows here:

http://ift.tt/1PZO8ta

using FluentValidation;

public class CustomerValidator: AbstractValidator<Customer> {
  public CustomerValidator() {
    RuleFor(customer => customer.Surname).NotEmpty();
   RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please     specify a first name");
    RuleFor(customer => customer.Discount).NotEqual(0).When(customer =>     customer.HasDiscount);
RuleFor(customer => customer.Address).Length(20, 250);
RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
  }

  private bool BeAValidPostcode(string postcode) {
// custom postcode validating logic goes here
  }
    }

Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);

bool validationSucceeded = results.IsValid;
IList<ValidationFailure> failures = results.Errors;

And then iterate over every error, rechecking the property type and the rules that was applied to send that back to the server. The downside is that I have to do validation rules for every single property which I guess is the best practice but is also way more work.

I didn't find any explicit answers to this or maybe I just didn't understand it, so I'd like to ask for some input and help on what to do. Speed actually is not the problem, but I'd like to know what I am doing and what I might be sacrificing in doing so.

Hence, my questions:

  • What's the best practice for validation in my case?
  • Should I go the long route any validate each property separately?
  • Is there any other way of achieving the same goal that might work better?

Any help is greatly appreciated.

Thanks :)





How can I sent the type to function

I have this function

  public IList<TEntity> GetData<TEntity>() where TEntity : class
    {
        return _DbContext.Set<TEntity>().ToList();
    }

and I call this function like this

GetData<View_Export_Books>()

So now I have to load the class View_Export_Books dynamically from a string. Is this possible?

Thanks for any help.





C# Entity Framework load dynamically view into the context

I have a foreach which will call severel views, and i try to laod this views dynamically into the dbContext of entity framework.

What I have so fare is :

var context = new DbContext();
var type = Type.GetType($"XXX.XXXXXXX.XXXX.XXXXX.{exportItem.DataSourceView}, XXX.XXXXXXX.XXXX.XXXXX");
context.Set(type).Load();
var result = context.Set(type).AsQueryable().Cast<View_DataLoad>().ToList();

This works so far, but I have to Cast the result to the class which I set to the dbContext.

How can I add dynamically class to the cast function?

Or is there a better way to load dynamically query's to the entity framework?

Thanks for help.





mercredi 23 août 2017

Non-virtual method invocation using reflection

In Java, when working with java.lang.reflect.Method how can I invoke a function without it being a virtual call?

I.e. I want this code to print "good" instead of what it currently does, which is print "bad":

Foo.java:

public class Foo {
  public void doit() {
    System.out.println("good");
  }
}

Bar.java:

import java.lang.reflect.Method;

public class Bar extends Foo {
  public void doit() {
    System.out.println("bad");
  }

  public static void main(String[] args) throws Exception {
    Bar b = new Bar();
    /* Using Foo.class ought to do it right? */
    Method m = Foo.class.getDeclaredMethod("doit", new Class[]{});
    /* Surely if that didn't do it casting to Foo would? */
    m.invoke((Foo)b, new Object[]{});
  }
}

Nothing I do using reflection succeeds in printing "good".

My expectation was that using one or more of casting the first argument of invoke to Foo, and/or using Foo.class.getDeclaredMethod instead of Bar.class would be sufficient. Clearly I'm wrong about that, how can I get the desired behaviour still using reflection?





mardi 22 août 2017

C# Will reflection create multiple instance of a singleton in my assembly?

I am creating a c# based automated testing framework and have configuration files that link test case methods and class names to requirement IDs. The framework will create a TestPlan that is a list of multiple test cases that will executed one after another.

Since there are thousands of testcases (and more all the time) I want to call these classes and methods by reflection, but I am concerned that these methods will create singleton instances of supporting classes that will hang around after the method returns that won't be reused when the next test method is called by reflection.

My question is: will each call use the same static instance in the assembly? Or will each call create a new instance of the singleton? Without reflection in the mix it is a simple answer, but with it ... I am not certain.





How to find the instance in Java that called my static method so I can call methods on that instance? [duplicate]

This question already has an answer here:

I think what I need is AOP but I can't use AOP there. Need some neat workaround from a creative mind.

Problem is simple:

public class Hello {

    public void myMethod() {

        MyClass.myStaticMethod();

    }
}

public class MyClass {

    public static void myStaticMethod() {

        Object callerInstance = getTheInstanceWhoCalledMe();

        if (callerInstance instanceof Animal) {
            Animal a = (Animal) callerInstance;
            System.out.println(a.eat());
        }
    }

    public static Object getTheInstanceWhoCalledMe() {

        // ???????? Any creative genius out there?
    }
}





Recursively walk through nested structs

I want to build a method that takes a struct as an interface{} and returns true if any of the supplied struct's fields are nil.

Here's what I have at the moment:

// ContainsNil returns true if any fields within the supplied structure are nil.
//
// If the supplied object is not a struct, the method will panic.
// Nested structs are inspected recursively.
// Maps and slices are not inspected deeply. This may change.
func ContainsNil(obj interface{}) bool {
    if obj == nil {
        return true
    }
    s := reflect.Indirect(reflect.ValueOf(obj))
    for i := 0; i < s.NumField(); i++ {
        f := s.Type().Field(i)
        field := s.Field(i)
        if fieldIsExported(f) { // Exported-check must be evaluated first to avoid panic.
            if field.Kind() == reflect.Struct {
                if ContainsNil(field.Addr()) {
                    return true
                }
            } else {
                if field.IsNil() {
                    return true
                }
                if field.Interface() == nil {
                    return true
                }
            }
        }
    }
    return false
}

func fieldIsExported(field reflect.StructField) bool {
    log.Println(field.Name)
    return field.Name[0] >= 65 == true && field.Name[0] <= 90 == true
}

And a failing test:

func Test_ContainsNil_NilNestedValue_ReturnsTrue(t *testing.T) {
    someNestedStruct := &c.SomeNestedStruct{
        SomeStruct: c.SomeStruct{
            SomeString: nil,
        },
    }
    result := util.ContainsNil(someNestedStruct)
    assert.True(t, result)
}

The test code executes without panicking, but fails because the method returns false rather than true.

The issue I'm having is that I can't figure out how to properly pass the nested struct back into the recursive call to ContainsNil.

When recursive call is made for the nested structure, the fieldIsExported method returns false because it's not receiving the value that I would expect it to be receiving.

I expect fieldIsExported to receive "SomeStruct" on its first call, and receive "SomeString" on the second (recursive) call. The first call goes as expected, but on the second call, fieldIsExported receives "typ", when I would expect it to receive "SomeString".

I've done a bunch of research about using reflect on structs, but I haven't been able to get my head around this yet. Ideas?

References:





How do I get the name of the type currently held by an `any`?

Suppose I have either:

  1. A boost::any or
  2. An std::any (and I'm using C++17)

the type of which I don't know. Is it possible for me to print, or get as a string, the name of the type that's being held by the any?

Note: Even a mangled type name - the kind you get with typeid(TR).name() - would be sufficient I can take it from there using abi::__cxa_demangle.





Getting the JsonPropertyAttribute of a Property

I found a post with a great answer for a problem I have, but I can't seem to find a small detail I'm looking for.

public class myModel
{
   [JsonProperty(PropertyName = "id")]
   public long ID { get; set; }
   [JsonProperty(PropertyName = "some_string")]
   public string SomeString {get; set;} 
}

I need a method which returns the JsonProperty PropertyName of a specific property. Maybe something where I can pass the Type and the Property I need, and the method returns the value if found.

Here's the method I found which has me in the right direction (I believe) taken from here

using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
...

public static string GetFields(Type modelType)
{
    return string.Join(",",
        modelType.GetProperties()
                 .Select(p => p.GetCustomAttribute<JsonPropertyAttribute>()
                 .Where(jp => jp != null)
                 .Select(jp => jp.PropertyName));
}

The goal is to call a function like this (any modification is fine)

string field = GetField(myModel, myModel.ID);

Thanks!





Implementing a plugin architecture without split packages (Java Modules)

In a past question I asked how to design a system where:

  • A class contains one or more optional methods.
  • Optional methods are implemented by plugins that may or not may be present at compile-time.
  • If a user invokes a method whose associated plugin is not present at compile-time, they will get a compile-time error.

I provided one possible solution that works in Java 8.

Unfortunately, this solution depends on the use of split packages (two modules exporting the same package) which are disallowed by the Java 9 Module System.

How can this be implemented in Java 9?





Go: how to use reflection to replace imported variables and functions

Say I have a code snippet that should be covered with the unit-tests:

func selfIntroductionMessage(ctx context.Context, errorC chan error) *routing.Message {
    msg := &routing.Message{}
    if emissionTime, err := ptypes.TimestampProto(time.Now()); err != nil {
        select {
        case errorC <- fmt.Errorf("Couldn't convert time to google.protobuf.Timestamp: %v", err):
        case <-ctx.Done():
        }
        return nil
    } else {
        msg.EmissionTime = emissionTime
    }
    return msg
}

Hopefully ptypes.TimestampProto(time.Now()) will never fail under normal conditions, but since ptypes.TimestampProto always returns error return, it's worth checking it.

The common approach to solve this problem is to mock every dependency: time.Now() should be replaced with the function of same interface. But when one starts to mock standard library, application code quickly becomes ugly.

So I wonder if it's possible to replace time.Now() implementation to erroneous for unit-testing purposes using the reflect package.





How to Convert Types Using Reflection

Please consider this Code:

string propertyValue = "1";
PropertyInfo info = obj.GetType().GetProperty("MyProperty");
info.SetValue(detail, Convert.ChangeType(propertyValue, info.PropertyType), null);

The problem is type of info.PropertyType is System.Byte? and when the line 3 wants to be executed I got this Error:

"Invalid cast from 'System.String' to 'System.Nullable`1[[System.Byte, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'."}

How I resolve this problem?

Thanks





What's wrong with my code? No errors are showing yet it's not creating a folder

As you can see, part of my code entails it creating a directory/folder if it does not already exist. I've had this working before, but recently it just stopped working. Why is that? I'm using Visual Studio 2017. Thanks! (It won't let me post my question with mostly code, but I have nothing else to say so I'm typing here randomly. Please ignore.)

Here is my code:

using System;
using System.Threading;
using System.Reflection;
using System.IO;

namespace chrome
{
    static class Program
    {
        static void Main()
        {
            //-----this code will make your program to automatically execute as computer starts----
            try
            {
                Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                Assembly curAssembly = Assembly.GetExecutingAssembly();
                key.SetValue(curAssembly.GetName().Name, curAssembly.Location);
                Console.WriteLine(curAssembly.GetName());

            }
            catch { }
            //------------------

            //------------screenshot  loop takes screenshots after 1 min-----------
            int n = 0;
            while (n == 0)
            {
                try
                {
                    Thread.Sleep(2000);
                    OnTimedEvent();
                }
                catch { }
            }
            //-------------------------

        }// main body ends !

        public static string st = "";
        public static string date = "";
        public static string month = "";
        public static string year = "";
        public static string time = "";
        public static string hour = "";
        public static string min = "";
        public static string sec = "";


        private static void OnTimedEvent()
        {
            st = DateTime.Today.Date.ToString();
            time = DateTime.Now.TimeOfDay.ToString();

            hour = DateTime.Now.Hour.ToString();
            min = DateTime.Now.Minute.ToString();
            sec = DateTime.Now.Second.ToString();

            date = DateTime.Today.Day.ToString();
            month = DateTime.Today.Month.ToString();
            year = DateTime.Today.Year.ToString();

            Console.WriteLine("The Elapsed event was raised at {0}_{1}_{2} at time {3}_{4}_{5} ", date, month, year, hour, min, sec);

            Bitmap memoryImage;
            memoryImage = new Bitmap(1366, 768);
            Size s = new Size(memoryImage.Width, memoryImage.Height);

            // Create graphics
            Graphics memoryGraphics = Graphics.FromImage(memoryImage);
            // Copy data from screen
            memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
            string str = "";

            //------------creating directory--------
            if (Directory.Exists("C:\\Intel\\dsp"))
            {
                Console.WriteLine("directory exits");
            }
            else
            {
                Directory.CreateDirectory("C:\\Intel\\dsp");
                File.SetAttributes("C:\\Intel\\dsp", FileAttributes.Hidden);
                Console.WriteLine("new directory created");
            }
            //---------------------------------------

            str = string.Format("C:\\Intel\\dsp\\{0}_{1}.png", date + month + year, hour + min + sec);

            //------------

            try
            {
                memoryImage.Save(str);
            }
            catch (Exception er)
            {
                Console.WriteLine("Sorry, there was an error: " + er.Message);
            }
        }

        //---------------------------------------------------------

        internal class Graphics
        {
            internal static Graphics FromImage(Bitmap memoryImage)
            {
                throw new NotImplementedException();
            }

            internal void CopyFromScreen(int v1, int v2, int v3, int v4, Size s)
            {
                throw new NotImplementedException();
            }
        }

        internal class Size
        {
            private object width;
            private object height;

            public Size(object width, object height)
            {
                this.width = width;
                this.height = height;
            }
        }

        internal class Bitmap
        {
            private int v1;
            private int v2;

            public Bitmap(int v1, int v2)
            {
                this.v1 = v1;
                this.v2 = v2;
            }

            public object Width { get; internal set; }
            public object Height { get; internal set; }

            internal void Save(string str)
            {
                throw new NotImplementedException();
            }
        }
    }
}




lundi 21 août 2017

Reflection to walk every string property in class

I want to store user's input on my database. The user can write texts with html tags to style his texts.

I want to remove potential malware like javascript and so on. Instead of checking every string property in the class by hand, I want an object-extension which walks through every string property and replace potential malware...

My approach supports:

class TestClassStringProperties
{
    public TestClassStringProperties()
    {
        MyProp = "123";
    }

    public string MyProp { get; set; }
}

class TestClassNestedProperties
{
    public TestClassNestedProperties()
    {
        NestedType = new TestClassStringProperties();
        MyProp = "123";
    }

    public string MyProp { get; set; }
    public TestClassStringProperties NestedType { get; set; }
}

class TestWithCollectionOfNestedProperties
{
    public TestWithCollectionOfNestedProperties()
    {
        NestedPropertiesCollection = new List<TestClassStringProperties>();
    }

    public ICollection<TestClassStringProperties> NestedPropertiesCollection { get; set; }
}

But it fails with this:

class TestClassWithStringCollection
{
    public TestClassWithStringCollection()
    {
        Strings = new List<string> {"123", "123", "123", "123"};
    }

    public ICollection<string> Strings { get; set; }
}

Extensionmethod:

public static class ObjectExtension
{
    private static HashSet<int> _vistedNestedTypes;

    public static void SanitizeJavaScriptFromAllPublicStringProps(this  object obj)
    {
        _vistedNestedTypes = new HashSet<int>();
        Sanitize(obj);
    }

    private static void Sanitize(object obj)
    {
        var properties = obj.GetType()
            .GetProperties(BindingFlags.Public | BindingFlags.Instance);
        if (ProduceStackOverflow(obj))
            return;
        foreach (var property in properties)
        {
            CollectionBehaviour(obj, property);
            if (property.PropertyType.GetTypeInfo().IsClass)
                if (property.PropertyType == typeof(string))
                {
                    // If not writable then cannot null it; if not readable then cannot check it's value
                    if (!property.CanWrite || !property.CanRead)
                        continue;
                    var mget = property.GetGetMethod(false);
                    var mset = property.GetSetMethod(false);

                    // Get and set methods have to be public
                    if (mget == null || mset == null)
                        continue;
                    property.SetValue(obj, "HACKED"); // I remove evil code at this place...
                }
                else
                {
                    NestedTypeBehaviour(obj, property);
                }
        }
    }

    private static void NestedTypeBehaviour(object obj, PropertyInfo p)
    {
        var pp = p.GetValue(obj, null);
        if (pp != null && !_vistedNestedTypes.Contains(pp.GetHashCode()))
        {
            Sanitize(pp);
            _vistedNestedTypes.Add(pp.GetHashCode());
        }
    }

    private static void CollectionBehaviour(object obj, PropertyInfo p)
    {
        if (typeof(IEnumerable<object>).IsAssignableFrom(p.PropertyType))
        {
            var items = (IEnumerable) p.GetValue(obj, null);
            var enumerable = items as IList<object> ?? items.Cast<object>().ToList();
            var cnt = enumerable.Count;
            for (int i = 0; i < cnt; i++)
            {
                var a = enumerable[i];
                Sanitize(a);
                enumerable[i] = a;
            }
        }
    }

    private static bool ProduceStackOverflow(object obj)
    {
        if (!_vistedNestedTypes.Contains(obj.GetHashCode()))
        {
            _vistedNestedTypes.Add(obj.GetHashCode());
            return false;
        }
        return true;
    }
}

After executing the extension, my strings are "123" in the collection and not "HACKED" as I would expect.

Thank you in advance.





Using reflection with class library exported as nuget asp.net core

I created a class library in .net core and and hosted class library on my local nuget server.Class library contains controllers and some other classes to be used by reflection.

I consumed this class library in my asp.net core MVC project.By installing it as nuget refrence. Now my MVC project builds well but at runtime I am not able to find my contoller or other classes defined in class library.

weird behavior when I copy dll of my class library to my MVC projects bin\Debug\netcoreapp1.1 directory, reflection starts working.

this is happening when i run my application in debug mode on IIS Express and I am using .net core 1.1 on Visual studio 2015

Question: Is there a way to extract nuget packages in to bin\Debug\netcoreapp1.1 on build. Question: Do I need to added some configuration so that Reflection look for dll in respective nuget package location.





System.Runtime.Remoting.RemotingException invoking method of an external assembly

I'm playing with reflection and remoting for the first time. I have an assembly present on the machine, that I have read-only access to the source code of, and I want to invoke one of its methods directly. This is my code:

        AppDomain NewDomain = AppDomain.CreateDomain("NewDomain");
        try
        {
            var objectHandle = NewDomain.CreateInstanceFrom(@"C:\Program Files (x86)\xxx\ExistingAssembly.dll", "RemoteNamespace.RemoteClass");
            var localObject = (RemoteNamespace.ISharedInterface)objectHandle.Unwrap();
            File.Copy(localObject.StrTargetMethod(arg1),
                Path.Combine(logDir, logfile), true);
        }
        finally
        {
            AppDomain.Unload(NewDomain);
        }

At the first line of the try block, the CreateInstanceFrom method throws an UnhandledException: System.Runtime.Remoting.RemotingException: Cannot load type 'RemoteNamespace.RemoteClass, RemoteNamespace, Version=1.2.0.8, Culture=neutral, PublicKeyToken=xxxxxxxxxx'.

EDIT: I'm now trying this:

var assembly = Assembly.LoadFrom(@C:\Program Files (x86)\xxx\ExistingAssembly.dll");
var localObject = (ISharedInterface)assembly.CreateInstance("RemoteNamespace.RemoteClass");

but I'm getting the same error being thrown at assembly.CreateInstance().





How to extract the class JObject represent in json.net?

I'm deserializing a JSON string to a type that's not known in compile time, so I made use of the overloaded JsonConvert.DeserializeObject method in json.net library:

    public static object GetJsonType(string json, Type type)
    {
        var logObject = JsonConvert.DeserializeObject(json, type);
        return logObject;
    }

I call it like so:

Type jsonType = Type.GetType(log.JSONClassName); 
var obj = AuditHelper.GetJsonType(log.ObjectJson, jsonType);

and then I create an instance of a WPF window :

var formType = Type.GetType("DiERP." + log.FormName);
var form = Activator.CreateInstance(formType, obj);

and this is the constructor:

public FrmControlCenters(object jControlCenters)
{
    //can't cast it to the class it represent:
    //var ob = (JClsTbControlCenters)jControlCenters;

}

in this constructor I know the type of the jControlCenters , the problem is that I can't cast it to that type. I'm pretty know a little about the JObject (the type passed to the constructor) , but can't use it .. so my question how to get the type I want from it?





Error in dynamic mapping: Missing type mapping or unsupported mapping

I have a data data something like this:

Public class Columns
{
Public String ColumnSource {get; set;}
Public public string TargetDb {get; set;}
Public DbType Type {get; set;}
}

Public class Table
{
Public string Name {get; set;}
Public IList <Column> Columns {get; set;}
}


Var DictionariesData = new Table ();

I use the System.Reflection.Emit.TypeBuilder class to generate a type at run time.

Use Dapper to get the data without a database and generate a variable with the type of the table, for example:

Var result = connection.Query (typeof (classGerada), "select * from Table");

Now I'd like to do a mapping from classGenerated to ClassGenerated2, one difference of the two is once for two columns and all things as columns.

I'm trying to do this to use AutoMapper (it's not like doing in another library, I accept suggestion). I am using the following mapping:

AutoMapper.Mapper.Initialize (f => f.CreateMap (targetClass, sourceClass)
.ForMember ("Sequential", m => m.MapFrom ("TableId")));

When I run

Var resultMap = Mapper.Map (result, sourceClass);

I have the following error:

Map configuration of missing type or mapping not supported.

Mapping types: IEnumerable1 -> Type System.Collections.Generic.IEnumerable1 [[System.Object, mscorlib, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089]] -> System.Type

*sourceClass is the type generated at runtime from the data dictionary.

Does anyone know what's wrong? Or what would one do?





Type.GetType(typeName) as a generic type? [duplicate]

This question already has an answer here:

I need to build a function to return the deserialized object of a JSON string, the type name is stored in the database:

Type jsonType = Type.GetType(log.JSONClassName);

so I need to do something like this:

var obj = AuditHelper.GetJsonType<jsonType>(log.ObjectJson);

AuditHelper.GetJsonType method:

 public static T GetJsonType<T>(string json)
        {
            var logObject = JsonConvert.DeserializeObject<T>(json);
            return logObject;
        }





C# - Get Type by string without specifiying full namespace

Currently, when using Assembly.GetType(string typeName) I have to specify the full namespace name, so if I had a class called MyClass within a namespace - MyNamespace.CoolClasses, to use the Assembly.GetType method I would have to specify the full namespace before the class as follows: "MyNamespace.CoolClasses.MyClass".
I would like to know if there is an existing method similar to the one I mentioned where I don't need to specifiy the full namespace name. So, if we go back to my example, all I'd need to write to get the type is Assembly.GetType("MyClass")





dimanche 20 août 2017

Redirect input from annotation [duplicate]

This question already has an answer here:

Is there a way that I can give an annotation an method as an input. Then use the value returned from it to pass to the annotation ?

public String fnc(String value){

   //do something
   return ret;
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface MAnon{
    String cond = fnc(cond);
}

@MAnon(fnc("Something")) //does not work
@MAnon("Something")
public void foo(){ ... }

public void bar(){
    //reflection call
   MAnon a = ...getDeclaredAnnotations()[0]
   String foo = a; //may not be the same as what is typed
}





How can I pass the unknown type of an instance to a generic method?

I have a method with the signature:

public static void MyMethod<T>()

I want to call it passing the generic type of some arbitrary variable:

var myFoo = new Foo(); //I do not know that this is Foo
var genericType = ???; //What should I write here?
MyMethod<genericType>();

How can I pass the generics of an instance in a method?


What have I tried? A bunch of things. An example, of one that does not compile:

var genericType = myFoo.GetType();





How to call Action

In this example code i am trying to invoke a anonymous action from il generator. I am not sure if and how i can load the reference to the delegate and how to call it. I can do it if the OnFunctionCall is a static method not property.

public delegate void TestDelegate();

public static class ExampleOne
{
    public static Action<string, bool> OnFunctionCall
        => (message, flag) => Console.WriteLine("Example");
}

public static class ExampleTwo
{
    public static TType CreateDelegate<TType>(Action<string, bool> onFunctionCall)
        where TType : class
    {
        var method = new DynamicMethod($"{Guid.NewGuid()}", typeof(void), Type.EmptyTypes, typeof(TType), true);

        ILGenerator il = method.GetILGenerator();

        // loading the first string argument
        il.Emit(OpCodes.Ldstr, method.Name);

        // not sure here how to load boolean value to the stack
        il.Emit(OpCodes.Ldc_I4_0);

        // this line doesn't work
        // example two has no idea about ExampleOne
        // is it possible to load the reference of the Action<string, bool> to the stack and call it ?
        il.Emit(OpCodes.Call, onFunctionCall.Method);

        il.Emit(OpCodes.Ret);

        return method.CreateDelegate(typeof(TestDelegate)) as TType;
    }
}

public class Program
{
    public static void Main(string[] args)
        => ExampleTwo
            .CreateDelegate<TestDelegate>(ExampleOne.OnFunctionCall)
            .Invoke();
}





Mirroring method in C#

Is there any ways I could use, to mirror any method from another class? i.e.

public class MyMethods
{

    public static double Func_1
    {


    }
    public static double Func_2
    ....
    ....
    ....

}





public class Reflector
{
    // any call to this class, should be redirected to MyMethods
    public SOMETHING_AUTOLOADER_OR_LIKE_THAT{
        ...
    }

}

as i could call Reflector.Func_888(); , and if that method is not found there, then it should search in MyMethods and execute that.





Using Simple Injector to register lazy parameters by reflection

I register all implementations of IService interface in Simple Injector by Reflection:

var registrations = assembly.GetExportedTypes()
   .Where(type => type.IsClass && baseType.IsAssignableFrom(IService))
   .Select(type => new { Interface = type.GetInterfaces().First(), Implementation = type });

foreach (var reg in registrations)
{
    container.Register(reg.Interface, reg.Implementation, Lifestyle.Transient);
}

I found Lazy Register solution to registering one instance of an interface. But I want register all implementations in lazy mode by Reflection. my desired solution is:

foreach (var reg in registrations)
{
    container.Register(() => new Lazy<reg.Interface>(container.GetInstance<typeof(reg.Implementation) >), Lifestyle.Transient);
}

Is there any solution to the problem described?





samedi 19 août 2017

Accessing all fields from an instance using composition in Go?

I have a struct named Parent that is designed to be used in composition:

package main

import (
    "fmt"
    "reflect"
)

type Parent struct {
    Field1 int
}

func (p *Parent) Display() {
    t := reflect.TypeOf(p).Elem()
    for i := 0; i < t.NumField(); i++ {
        fmt.Println(t.Field(i).Name)
    }
}

type Child struct {
    Parent
    Field2 int
}

func main() {
    c := &Child{}
    c.Display()
}

I would like the parent to be able to access both Field1 and Field2 using reflection. For example, the code above will only output Field1 since the type of p is Parent.

Is there a way (using reflection) for Display() to determine that the Parent is part of a Child and display all of its fields as well? Unfortunately, I cannot perform a .(*Child) type assertion since many different types will be using Parent.





Sorting with Java 8 by Field given as Input

I have a REST endpoint and I want the UI to pass the field name that they want to sort their result by. 'id', 'name', etc. I came up with below, but was really trying to use Reflection / Generics so this could be expanded to encompass every object in my project.

I feel like this solution isn't easily maintainable if I want to have the same functionality for 100 different classes.

public static void sort(List<MovieDTO> collection, String field){

        if(collection == null || collection.size() < 1 || field == null || field.isEmpty()){
            return;
        }
        switch(field.trim().toLowerCase()){
        case "id": 
            collection.sort(Comparator.comparing(MovieDTO::getId));
            break;
        case "name": 
            collection.sort(Comparator.comparing(MovieDTO::getName));
            break;
        case "year": 
            collection.sort(Comparator.comparing(MovieDTO::getYear));
            break;
        case "rating": 
            collection.sort(Comparator.comparing(MovieDTO::getRating));
            break;
        default: 
            collection.sort(Comparator.comparing(MovieDTO::getId));
            break;
        }
    }

Any ideas on how I could implement this better so that it can be expanded to work for an enterprise application with little maintenance?





vendredi 18 août 2017

Can a WCF duplex service determine if the callback channel of a client has implemented a specific method before the service tries to call it?

I've implemented a WCF duplex service IMyDuplexService with a callback contract IMyCallbackContract.

It was deployed successfully; clients can subscribe to the service and the service can call methods on the client using the callback channel without issues.

I've since added a new method to the callback contract and it can also be deployed successfully; old clients can still subscribe to the service as well as new clients, the service can call the old methods on both the old and new clients using the callback channel, as well as new methods on the new clients without issues.

Is there any way to determine if a specific client is an old or new client without having to implement this "versioning" logic myself?

For example, if the client was implemented using the older version of the callback contract and the service tries to call the new method on the old client, the following exception is thrown: System.ServiceModel.ActionNotSupportedException occurred HResult=-2146233087 Message=The message with Action 'http://domain/virtual_directory/IMyDuplexService/MyNewMethod' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None). Source=mscorlib StackTrace: Server stack trace: at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter) at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at MyService.IMyCallbackContract.MyNewMethod()

Is it possible for the service to determine if the client supports the new method before trying to call it?

I tried to use reflection but the following doesn't return null on an older client: clientCallbackChannelInstance.GetType().GetMethod("MyNewMethod")

Is implementing my own "versioning" scheme the only way?

P.S. I don't need help architecting or implementing my own versioning scheme. I just don't want to "reinvent the wheel." ;)

Thank you.





Autofac WCF injection on reflection

I have N validators on my aplication but a client doesn't use all validators, I got by procedure all classes that my current client will need to instantiate.

My Business layer:

public class MyClass
{
    public void MyMethod(int idClient)
    {
        //This array is returned by a procedure passing idClient
        string[] validatorsName = { "ValidatorName", "ValidatorName2" };

        foreach (string name in validatorsName)
        {

            IValidator validator = (IValidator)Activator.CreateInstance(Type.GetType(name));
            //Error. I need pass the INameDB;

            validator.Process();
        }
    }
}

My Interface:

public interface IValidator
{
    void Process();
}

The Validators:

public class ValidatorName : IValidator
{
    INameDB nameDB;

    public ValidatorName(INameDB nameDB)
    {
        this.nameDB = nameDB;
    }

    public void Process()
    {
        nameDB.AnyThing(pedidoId);
    }
}

public class ValidatorName2 : IValidator
{
    INameDB2 nameDB;

    public ValidatorName(INameDB2 nameDB)
    {
        this.nameDB = nameDB;
    }

    public void Process()
    {
        nameDB.AnyThing2(pedidoId);
    }
}

public class ValidatorName3 : IValidator
{
    INameDB2 nameDB;

    public ValidatorName(INameDB2 nameDB)
    {
        this.nameDB = nameDB;
    }

    public void Process()
    {
        nameDB.AnyThing2(pedidoId);
    }
}

On Global, I could register all validators and with the IList<IValidator>, so I would remove from the list the validators that I will not need.

 string[] validatorsName = { "ValidatorName", "ValidatorName2" };
 validators = validators .Where(p => validatorsName .Contains(p.GetType().Name)).ToList();

but I have a lot of classes, it would register this no need.

My Global:

public class Global : System.Web.HttpApplication
{

    protected void Application_Start(object sender, EventArgs e)
    {
        ContainerBuilder builder = new ContainerBuilder();
        builder.RegisterType<NameDB>().As<INameDB>();
        builder.RegisterType<NameDB2>().As<INameDB2>();

        //builder.RegisterType<ValidatorName1>().As<IValidator>();
        //builder.RegisterType<ValidatorName2>().As<IValidator>();
        //builder.RegisterType<ValidatorName3>().As<IValidator>();

        AutofacHostFactory.Container = builder.Build();
        //AutofacHostFactory.Container.Resolve<IList<IValidator>>();
    }
}

My question is how can I detect the interface INameDB or INameDB2, get the instance on Autofac and use on Activator.CreateInstance?

Thanks.





Performance of Invokemethod

void ExecuteMethodViaReflection(TestObj comm)
{
    var paramNames = comm.paramNames; //of type string array
    var paramData = comm.Data; //of type Object array

    Type t = this.GetType();
    t.InvokeMember(comm.Method, BindingFlags.InvokeMethod, null, this, paramData, null, null, paramNames);
    }

I use above method to invoke method using reflection. I call same method multiple times. Performance of this not great when compared to normal method invocation. Is there a better way i can do to improve performance.





Elegant Reflection Framework in .NET

Is there any open-source C# project available as a replacement for reflection providing an abstraction layer for ease of use and is also effective and useful in terms of performance and working.

I was searching on the web and found many such frameworks, e.g.

But no time to evaluate, so seeking some quick expert opinion on this. My goal is to replace many of the extension methods that I have defined to ease the reflection usage as shown below:

    public static Array CreateArrayInstance(this PropertyInfo propInfo, int length)
    {
        if (propInfo.PropertyType.IsArray)
        {
            var arrayType = propInfo.PropertyType.GetElementType();
            return Array.CreateInstance(arrayType, length);
        }
        return null;
    }

    public static IList CreateGenericListInstance(this PropertyInfo propInfo)
    {
        var type = propInfo.PropertyType.GenericTypeArguments[0];
        var listType = typeof(List<>).MakeGenericType(type);
        var listInstance = (IList)Activator.CreateInstance(listType);
        return listInstance;
    }

OR suggest some good and smart approach to handle instead of creating so many scattered extension methods.