dimanche 31 mai 2020

golang get value from nested interface

I have a small problem while trying to dynamically read string from my db using odbc and no ORM.

maybe it's worth mentioning that with another SQL server driver I receive the data as string and not []uint8 which solving my problem).

I'm using the following code to scan a row into slice array:

func createEmptyResultSet(numOfCols int) []interface{} {
res := make([]interface{}, numOfCols)
for col := 0; col < numOfCols; col++ {
    var i interface{}
    res[col] = &i
}
return res

} and the actual scan:

func rowsToStringInterfaceMapSlice(rows *sql.Rows, cols []string) ([]map[string]interface{}, error) {
    var err error
    rowsRes := make([]map[string]interface{}, 0)
    numOfCols := len(cols)
    for rows.Next() {
        row := make(map[string]interface{}, numOfCols)
        values := createEmptyResultSet( numOfCols)
        if rows.Scan(values...); err != nil {
            return nil, err
        }
        rowsRes = append(rowsRes, row)
    }
    return rowsRes, nil
}

I'm trying to access the following slice:

enter image description here

using few versions of the following code:

  for i := range values {
//also tried multiple get value
                t := reflect.TypeOf(values[i])
                if t.Kind() == reflect.Slice {
                    row[cols[i]] = interfaceSliceToString(values[i])
                } else {
                    row[cols[i]] = values[i]
                }
            }

but nothing seems to work. any suggestions?





How can I get enum's field value using reflection?

Given an enum

    public enum Country {
      INDIA("New Delhi"),
      US("Washinton DC");

      private String capital;
      private Country(String capital) {
       this.captital = capital;
      }

      // getters & setters

}

How can I get the field values, given the fieldName "capital" and Country.class using reflection?





samedi 30 mai 2020

How to cast an object to Type?

I want to cast an object to a type that a System.Type object defines. I only know the object and the Type as inputs, I can't add type parameters.

void Test()
{
    object obj = 3;
    Type type = typeof(int);

    int number = Cast(obj, type);

    Console.WriteLine($"{number}, {number.GetType()}"); // Should output "3, System.Int32"
}

I can't change the inputs
??? Cast(object obj, Type type)
{
    // return the obj casted to type, but how?
}

I guess there's a way to solve it using reflection but I couldn't find anything like this.





Referencing packages in java without using String

Is there a way to reference a package in java in code without using a String?

Let me explain myself:

I've a function that fetches all object contained in a package, but I've to reference that package using a String, lets say "com.google.guava". This works, however, If I change the package name, the IDE is not able to automatically refractor the references, or if the package is external and dissapears after a major version change it is not detected at compile time.

With classes, I'd use a Class object directly when possible or Class#getName if what I need is a String representing the FQDN of the class, but I don't know if there's a way to do so with packages.

Sometimes I just do

Class<?> clazz = Foo.class;
Package p = clazz.getPackage();

This is more a curiosity than a real issue, I usually just reference by String and write a junit test in order to detect nom-existant packages used this way





vendredi 29 mai 2020

vb.net Is this reflection

I am building an app and I would like to read various properties from a file and dynamically create classes for them. The object being to use one set of basic code and change a target by selecting the file to create the classes to operate on. I hope I am defining my objective properly. I can bone up on reflection if I need to, I just don't want to fly off on a fruitless tangent. Is C# as better platform for this?

Thanks

Dean Geary





Using a struct as advanced enum type and attempting to access the properties by index

I followed this guide on making a more complicated enum type for my implementation. http://www.huristic.co/blog/2018/1/30/c-advanced-enum-value-types

So far so good, however now I need to access the struct properties I have made ideally by index. A use case is if I get in a list of integers, I want to be able to provide a list of strings with the seasons in, e.g. {1,4,7} would get me {"Winter", "Spring", "Summer"} for example.

So in effect, using this example, I would like to be able to select Month where the index is 7 for example and get out the season of "Summer".

My first step was to get the names like so:

IEnumerable<string> names = typeof(Month).GetProperties(BindingFlags.Static | BindingFlags.Public)
.Select(x => x.Name);

I then attempted to get the particular Month with:

foreach(string name in names) { 
  Month m = (Month) typeof(Month).GetType().GetProperties()
  .Single(info => info.Name == name)
  .GetValue(typeof(Month),null);
}

however this is going to cause me to iterate over the entire collection for every value I want to get.

Ultimately I think I'm headed in the wrong direction and would really appreciate a pointer. At the moment I'm trying to do this in a method in another class, but don't see why it couldn't be a getter in the struct itself, although that may be complicated given the binding attributes in use.





How can I load a component with dependencies to System.Data.Odbc via reflection?

I've encounted a problem with my application where I had to load a component with dependencies to System.Data.Odbc.

In this repository I reproduced my issue, maybe someone has an idea what I could do.

https://gitlab.com/christian.decker/system_data_odbc_problems

In the .NET-Framework context everything works just fine, it must be an issue with .NET Core.

Greets, Christian





jeudi 28 mai 2020

How can I capture the name of a variable still to be assigned in R?

Note: This is separate from, though perhaps similar to, the deparse-substitute trick of attaining the name of a passed argument.

Consider the following situation: I have some function to be called, and the return value is to be assigned to some variable, say x. Inside the function, how can I capture that the name to be assigned to the returned value is x?

For example:

nameCapture <- function() {
    # arbitrary code
    captureVarName()
    }

x <- nameCapture()
x
## should return some reference to the name "x"

What in R closest approximates captureVarName() referenced in the example? My intuition was that there would be something in the call stack to do with assign(), where x would be an argument and could be extracted, but sys.call() yielded nothing of the sort; does it then occur internally, and if so, what is a sensible way to attain something like captureVarName()?





Assembly reflection problem in Release mode

I'm facing some weird behaviour trying to get the parent assembly in some logging class (only when it's compiled in Release mode).

In Debug mode this works like a charm:

            StackFrame[] frames = new StackTrace().GetFrames();
            var assemblies = (from f in frames
                              select f.GetMethod().ReflectedType.Assembly)
                                    .Distinct()
                                    .Last();

Example: assembly A => assembly B => method

when I run the above script in debug mode I get assembly A (as expected) but when it runs in release mode I get: mscorlib instead. but the most weird thing is that if a check for the whole assemblies stack there is not a single reference of assembly A. how is this possible? what can be happening?

PS: assembly A is a webapp project.





Is type(obj) always equal to obj.__class__ in python?

As the question says, does

type(obj) == obj.__class__

always hold true?

Or there may be cases in which this is not true?





SimpleInjector Lazy in a Reflection

We are using SimpleInjector as a Dependency Injector, and we are registering all interface types using assembly iteration.

public static void RegisterInterfaceTypes(this Container container, Assembly assembly)
{
    assembly.GetExportedTypes()
        .Select(t => new {
            Type = t,
            Interface = t.GetInterfaces().FirstOrDefault()
        })
        .ToList()
        .ForEach(t =>
        {
            container.Register(t.Interface, t.Type, Lifestyle.Transient);
        });
}

We also have lazy classes to register. We can register these classes like below one by one. But we want to register all lazy types with similar iteration using reflection.

container.Register(() => new Lazy<ICommonBusiness>(container.GetInstance<CommonBusiness>));




mercredi 27 mai 2020

Type.GetProperties(bindingFlags) is not giving fields from parent classes

I am trying to list all the properties in the type as shown below.

I am loading the DLL file using Assembly.LoadFile(dllFilePath).

Getting all properties in assembly using assembly.GetTypes().ToList().

Classes:

public class A
{
    public int Property1 { get; set; }
    public int Property2 { get; set; }
    public int Property3 { get; set; }
    public int Property4 { get; set; }
}

public class B : A
{
    public int Property5 { get; set; }
}

Methods:

static void Main()
{
    Assembly assembly = Assembly.LoadFile(dllFilePath);
    List<Type> types = assembly.GetTypes().ToList();
    GetAllProperties(typeof(types.FirstOrDefult(a => a.Name == "B")));
}

private void GetAllProperties(Type type)
{
    BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic
        | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Static
        | BindingFlags.FlattenHierarchy;

    // Test 1: No inherited properties.
    PropertyInfo[] propertyInfoList1 = type.GetProperties(bindingFlags);

    List<string> propertyNameList1 = new List<string>();
    foreach (PropertyInfo propertyInfo1 in propertyInfoList1)
    {
        propertyNameList1.Add(propertyInfo1.Name);
    }

    // Test 2: No inherited properties.
    PropertyInfo[] propertyInfoList2 = Activator.CreateInstance(type).GetType().GetProperties(bindingFlags);

    List<string> propertyNameList2 = new List<string>();
    foreach (PropertyInfo propertyInfo2 in propertyInfoList2)
    {
        propertyNameList2.Add(propertyInfo2.Name);
    }

    // Test 3: object has all inherited properties but propertyInfoList doesn't have inherited properties.
    object typeInstance = Activator.CreateInstance(type);
    PropertyInfo[] propertyInfoList3 = typeInstance.GetType().GetProperties(bindingFlags);

    List<string> propertyNameList3 = new List<string>();
    foreach (PropertyInfo propertyInfo3 in propertyInfoList3)
    {
        propertyNameList3.Add(propertyInfo3.Name);
    }
}

In Test 3 all parent class properties are visible when I inspect it.

But typeInstance.GetType().GetProperties(bindingFlags) doesn't return all parent class properties.





How to find out the generic type passed to the parent

Tell me please how you can determine the type that was passed to the parameter generics during inheritance

public abstract class BaseEntity 
{
}

public class DogEntity : BaseEntity
{
}

public interface IAnimal
{
}

public abstract class Animal<TEntity> : IAnimal
    where TEntity : BaseEntity
{
}

public class Dog : Animal<DogEntity>
{
}

I have only Dog entity type, I need to get DogEntity

Type type = typeof(Dog);

I would be grateful for any help or hint





How can I show an enum like the Visual Studio tooltip?

I have the following class:

Public Class PetClass

    Public Enum Animal
         Bird = 1
         Dog = 2
         Cat = 3
    End Enum

    Public MyPetType As Animal = Animal.Cat

    (...)
End Class

When I move the mouse over MyPetType, VS shows the following:

enter image description here

I would like to print this using Debug.

I'm using the following code to do this:

<Extension()>
Public Function Description(ByVal EnumConstant As [Enum]) As String
    Dim fi As Reflection.FieldInfo = EnumConstant.GetType().GetField(EnumConstant.ToString())
    Dim aattr() As DescriptionAttribute = DirectCast(fi.GetCustomAttributes(GetType(DescriptionAttribute), False), DescriptionAttribute())
    If aattr.Length > 0 Then
        Return aattr(0).Description
    Else
        Return EnumConstant.ToString()
    End If
End Function

Then I use it like this:

Dim n As New PetClass
Debug.Print(Description(n.MyPetType))

The output is "Cat".

When I debug the function and hover the mouse over the last line, it shows exactely what I want to output:

enter image description here

However, the results of the function is "Cat" and not "Cat {3}".

How could I make it output "Cat {3}"?





mardi 26 mai 2020

Is reflection deterministic?

When i look i.e: for all types in an assembly implementing some interface using reflection, will the order of returned types always be the same or they can be returned in any order during different runs?





C# - Reflection.Emit : Return result of called method

In a DynamicMethod I try to call a method that wants an array of objects to return the length of the given array. Currently, my method which should be called from the DynamicMethod looks like the following:

public static int Test(Object[] args)
{
    Console.WriteLine(args.Length);
    return args.Length;
}

The creation process of the DynamicMethod looks like the following:

(The creation of the Object array is adopted from the following SO answer)

public static DynamicMethod GetDM()
{ 
    var returnType = typeof(int);
    var paramTypes = new Type[]{typeof(string), typeof(bool)};

    var method = new DynamicMethod(
        "",
        returnType,
        paramTypes,
        false
    );
    var il = method.GetILGenerator();

    // Save parameters in an object array
    il.Emit(OpCodes.Ldc_I4_S, paramTypes.Length);
    il.Emit(OpCodes.Newarr, typeof(Object));
    il.Emit(OpCodes.Dup);

    for (int i = 0; i < paramTypes.Length; i++)
    {
        Type type = paramTypes[i];

        il.Emit(OpCodes.Ldc_I4, i);
        il.Emit(OpCodes.Ldarg, i);
        if (type.IsValueType) { il.Emit(OpCodes.Box, type); }
        il.Emit(OpCodes.Stelem_Ref);
        il.Emit(OpCodes.Dup);
    }

    // Call method and get the length of the array
    // How do I return the result of the called method?
    var callMethod = typeof(Program).GetMethod("Test", (BindingFlags)(-1));
    il.Emit(OpCodes.Call, callMethod);

    il.Emit(OpCodes.Ret);

    return method;
}

With the following method I check the functionality:

public static void Main(string[] args)
{
    var method = GetDM();
    var result = method.Invoke(null, new Object[]{"Test 1234", true});
    Console.WriteLine(result); // Should be 2
}

When I run the main method I get the System.Reflection.TargetInvocationException. Can someone help me out how to return the value which was returned by the called method? Here is a link to a dotnetfiddle to see my problem in action.





How to resolve generic method ambiguity in C# reflection

I have two generic method overrides, that differ by the number of generic type parameters and argument type

// Argument types
public class Bar<T> {}
public class Bar<T, U> {}

// Generic method overrides
private static void Foo<T> (Bar<T> b) {}
private static void Foo<T, U> (Bar<T, U> b) {}

I'm assuming that i can get the method info for either one by using the appropriate number of type parameters

BindingFlags Flags = BindingFlags.NonPublic | BindingFlags.Static;

// Should give Foo<int>
GetType ().GetMethod ("Foo", Flags).MakeGenericMethod (typeof(int));

// Should give Foo<int, int>
GetType ().GetMethod ("Foo", Flags | BindingFlags.Static).MakeGenericMethod (typeof(int), typeof(int));

However this fails with System.Reflection.AmbiguousMatchException.

I tried specifying things like new Type[] {typeof (Bar<,>)} as the types argument for some of the GetMethod overrides, but the result was always null. I know i can workaround the ambiguity simply by using different names for the functions, but i'm interested to know if there's an actual solution to this.

I'm on .NET standard 2.0





How to load a class from the source code using reflection inside SBT task?

I'm using SBT to build my project. I want to analyze some classes from my source code using either Scala or Java reflection during the build process.

How do I define an SBT task that loads a single known class or all classes from my source code?

import sbt._

val loadedClasses = taskKey[Seq[Class[_]]]("All classes from the source")

val classToLoad = settingKey[String]("Scala class name to load")
val loadedClass = taskKey[Seq[Class[_]]]("Loaded classToLoad")




Passing an unknown datatype parameter in C#

My main program is reading a spreadsheet via another class, which knows nothing about the schema of (i.e. data types within) the spreadsheet. My approach is to define a spreadsheetRecord that defines these data types and pass that record as either a class or struct into the class being called to do this spreadsheet read.

The problem is the C# compiler gripes it can't implicitly convert main's SpreadsheetRecord datatype with the one known to the class being called. Of course it can't because the destination class knows nothing about this datatype. So how should the schema for the spreadsheet be passed to the class routine that's responsible for reading and saving the spreadsheet data?

void class Main
{
    public class SpreadsheetRecord
    {
        public double volAvg;
        public double volOvr10;
        public double sumScore;
    }

    static string[] sheetHeads = { "Volume (10 Day Avg)", "Volume (Today/Avg 10 Day)",
            "Equity Summary Score from StarMine from Refinitiv" };

    SpreadsheetData sheetDat = new SpreadsheetData(new SpreadsheetRecord(), sheetHeads);
    ...
}


public class SpreadsheetData //SpreadsheetData parses an "unknown" spreadsheet.xls file
{
    public Dictionary<string, Record> SheetDB { get; private set; } //declaration of database
    public class Record { };  //schema for incoming spreadsheet data record

    public SpreadsheetData(Record schemaRecord, string[] recordHeadings) //constructor read in spreadsheet
    {
        ...
        using (IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(sheetInputFile.OpenRead()))
        {...
            FieldInfo[] recordFieldInfo = typeof(Record).GetFields();
            for (int i = 1; i < result.Tables[0].Rows.Count; i++)
            {
                for (int j = 0; j < recordHeadings.Length; j++)
                    recordFieldInfo[j].SetValue(schemaRecord, sheet1.Rows[i][Column2RecordCrossIndx[j]]);
                SheetDB.Add(sheet1.Rows[i][indxOfSymbol].ToString(), schemaRecord); //store sheet data record
            }
            ...
        }
    }
}




Retrieve Kotlin Property type from Kotlin psi API?

I'm trying to create new rule for detekt project. To do this I have to know exact type of Kotlin property. For example, val x: Int has type Int.

Unfortunately, for property of type private val a = 3 I receive the following:

  1. property.typeReference is null
  2. property.typeParameters is empty
  3. property.typeConstraints is empty
  4. property.typeParameterList is empty
  5. property.text is private val a = 3
  6. property.node.children().joinToString() has object notation of previous item
  7. property.delegate is null
  8. property.getType(bindingContext) is null (the property bindingContext is part of KtTreeVisitorVoid used

Question: how can I get name of type (or, what is better, object KClass) to compare the actual property type with Boolean class type? (e.g. I just need to get if property boolean of not)

Code:

    override fun visitProperty(property: org.jetbrains.kotlin.psi.KtProperty) {
        val type: String = ??? //property.typeReference?.text - doesn't work

        if(property.identifierName().startsWith("is") && type != "Boolean") {
            report(CodeSmell(
                issue,
                Entity.from(property),
                message = "Non-boolean properties shouldn't start with 'is' prefix. Actual type: $type")
            )
        }
    }




lundi 25 mai 2020

How to get Instance of a Class using reflection in java having generics parameter and return type method?

public enum E{
E1,E2,E3
}

public Class Service{
...
}

public interface A<RET>{
  RET get();
}

public interface AI<RET,CONF> extends A<RET>{
   void conf(CONF ...args);
}

public class AC implements AI<Service,E>{
  public void conf(E ...args){
   ....
 }
public Service get(){
  return new Service();
}
}

Now when I am trying with reflection to create Instance of Class "AC" I am getting error:

public Class MyReflectionAPI{
  public Object getInstance(){
       Class <? extends AI> aClass = (Class <? extends AI>) Class.forName("AC");
       Constructor<? extends AI> aCon = aClass.getConstructor(null);
       AI ai = aCon.newInstance((Object[]) null);

        Class<?> typeArg = Class.forName("[L"+"E"+";");
        Method valueOfTypeArg = typeArg.getMethod("valueOf", String.class);
        Object obj[] = new Object[]{valueOfTypeArg.invoke(typeArg,"E1")};
        ai.conf(obj);
    }

}

giving me the error: Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [E;

Is there any way of getting an object of Instance of AC with a generic objects passed to it?





Check if a Type derives from a Interface with more than one Generic Argument

I have a question about loading types with reflection. I am attempting to filter the list of types in an Assembly by those which implement an interface with two generic parameters. I don't intend to explicitly tell which types are those generic parameters since I want all classes that implement the interface but whenever I attempt to use typeof(IExample<>) it gets marked as an error. However, it's possible to do it with an interface that only has one generic parameter. I would really appreciate some help with this! Thanks in advance :)

public interface IExample<T, E>
{
}

This is how my interface would looks like. And then I currently have to classes that implement it.

public class C 
{
}

public class A : IExample<string, C>
{
}

Public class B : IExample<XMLDocument, C>
{
}




Issue retrieving ByteBuddy-generated Spring Bean

I am making my own ORM and I'm at a point where I want to to eliminate the need to create repository classes. They currently look like this :

@Repository
public class CustomerDao extends AbstractDao<Customer, Long>
{

}

Without going too deep into the inner workings of my ORM, the AbstractDao class uses a bean which is a map containing the entity class as a key and the dao class as a value. Without bringing ByteBuddy in the mix, the declaration of that bean looks like this :

@Bean
public Map<Class<?>, AbstractDao<?, ?>> daoMap()
{
    context.getBeansWithAnnotation(Repository.class).forEach((s, c) ->
    {
        if (c instanceof AbstractDao<?, ?>) map.put(ClassUtils.getSuperClassTypeArgument(c.getClass(), 0), (AbstractDao<?, ?>) c);
    });

    return map;
}

Again this works great but it's very annoying to have to create these empty classes. I am trying to use the Reflections and ByteBuddy libraries to generate these classes at runtime and dynamically inject them into the Spring context as repository beans. Here is my modified method :

@Bean
public Map<Class<?>, AbstractDao<?, ?>> daoMap() throws InstantiationException, IllegalAccessException, IllegalArgumentException, 
    InvocationTargetException, ConstructorMissingException, AnnotationMissingException, NoSuchMethodException, SecurityException
{
    var map = new HashMap<Class<?>, AbstractDao<?, ?>>();

    var byteBuddy = new ByteBuddy();

    for (var entityClass : new Reflections("com.somepackage.entity").getSubTypesOf(Entity.class))
    {
        var daoClass = byteBuddy
            .subclass(TypeDescription.Generic.Builder.parameterizedType(AbstractDao.class, entityClass, 
                ReflectionUtils.getIdField(entityClass).getType()).build())
            .annotateType(AnnotationDescription.Builder.ofType(Repository.class).build())
            .make();

        var clazz = daoClass.load(getClass().getClassLoader()).getLoaded();

        ((GenericApplicationContext) context).registerBean(clazz, clazz.getConstructor().newInstance());
    }

    context.getBeansWithAnnotation(Repository.class).forEach((s, c) ->
    {
        if (c instanceof AbstractDao<?, ?>) map.put(ClassUtils.getSuperClassTypeArgument(c.getClass(), 0), (AbstractDao<?, ?>) c);
    });

    return map;
}

The loop that creates the classes and injects them as beans seems to work fine. It doesn't throw exceptions and affects the right classes. I am however getting an exception at the getBeansWithAnnotation line :

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.mdenis.carbon.carbon_orm.dao.AbstractDao$ByteBuddy$jzMtXq5b': Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:278) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1358) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1204) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:226) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansWithAnnotation(DefaultListableBeanFactory.java:672) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBeansWithAnnotation(AbstractApplicationContext.java:1264) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at com.mdenis.carbon.carbon_orm.config.ORMConfig.daoMap(ORMConfig.java:55) ~[classes/:na]
at com.mdenis.carbon.carbon_orm.config.ORMConfig$$EnhancerBySpringCGLIB$$8fd9cb34.CGLIB$daoMap$1(<generated>) ~[classes/:na]
at com.mdenis.carbon.carbon_orm.config.ORMConfig$$EnhancerBySpringCGLIB$$8fd9cb34$$FastClassBySpringCGLIB$$a25eec90.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at com.mdenis.carbon.carbon_orm.config.ORMConfig$$EnhancerBySpringCGLIB$$8fd9cb34.daoMap(<generated>) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
... 85 common frames omitted

This seems to be related to Spring failing to autowire the constructor even though it technically doesn't have to. Any idea how to resolve this?





Find method by signature in a class and invoking it

Is there a way to find a method in a class by its signature and invoke it runtime? Example in the class below:

class Person {
   public String getFullName(String first, String last) {
     return first + " " + last;
   }
   public String getValue(int i) {
      return ""
   }
}

can I use reflection to scan the Person class and return the method getFullName when searching all methods with (String, String) signature?





Method parameter is Array of Enum, using reflection how to get the method

I have:

 enum E {A,b}

Now a class and method having var args of type E:

public class D{
 public void do(E ..arg){}
}

Class z = Class.forName("D");
Class e = Class.forName("E");
Method m = z.getDeclaredMethod("do",e);

giving me error java.lang.NoSuchMethodException





How to dynamically add ByteBuddy-generated class as a spring bean

I am making my own ORM as a reflection / generics exercise. What I am trying to do is to create classes extending my AbstractDao class with ByteBuddy and register them as beans. The following code throws the following error (note that the c variable is obtained by looping through Spring beans flagged with a certain annotation):

Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)

var daoClass = byteBuddy
                    .subclass(TypeDescription.Generic.Builder.parameterizedType(AbstractDao.class, c.getClass(), Long.class).build())
                    .annotateType(AnnotationDescription.Builder.ofType(Repository.class).build())
                    .make();

                var clazz = daoClass.load(getClass().getClassLoader()).getLoaded();

                ((GenericApplicationContext) context).registerBean(clazz, clazz.getConstructor().newInstance());

Sounds like it's not finding a no-args constructor. I tried adding one and now it's complaining about a duplicate method signature (!) :

var daoClass = byteBuddy
                    .subclass(TypeDescription.Generic.Builder.parameterizedType(AbstractDao.class, c.getClass(), Long.class).build())
                    .annotateType(AnnotationDescription.Builder.ofType(Repository.class).build())
                    .defineConstructor(Visibility.PUBLIC)
                        .intercept(MethodCall.invoke(Object.class.getConstructor()))
                    .make();

                var clazz = daoClass.load(getClass().getClassLoader()).getLoaded();

                ((GenericApplicationContext) context).registerBean(clazz, clazz.getConstructor().newInstance());

What am I doing wrong?





Why doesn't java.reflect.Method.invoke wrap primitive return values with valueOf? [duplicate]

I just noticed that when invoking methods via reflection that return a boolean, the result is neither Boolean.TRUE nor Boolean.FALSE as I would expect as they are the definite result of Boolean.valueOf(). This feels strange to me.

Why is that?





How to access private/package protected fields and methods in Java module system?

I'm trying to access the horizontal ScrollBar for the VirtualFlow that is internal control for a TableView. My working environment:

  • OS - Windows 10
  • IDE - Eclipse v. 2020-03 (4.15.0)
  • JDK - jdk-10.0.2
  • Compiler - maven-compiler-plugin 3.8.1 (m2E for Eclipse)

The code below attempts to access the VirtualFlow (which is a field named flow in TableViewSkinBase, the parent for the skin for the TableView), and then to access the horizontal ScrollBar:

private void xxx() {
      final TableView<R> tableView = new TableView<>();
      final TableViewSkin<R> skin = (TableViewSkin<R>) tableView.getSkin();
      try {
           final Field flowField = TableViewSkinBase.class.getDeclaredField("flow");
           flowField.setAccessible(true);
           final Method hbarMethod = VirtualFlow.class.getDeclaredMethod("getHbar");
           hbarMethod.setAccessible(true);

           final VirtualFlow<IndexedCell<R>> flow = (VirtualFlow<IndexedCell<R>>) flowField.get(skin);
           ScrollBar hbar = (ScrollBar) flowField.get(flow);
      }
      catch (NoSuchMethodException | SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException ex) {
           ex.printStackTrace();
      }
 }

The snippet below is from the entry in the .pom file for the compiler plugin:

<plugin>
            <!-- http://maven.apache.org/plugins/maven-compiler-plugin/ -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <source>10</source>
                <target>10</target>
                <compilerArgs>
                    <arg>--add-opens=javafx.scene.control=ALL-UNNAMED</arg>
                    <arg>--add-opens=javafx.scene.control.skin=ALL-UNNAMED</arg>
                </compilerArgs>
            </configuration>
</plugin>

An InaccessibleObjectException is thrown at the flowField.setAccessible(true) line in the try/catch block with the message:

Unable to make field javafx.scene.control.skin.VirtualFlow javafx.scene.control.skin.TableViewSkinBase.flow accessible: module javafx.controls does not "opens javafx.scene.control.skin" to unnamed module @418e9723

I'm pretty sure there's more than one error here and would be grateful to have them pointed out; an example based on the working environment described above would be useful.

Thanks in advance.





dimanche 24 mai 2020

How to reflect on a different delegate for a string type in C#?

How can one reflect on a different delegate for a string type in C#?

private static Func<string, T> TryGetParser<T>()
    {
        return typeof(T).GetMethod("Parse", new Type[] { typeof(string) })
            .CreateDelegate(typeof(Func<string, T>)) as Func<string, T>; 
    }




How to get concrete type in generic method

I have a method that returns an interface:

private List<IFoo> GetData(string key)
{    
   ...returns a different concrete implementation depending on the key (e.g. FooBar : IFoo)
}

And I want to convert the result to a DataTable:

var result = GetData("foobar");
return ConvertToDataTable(result)

and my implementation of ConvertToDataTable looks something like this:

private DataTable ConvertToDataTable<T>(IEnumerable<T> data)
{
    //problem is typeof(T) is always IFoo - not FooBar
    PropertyInfo[] properties = typeof(T).GetProperties();

    DataTable table = new DataTable();
    foreach (var prop in properties)
    {
        table.Columns.Add(prop.DisplayName, prop.PropertyType);
    }
    //etc..
}

How can I get the underlying type in the generic ConvertToDataTable method?





Invoke methods dynamically: replacing reflection with functional programming

This question on stackoverflow has an answer that replaces calling methods using reflection with functional programming. I like it, but I don't understand why it works. The interface defines an execute method, but nothing explicitly implements that method!

Why does this work? Why does it even compile? What am I missing?

@FunctionalInterface
public interface Method {
    double execute(int number);
}

public class ShapeArea {
    private final static double PI = 3.14;

    private Method[] methods = {
        this::square,
        this::circle
    };

    private double square(int number) {
        return number * number;
    }

    private double circle(int number) {
        return PI * number * number;
    }

    public double run(int methodIndex, int number) {
        return methods[methodIndex].execute(aNumber);
    }
} 




I am trying to access a private member variable through reflection but getting java.lang.NoSuchFieldException

''' public class AccessPrivateMember { private String privateName;

public AccessPrivateMember(String privateName) {`enter code here`
    super();
    this.privateName = privateName;
}

public String getPrivateName() {
    return privateName;
}

public void setPrivateName(String privateName) {
    this.privateName = privateName;
}
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {

    AccessPrivateMember objAccessPrivateMember = new AccessPrivateMember("Secret Name");
    /*
     * Field reflectionAPIField=
     * objAccessPrivateMember.getClass().getDeclaredField("privateName"); String
     * secretName = (String) reflectionAPIField.get(objAccessPrivateMember);
     * System.out.println("secretName="+secretName);
     */
    Field reflectionAPIField2= AccessPrivateMember.class.getClass().getDeclaredField("privateName");
    reflectionAPIField2.setAccessible(true);        
    String secretName2ndWay = (String) reflectionAPIField2.get(objAccessPrivateMember);
    System.out.println("secretName2ndWay="+secretName2ndWay);
}

} '''

    Exception 

    Exception in thread "main" java.lang.NoSuchFieldException: privateName
    at java.lang.Class.getDeclaredField(Unknown Source)
    at io.java.interview.AccessPrivateMember.main(AccessPrivateMember.java:31)
    1. Line Number 31 is 
   Field reflectionAPIField2 = AccessPrivateMember.class.getClass().getDeclaredField("privateName");

2. The code commented is printing the correct result and it is also accessing the private instance variable by privateName. But the line 31 is giving above error.





samedi 23 mai 2020

Why does my static field become null when accessed later?

I have following code:

public abstract class Base {
    private static FieldInfo usersField;

    private object users;

    internal static void InitType(Type type) {
        // usersField == null
        usersField = type.GetField("users");
        // usersField != null
    }

    protected internal virtual void InitInstance(object instance) {
        // usersField == null; again?!
        this.users = usersField.GetValue(instance);
    }
}

public class A : Base {}

In order to initialize it, I execute these two instructions in an unspecified order (A instance may be created first and vice-versa):

Base.InitType(/* reflection type I want to access */);
a = new A(); // private static A a; // Note that this works normally, it is never null when I set it.

Some time later, I call a.InitInstance(/* reflection instance I want to access */) but it fails because my previously-initialized usersField becomes null.

I don't understand why this is happening. I tried checking the AppDomain as suggested in this answer but it is the same in both methods, Unity Root Domain. I also tried making sure that I hold an instance of A before I call InitType() with no success.

While there is a possibility that the external library is reloaded between my InitType() and InitInstance() calls, it is highly unlikely that the engine reloads the whole assembly - it should only call a library-internal method to do the reload.

What am I missing here? Surely usersField object can't be garbage-collected when I hold a reference to it, right?





No getters and setters are called in JPA

I am using JPA 2.1 and while persisting and retrieving the entities from database I could see no constructor of the entity is called and not getters and setters. How does the serialization and deserialization take place then from DB object to JAVA object, if getters, setters and constructor are not called

Teacher

@Entity
@Table(name="Teacher")
public class Teacher {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    int id;

    @Column
    String name;



    public Teacher(String name) {
        super();

        this.name = name;
    }

    public Teacher()
    {
        System.out.println("const");
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Column
    public String getName() {
        System.out.println("get Name");
        return name;
    }

    public void setName(String name) {
        System.out.println("set Name");
        this.name = name;
    }

Main

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistence");
        EntityManager em1 = entityManagerFactory.createEntityManager();

        em1.getTransaction().begin();

        Teacher t = new Teacher("wick");

        em1.persist(t);

        Teacher t1= em1.find(Teacher.class, 21);


        em1.getTransaction().commit();
        em1.close();




Dynamically instantiate a class based on that classes name, in Scala

I have a group of classes, each of which has a member called Description.
I would like the end-user of my library to be able to specify which classes they are interested and be able to read that description. Hence I want to be able to dynamically instantiate each of the specified classes and return the Description.

I'm aware that I need reflection to do this and I've seen a lot of SO questions suggesting Class.forName can help me but I haven't been able to get it working.

Hopefully the following demonstrates what I want to be able to do:

scala> abstract class Feature (start: Short, end: Short){val description: String}
defined class Feature

scala> class Feature1 (start: Short, end: Short) extends Feature(start, end){override val description = "this is feature 3"}
defined class Feature1

scala> class Feature2 (start: Short, end: Short) extends Feature(start, end){override val description = "this is feature 2"}
defined class Feature2

scala> class Feature3 (start: Short, end: Short) extends Feature(start, end){override val description = "this is feature 3"}
defined class Feature3

scala> val classesForWhichIWantToGetTheDescription = Set[String]("Feature1", "Feature2")
classesForWhichIWantToGetTheDescription: scala.collection.immutable.Set[String] = Set(Feature1, Feature2)

scala> val classesWithDescriptions = classesForWhichIWantToGetTheDescription.map(
     |     className => (className, s"I want the class description of ${className} to be displayed here")
     | )
classesWithDescriptions: scala.collection.immutable.Set[(String, String)] = Set((Feature1,I want the class description of Feature1 to be displayed here), (Feature2,I want the class description of Feature2 to be displayed here))

scala> classesWithDescriptions.foreach(
     |     c => println(c)
     | )
(Feature1,I want the class description of Feature1 to be displayed here)
(Feature2,I want the class description of Feature2 to be displayed here)

Can anyone help me achieve this?

thanks in advance





No such Method Exception, in generic method when creating new instances of a class

I'm reading in a couple of data files with methods like the readWeather method below (second code paragraph). The are two things separating these methods, one are the Class for the data, in the readWeather method the Class is WeatherData.

public final class WeatherData extends Data {
    protected WeatherData(String[] dataLines, int lineIndex) {
        super(dataLines, lineIndex);
    }
} 
/**
 * Create and read new Data
 * 
 * @param dataLines
 * @param lineIndex
 */
protected Data(String[] dataLines, int lineIndex) {
    super(createIdentifiableData(dataLines, lineIndex));
    lineIndex += 4;
    dataLinesIndex = readComponentData(dataLines, lineIndex);
}

protected Data() {
    super();
}

And the second thing is the HashMap object which is used to store the data in. In this case weatherDataMap.

   /**
     * Read data
     * 
     * @param path - datafile
     */
    private void readWeather(String path) {
        setupDataFileInfo(path);
        final int nWeathers = Integer.parseInt(dataLines[lineIndex]);
        weatherDataMap = new HashMap<>(calcHashMapSize(nWeathers));
        for (int i = 0; i < nWeathers; i++) {
            lineIndex++;
            WeatherData data = new WeatherData(dataLines, lineIndex);
            lineIndex = data.getLineIndex();
            weatherDataMap.put(data.getId(), data);
        }
    }

Anyway I tried making a generic method in order to stop keeping to make new methods for different kind of data see method below (dataLines is a String[], lineIndex is an int). However I get an java.lang.NoSuchMethodException: GameData$WeatherData.([Ljava.lang.String;, int)

     private <T extends Data> HashMap<Integer, T> readData(String className, HashMap<Integer, T> o, String path) {
        setupDataFileInfo(path);
        final int nDatas = Integer.parseInt(dataLines[lineIndex]);
        o = new HashMap<>(calcHashMapSize(nDatas));
        for (int i = 0; i < nDatas; i++) {
            lineIndex++;
            T data;
            try {
                data = (T) Class.forName(className).getDeclaredConstructor(String[].class, int.class)
                        .newInstance(dataLines, lineIndex);
                lineIndex = data.getLineIndex();
                o.put(data.getId(), data);
            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException | NoSuchMethodException | SecurityException
                    | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return o;
    }

I also get a "Type safety: Unchecked cast from capture#1-of ? to T" warning on the following line. I have looked at this question regarding the warning, but I don't understand why I get the warning in my code. why it is giving me no such method exception

data = (T) Class.forName(className).getDeclaredConstructor(String[].class, int.class)
                        .newInstance(dataLines, lineIndex);




vendredi 22 mai 2020

How to extract index of a UiObject element

I have been ramaging through this for a couple of hours now.

I have a UiObject element for which I need to find the value of the index attribute. The UiObject element only exposes methods to extract information like Text, ContentDescription, Bounds, Classname, etc. but not index.

I had a similar problem with resourceID and I was able to solve it using Java reflection to extract the same during runtime. The solution is here. I wanted to use a similar approach but AccessibilityNodeInfo doesn't expose that information.

Does anyone know of a solution or something similar to retrieve the index information from a UiObject?





golang reflection to initialise struct that satisfies an interface

Can I get rid of the switch with some sort of reflection? brand will always match the struct name

package main

import "fmt"

type Car interface {
    Move()
    SetModel()
}

type Ford struct {
    Model string
}

type Volkswagen struct {
    Model string
}

func (car *Ford) Move() {
    fmt.Println(car.Model + " is moving!")
}

func (car *Ford) SetModel() {
    car.Model = "Focus"
}

func (car *Volkswagen) Move() {
    fmt.Println(car.Model + " is moving!")
}

func (car *Volkswagen) SetModel() {
    car.Model = "Jetta"
}

func main() {
    var car Car

    brand := "Ford"

    switch brand {
    case "Ford":
        car = &Ford{}
    case "Volkswagen":
        car = &Volkswagen{}
    }
    car.SetModel()
    car.Move()
}




Java - weird genetics behavior with arrays

I was trying to implement some kind of custom serialization with reflection, and then I found out that you just cannot cast A[] to B[] if A isn't a subtype of B even if all the elements in the array are subtypes of B (It should work because of type erasing because at the end of the day both a[] and b[] are Object[]).

here is an example of what I mean:

public class Foo {
    public static void main(String[] args) throws Exception {
        new Foo().testGenerics();
    }


    public LinkedList<String> strList;
    public String[] strArr;

    public void testGenerics() throws Exception {

        LinkedList<Object> objList = new LinkedList<Object>();
        objList.add("foo");


        Object[] objArr = new Object[1];
        objArr[0] = "bar";

        Foo.class.getField("strList").set(this, objList);

        System.out.println("list[0]  = " + strList.get(0));
        System.out.println("list len = " + strList.size());

        Foo.class.getField("strArr").set(this, objArr);

        System.out.println("arr[0]  = " + strArr[0]);
        System.out.println("arr len = " + strArr.length);

    }

}

In this example the list works fine but the array throws an exception at the line that tries to set it.

is there any reason arrays ignore type erasing, and is there any good way to create an array and a list for a given type at runtime?





ReflectionClass keeps returning className does not exist

What am trying to do is use scandir() to scan a directory and get all the files there, then use the ReflectionClass to read or access the class.

I was able to get all the files in the directory and assigned it to an array but was unable to read or access the properties and the methods using the \ReflectionClass as it keeps returning

Class App\Controllers\AtController does not exist

This is the code I have so far

// The directory to scan and assign it to a variable
$classControllers = scandir($cur_dir . '/app/Controllers');

// Change to the ReflectionClass to access
chdir($cur_dir . '/app/Controllers/');

// Dump the $classControllers to see if it truly scan the directory
var_dump($classControllers);

$control = '';

// Loop over the $classControllers
foreach($classControllers as $classController){
    if($classController != "." && $classController != "..")
    {
        $classController = str_ireplace(".php", "", $classController);
        echo $classController . PHP_EOL;

        // Use ReflectionClass to read the class name, methods and properties of each class.
        $controllers = new \ReflectionClass("App\\Controllers\\$classController")#App\Controllers is the namespace of the files in the directory;

        $controller = $controllers->getName();
        $control = substr($controller, 12);
        $control = ucfirst($control);
        $routeScript .= "\t$control" . "," . PHP_EOL; 
    }
}

NB: new \ReflectionClass("App\\Controllers\\$classController"); #App\Controllers is the namespace of the files in the directory





jeudi 21 mai 2020

How to make AutoMapper crash when mapping null to [NotNull]?

I'm trying to figure out how to prevent AutoMapper from ever putting a null into a constructor argument marked with a [NotNull] attribute.

For example, given the following:

public class MyNullClass
{
    public string MyProp { get; set; }
}

public class MyNotNullClass
{
    public MyNotNullClass([NotNull] string myProp) =>
        System.Console.WriteLine(myProp == "Foo" ? "Foo" : "Bar");
}

I would like this code:

var myClass = new MyNullClass();
var iShouldCrash = _mapper.Map<MyNotNullClass>(myClass);

To throw a NullArgumentException with a message of "AutoMapper tried to map null to a member marked [NotNull].".

...But I'm not sure how. How can I hook something into AutoMapper to check the actual mapping being done?

I've tried BeforeMap, and then using reflection, but that seems to run after the mapping has already been performed and it's for the entire object, so I have no idea how to tell which constructor was actually called with which values.





Kotlin reflection java long[] field err:java.lang.ClassCastException

kotlin reflection java long[] field err:java.lang.ClassCastException: long[] cannot be cast to java.lang.Long





Loading C# project dll with unmanaged c++ dependency

I created on C# dll library which has reference to some unmanaged c++ dlls. If i create consoled application to test dll and run it works properly.

 static void Main(string[] args)
    {
       MYdll mine = new MYdll();

      string status = mine.GetStatus();
}

But if same dll is used in actual solution with multiple projectsm and same function is called, I get null exception for som object of unmaanged dll, I copied all unmanaged dll to debug folder. Is there any dll or loading of dll I need to do to remove null exception?





How to fetch a webElement field from the page class by using a name which is passing from xml or excel sheet to design a keyword driven framework

My page class is

   public class LoginPage {
             WebDriver d;
            @FindBy(xpath="")

              public WebElement userName;

            @FindBy(xpath="")

            public WebElement password; 
           public LoginPage(WebDriver d){
                this.d=d ;
                PageFactory.initElements(d,this);
           }
         }

I have a testcase class which is

public class UserTestcase extends BaseClass{


     @Test(priority=0)
     @Parameters("url")
     public void SuperAdminValidLogin(String url) throws Exception{
       d.get(url.concat("/user/list"));
      Thread.sleep(1000);
       /*here i need to fetch data from excel sheet where action, testdata and element and page class is using are specified*/
         // how to fetch the webleement in LoginPage class?
          /* here i will call a method which is having a switch case for actions and based on that it 
          will perform. so i have to pass keyword action, element and testdata from the excel or xml. 
        But getting webelement by using the name is possible?*/

           }
     }

I am very basic to java progrmming, is there a way to access the webelement by using its name? we can mention the class name also from excel. My intention is passing actions test data and the element name for example "userName" from excel and fetching the userName webelement from the page class and pass the element in the test case.





mercredi 20 mai 2020

How do I use *attributeless* MEF 2.0 to export methods that match a specific signature?

I'm interested in using external assemblies as plugins. Instead of basing import/export on interfaces, I want to be able to export methods from random assemblies in cases where the method meets a certain signature and import them as method proxies. I have done this previously via custom reflection code but I would rather use Microsoft's built in functionality. Unfortunately, the documentation for MEF v2 is quite lacking.

So how can I change this to successfully create method proxies:

[Test()]
public void ProxyTest()
{
    var builder   = new ConventionBuilder();
    var filter    = new MemberFilter((info, obj) => info.DeclaringType != typeof(object) && info.MemberType == MemberTypes.Method && ((MethodInfo)info).IsBoolTask());
    builder.ForTypesMatching((classType) => classType.FindMembers(MemberTypes.Method, ReflectionExtensions.Everything, filter, null).Any()).Export<Func<Task<bool>>>();
    var host      = new ContainerConfiguration().WithAssembly(this.GetType().Assembly, builder).CreateContainer();
    var container = new ProxyContainer();
    host.SatisfyImports(container);
}

public class ProxyContainer
{
    [ImportMany]
    public IEnumerable<Lazy<Func<Task<bool>>>> LazyProxyMethod
    {
        get;
        set;
    }

    [ImportMany]
    public IEnumerable<Func<Task<bool>>> ProxyMethods
    {
        get;
        set;
    }
}
public static class StaticThing
{
    public static Task<bool> MyStaticMethod() =>
        Task.FromResult(true);
}

public class InstanceThing
{
    public Task<bool> MyInstanceMethod() =>
        Task.FromResult(true);
}

public class InstanceWithStaticThing
{
    public static Task<bool> MyStaticMethod() =>
        Task.FromResult(true);
}

public static class ReflectionExtensions
{
    public const BindingFlags Everything = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy;

    public static bool IsBoolTask(this MethodInfo method) =>
        null != method &&
        typeof(Task<bool>) == method.ReturnType;
}




C# - Replace methods body with DynamicMethods body

I try to replace the body of a method with the body of a DynamicMethod. So far I used the following resources to get the pointer to a "normal" method and to a DynamicMethod. With the functionality from the first link I have the functionality to replace the body of "normal" method with the body of another "normal" method. But if I try to use the functionality with the DynamicMethod it doesn't work. In the following is an example test:

using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;

public class Test
{
    public void Test_Dynamic()
    {
        // --- Gemerate new dynamic method ---
        DynamicMethod dynamicMethod = new DynamicMethod(
            "My_DynamicMethod",
            typeof(int),
            new Type[] { typeof(int) },
            typeof(Test).Module)
        ;

        ILGenerator il = dynamicMethod.GetILGenerator();
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Ret);


        // --- Check expected results ---
        var normalOriginalValue = TestFunc(78); // is 73
        var normalInjectValue = InjectFunc(78); // is 28
        var dynamicValue = dynamicMethod.Invoke(null, new object[] { 78 }); // is 78


        // --- Get pointer of DynamicMethod ---
        var getDynamicHandle = Delegate.CreateDelegate(
            typeof(Func<DynamicMethod, RuntimeMethodHandle>),
            typeof(DynamicMethod).GetMethod("GetMethodDescriptor",(BindingFlags)(-1))
        ) as Func<DynamicMethod, RuntimeMethodHandle>;

        var handle = getDynamicHandle(dynamicMethod);
        var dynamicMethodPtr = handle.Value;


        // --- Get pointer of "normal" method ---
        var testFunc = typeof(Test).GetMethod("TestFunc", (BindingFlags)(-1));
        RuntimeHelpers.PrepareMethod(testFunc.MethodHandle);
        var normalTargetMethodPtr = testFunc.MethodHandle.Value;

        var injectFunc = typeof(Test).GetMethod("InjectFunc", (BindingFlags)(-1));
        RuntimeHelpers.PrepareMethod(injectFunc.MethodHandle);
        var normalInjectMethodPtr = injectFunc.MethodHandle.Value;


        // --- Swap "normal" method bodies ---
        SwapBodies(normalTargetMethodPtr, normalInjectMethodPtr);
        var injectedNormalValue = TestFunc(78); // is 28


        // --- Swap method bodies with a DynamicMethod ---
        // Should be 78 but throws an System.AccessViolationException
        SwapBodies(normalTargetMethodPtr, dynamicMethodPtr);
        var injectedDynamicMethodValue = TestFunc(78);
    }

    public static int TestFunc(int value)
    {
        return value - 5;
    }

    public static int InjectFunc(int value)
    {
        return value - 50;
    }

    private unsafe static void SwapBodies(IntPtr toReplace, IntPtr toInject)
    {
        // For simplicity here I only show the procedure for a debug run
        // and not a production run.
        if (IntPtr.Size == 4)
        {
            int* inj = (int*)toInject.ToPointer() + 2;
            int* tar = (int*)toReplace.ToPointer() + 2;

            byte* injInst = (byte*)*inj;
            byte* tarInst = (byte*)*tar;

            int* injSrc = (int*)(injInst + 1);
            int* tarSrc = (int*)(tarInst + 1);

            *tarSrc = (((int)injInst + 5) + *injSrc) - ((int)tarInst + 5);
        }
        else
        {
            long* inj = (long*)toInject.ToPointer() + 1;
            long* tar = (long*)toReplace.ToPointer() + 1;

            byte* injInst = (byte*)*inj;
            byte* tarInst = (byte*)*tar;

            int* injSrc = (int*)(injInst + 1);
            int* tarSrc = (int*)(tarInst + 1);

            *tarSrc = (((int)injInst + 5) + *injSrc) - ((int)tarInst + 5);
        }
    }
}

Can someone help me to get it working to replace a method body with the body of a DynamicMethod?





mardi 19 mai 2020

Cloning field via reflection - protected access

Here is my code

public Object backUP(Class<?> testClass, Object testObject) throws Exception{
        Class<?> testC = Class.forName("testClass");  //TODO: Not sure this is right.
        Object newObj = testC.newInstance();  // this is the backed up copy of the object we are updating and calling methods for.
        Field[] fields = testObject.getClass().getDeclaredFields();

        for(int i=0; i<fields.length; i++){
            fields[i].setAccessible(true);
            if(fields[i].get(testObject) instanceof Cloneable){
               Object obj =  (fields[i].get(testObject)).clone();
               newObj.getClass().getDeclaredField(fields[i].getName()).setAccessible(true);
               newObj.getClass().getDeclaredField(fields[i].getName()).set(newObj,obj);
            }

Tried cloning field with reflection, but got message that clone has protected access




How to reuse logic for class instantiation and get around IllegalAccessException?

Goal: create a util class that will contain some reflection code, in particular code that creates a new class instance. That code is not very simple, so I want to keep it in a util function so that I can reuse it multiple times.

Approach/Idea: create ClassUtil that will have a function that returns a lambda that creates a new class instance. I will execute that lambda in MyClassFactory, a class that I know can create a new instance of MyClassOne because it will be in the same package and the default constructor is package-private access modifier, so ClassUtil cannot make an instance of that class, but since I am executing the lambda in a class that can all should be good.

Error: java.lang.IllegalAccessException: class com.util.ClassUtil cannot access a member of class com.somepackage.MyClassOne with modifiers ""

Question: How to make Java runtime think that it is MyClassFactory the one that is trying the instantiation?

UML: enter image description here
Code:

package com.somepackage

import com.util.ClassUtil;

public class MyClassFactory {

    public MyClass createMyClass() {
        String implClassFQN = <get impl class FQN from somewhere>;
        return (MyClass ) ClassUtil.createClassInstance().apply(implClassFQN);
    }
}

package com.util;

import java.lang.reflect.InvocationTargetException;
import java.util.function.Function;

public class ClassUtil {

    /**
     * @return a new instance of the class given the class fully qualified name
     */
    public static Function<String, Object> createClassInstance() {
        return (classFQN) -> {
            try {
                return Class.forName(classFQN).getDeclaredConstructor().newInstance();
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Impl class specified in properties file not found", e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("Default constructor not found", e);
            } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        };
    }

}

Workaround/New Approach: would anyone know how I could have taken a different approach to achieve the same goal?

Note: If I put the code from ClassUtil into MyClassFactory it works fine, but I want it reusable.





How to remove special characters from a class object C#

I have a class object with nearly 200 properties and need to remove the special characters from the property value. What is the efficient way to remove the special characters from the properties in a class object. The properties in a class contains special characters while receiving input from service. If the properties are less in a class then it can be done for each property. Is there a way to remove special characters from the properties other than using reflection ?





Type.IsPrimitive working for generic types?

If I write the following generic method:

static bool HelloWorld<TSource>(TSource input)
{
    return typeof(TSource).IsPrimitive;
}

and I pass an int to it, it successfully recognizes it as a primitive. If I pass a string for example, it will not - which means it works.

The documentation states that it shouldn't work though, or am I miss-reading something?

If the current Type represents a generic type, or a type parameter in the definition of a generic type or generic method, this property always returns false.





Loop through List

I used Reflection to get all relevant information out of a Class Libary (.dll). It returns a List of Object-Arrays, which I created

list.Add(new object[] { args.Select(x => x.Value) });

Each Object-Array contains a System.Reflection.CustomAttributeTypedArgument, object. My goal is to get all values of each Object[].

foreach (var type in types)
{

    MethodInfo[] declaredMethods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public);

    foreach (var method in declaredMethods)
    {
        foreach (var test in method.CustomAttributes)
        {
            var args = test.ConstructorArguments;
            foreach (var arg in args)
            {
                if (args.Count > 0 && 
                    arg.ToString().Contains(Path.GetFileName(path)))
                {
                    list.Add(new object[] { args.Select(x => x.Value) });     
                }
            }
        }
    }
}

I get some arrays with the information I want to work with. But I cant reach it while iterating.





lundi 18 mai 2020

C# How to use GetMethod to find an overload with a generic out parameter?

everything is in the title, but let me put some code :

/// <summary>
/// The first version
/// </summary>
public TItem Foo(long param1) { ... }
/// <summary>
/// Overload with a generic parameters
/// </summary>
public bool Foo<TItem>(out TItem item, long param1) { ... }

The goal is:

  • to end up with a MethodInfo for the second 'Foo' method
  • to NOT use GetMethods or GetMember because it's inelegant and prone-to-future-errors
  • to NOT rename any of those methods. The easy GetMethod("name") cannot be used here...

Please note that:

  • The type or TItem is obviously unknown.
  • That MethodInfo is a GenericMethodDefinition, meaning it will need a MakeGenericMethod(...) to be invokable.
  • I did not find the right parameters for GetMethod in the MS documentation.
  • I spent 1 hour searching StackOverflow for the answer without success, but reflection evolved so much that there is a lot of irrelevant answers all around. Adding a date filter in stackoverflow might be a great idea (or maybe a .Net framework version filter ?)
  • You are more than welcome to prove me wrong an find me the obvious answer I missed !
  • My name is Mose and I'm a bullet addict ^^




Get fields from DataContext class, but exclude related tables

I'm trying to iterate through a class T, which may or may not be a LINQ DataContext class. It works for normal classes, but when passing in a database class from a Linq data context, it also iterates over the related tables with their related properties (like a deep copy).

I'm trying to just get all the "primitive" fields if it's a database class. I.e. it should return all the fields in the table. I've tried to filter on IsPrimitive(), but it does not return all the fields (it might for example exclude nullable int32's amongst others). I've also tried using things like BindingFlags.Public and/or BindingFlags.Instance but to no avail.

public static T MyClone<T>(T original)
{
    T newObject = (T)Activator.CreateInstance(original.GetType());

    foreach (var originalProp in original.GetType().GetProperties())
    {
        //Do something
    }




Instantiate a class when only class name is known

Is it possible to instantiate a class if only class name is known and the class does not have a default constructor?

Only class name is available but nothing is known about the constructors (how many arguments, what type of arguments).

I googled and according to my research, it looks like it is not possible.

But I am just asking this question here to know whether my understanding is correct or is there a way?

Regards, Amit





dimanche 17 mai 2020

Go map struct type conversion after json unmarshaling

I'm trying to create a factory pattern of sorts in Go, but not having any luck. I wanted to be able to use reflection, kind of in the way other languages do it, to create objects/structs on the fly with the object name. However, go doesn't seem to support it the way I hoped, and so I've opted for a simpler approach (see below) by just mapping the struct to a string using a map.

The issue I've now run into, is that, it initially seems to work based on my testing, however, once I call json.Unmarshal on it, it goes from the correct struct type, to a map[string]interface{}, as if it's almost reverting to the containing object's type?

st := make(map[string]interface{})
st["StructName1"] = s.StructName1{}
st["StructName2"] = s.StructName2{}
//...

fmt.Printf("1) '%+v' '%+v'\n", reflect.ValueOf(st["StructName1"]), reflect.TypeOf(st["StructName1"]))
fmt.Printf("2) '%+v' '%+v'\n", reflect.ValueOf(s.StructName1{}), reflect.TypeOf(s.StructName1{}))

ff := st["StructName1"]
err := json.Unmarshal([]byte(reqBody), &ff)
fmt.Printf("3) '%+v' '%+v'\n", reflect.ValueOf(ff), reflect.TypeOf(ff))

Output:

1) '{V1: V2:{V2v1: V2v2: V2v3:}}' 'structs.StructName1'
2) '{V1: V2:{V2v1: V2v2: V2v3:}}' 'structs.StructName1'

3) 'map[V2:map[V2v1:value1 V2v2:value2 V2v3:value3] V1:"value4"]' 'map[string]interface {}'

Unmarshaling 'succeeds', in that it has no errors, but the type that is printed in 3) is a map[string]interface{}. Any ideas why this is?

Also, assigning ff the struct directly instead of using a map, i.e.

ff := s.StructName1{}

Works completely fine.

Also, if you have any advice on a better approach for this in go, I'd appreciate any input.

Thanks in advance.





C# Reflection Emit Call with parameter

I want to call a function with a parameter with the reflection.emit API. In the following is what I have at the moment. But when I run it, it throws the following exception: System.InvalidProgramException : Common Language Runtime detected an invalid program. So my question is what I have wrong in my code snippet below? Can someone help me out?

public class Test
{

    public void test()
    {
        Func<int, long> realSquareFunc = (val) => val * val;
        Type[] methodArgs = { typeof(int) };

        DynamicMethod squareIt = new DynamicMethod(
            "SquareIt",
            typeof(long),
            methodArgs,
            typeof(Test).Module)
        ;

        ILGenerator il = squareIt.GetILGenerator();
        il.Emit(OpCodes.Ldarg_0); // Save parameter on stack
        il.Emit(OpCodes.Call, realSquareFunc.Method); // Call function with input as parameter
        il.Emit(OpCodes.Ret); // Return value from function call before

        var myMethod = (Func<int, long>)squareIt.CreateDelegate(realSquareFunc.GetType());
        var result = myMethod.Invoke(4); // Should be 16 (4*4)
    }

}




Can I query properties from package.json at runtime? [duplicate]

Writing a wrapper for different vscode tsc extensions and I would like to generate a unique ID for each different extension by reading the current context package.json name+publisher properties. Is this possible?





samedi 16 mai 2020

How to distinguish class and delegate using Type API in C# [duplicate]

Type.IsClass property tells whether the type is a class or a delegate. How to distinguish between these to (class and delegate) using Type class API?





Java reflection inside stream's filter

I have an Java POJO:

public class Event {
    private String id;
    private String name;
    private Long time;
}

A simple filtering method I created is:

public static List<Event> simpleFilter(List<Event> eventList, String value) {
    return eventList.stream().filter(Event -> Event.getName().equals(value)).collect(Collectors.toList());
}

Now my task is to create a generic method instead of simpleFilter which can be applicable for any Java POJO object and any of its field. For example, if in future there is new Java object Employee and we want to filter on its String field employeeDepartment, we can use same generic filter method by passing the List of Java object (List, Class type (Employee.class), which field (getEmployeeDepartment) and what value ("Computer") we want to filter on.

I created a method definition:

public static <T> List<T> genericStringFilterOnList(List<T> list, Class<T> c, String methodName, String value) {
}

Caller looks like:

//events is List<Event>
//getName is the method in Event on which I want to filter
//e2 is value which I want to filter
genericStringFilterOnList(events, Event.class, "getName", "e2")

My implementation is:

public static <T> List<T> genericStringFilterOnList(List<T> list, Class<T> c, String methodName, String value) {
    return list.stream().filter(m -> {
        try {
            return c.getMethod(methodName, null).invoke(c).equals(value);
        } catch (IllegalAccessException e) {
        } catch (IllegalArgumentException e) {
        } catch (InvocationTargetException e) {
        } catch (NoSuchMethodException e) {
        } catch (SecurityException e) {
        }
        return false;
    }).collect(Collectors.toList());
}

All these catch were generated by IDE because of checked exception. This doesn't seem to working as it is returning back an empty list. What I am trying to do here is - Using the class type (which is Event.class), I am getting method name using reflection and then invoking that method and then invoke which is basically calling getName() method of Event class and then equals. I also tried this -

return c.getMethod(methodName, null).invoke(c.newInstance()).equals(value);

But with this I am getting NPE on this }).collect(Collectors.toList());

Can you guys please help me in creating a generic method which can called for a List of any POJO and a filter can be applied on any of their String type methods?





java reflection for generic type when using jdbc

In C#, I got an utility that cast Datatable into a list of specified model, like this:

Datatable dt = conn.GetDataTable(); 
List<BookModel> result = EntityHelper<BookModel>.GetListModel(dataTable); 

And the GetListModel() method that using generic type goes like this:

public static List<T> GetListModel(DataTable dt)
    {
        List<T> lObject= new List<T>();
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            T obj = new T();
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                int index = IndexOfField( dt.Columns[j].ColumnName );
                if (index != -1)
                {
                    PropertyInfo pi = obj.GetType().GetProperties()[index];
                    Type propType = pi.PropertyType;
                    if (propType.IsGenericType && (propType.GetGenericTypeDefinition() == typeof( Nullable<> )))
                    {
                        propType = propType.GetGenericArguments()[0];
                    }
                    if (propType.IsEnum)
                    {
                        int objectValue = 0;
                        Int32.TryParse( dt.Rows[i][j].ToString(), out objectValue );
                        pi.SetValue( obj, Enum.ToObject( propType, objectValue ), null );
                    }
                    else if (dt.Columns[j].DataType == propType && dt.Rows[i][j] != DBNull.Value)
                    {
                        pi.SetValue( obj, dt.Rows[i][j], null );
                    }
                    else if ((propType.Name.Equals( "Boolean" ) || propType.Name.Equals( "bool" )) && dt.Rows[i][j] != DBNull.Value)
                    {
                        pi.SetValue( obj, Convert.ToBoolean( dt.Rows[i][j] ), null );
                    }
                }
            }

            lObject.Add( obj );
        }
        return lObject;
    }

That is C# story, now back to Java. I'm using JDBC to execute a stored proc and return a ResultSet. But I found that in Java, generic type got its information erased at the runtime so I cannot do something like this:

public static <T> List<T> castObject(ResultSet rs)
{
    T x = new T(); //IMPOSSIBLE ;___;
    Field[] fields = x.getClass().getDeclaredFields();
     for(Field field: fields) 
     { 
         field.setAccessible(true); 
     }
    ....
}

If it's impossible to create an utility like this, then is there anyway to reduce boilerplate code after getting a resulset ? My table got like 30 columns and I do not want to deal with codes like this:

actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
...




vendredi 15 mai 2020

how know how to open all forms in project by one method by Assembly

who knows how to open all forms in the project by one method by Assembly and system reflection ?? Assembly.GetExecutingAssembly().GetTypes()





lombok @NonNull on Field not readable using getAnnotations

Example:

@Value
@Builder(toBuilder = true)
@AllArgsConstructor(access = AccessLevel.PUBLIC)
public class A {
    //
    // RecordRootable fields
    //
    @NonNull
    private UUID a;
}

Looking at the class file the @NonNull annotation seems to be present if the IntelliJ decompiler is not lying.

Now we want to read the annotation from the Field using Field.getAnnotations or something similar at runtime but nothing is found.

Is there any particular method I can use to read this annotation?

Is there anything extra I need to add to the annotation to be able to read it?





How to retrieve full assembly name with processor architecture?

I would like to retrieve the full name of an assembly from a System.Reflection.Assembly instance as it appears in references in a .csproj file, e.g.:

Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL

I have tried using FullName and GetName().FullName, but at least in .NET 4.6.2, both of them do not contain the processor archiecture part. (It would obviously be trivial to concatenate the string, but I am looking for the "official" way that automatically applies the "correct" formatting rather than relying on my own code to replicate it.)





Spring JPA scan user implementations of generic interface

I wanna write some starter for spring data JPA. I have an interface on kotlin:

interface Converter<ResultType> {
fun convertList(values: List<String>): List<ResultType> {
    return values.map { convert(it) }
   }
    fun convert(value: String): ResultType
}

And scan of implementation of this interface from user(app which will use my starter) package to Map. My questions:

  1. How do know which package I should scan(Ideally without asking user add some property)
  2. And how to build Map i am thinking about using reflection. Have i other options?

And yes, i dont need examples i need some reccomendations about best practices? Thank you!





Resolve generic return type of method at runtim

In a situation where the generic return type of a method only depends on the types of the input parameters (not on the class type parameters), how can I resolve the generic type to the actual type given a concrete list of parameters?

Let's say I have a method like this

public <T,S extends T> T doSomething(T input, S derivedInput)

and at Runtime I have a Method object representing this method as well as some parameter objects so that I can invoke the method with reflection

Object returnval = m.invoke(instance,Object[]{x,y});

Because the return type is determined by the types of the inputs and given that I know the actual types of x and y at runtime, I should be able to figure out at runtime what the type of returnval actually is, or at least a more specific superclass of the actual type than Object. In the example, I would expect there to be a way to automatically infer the class x.Class() from m, x and y, assuming of course that x and y really satisfy the type constraint in the method definition, but ideally I would also be able to tell at runtime if they violate it.

Now I know that there is Method#getGenericReturnType and Method#getGenericParameterTypes, but I could not figure out how to use those to make the inference I want. I also know that this won't work if there is a type parameter of the class involved since those get erased. So I won't be able to resolve the T in T List<T>.get(int) given only a list and an integer. But if the return type is only dependent on the parameter types, I think it should be possible.





Is there a pattern for dealing with interface instances that require different classes of data?

I'm currently working on a workflow system. Simply put, a workflow consists of several steps. Each step has 0 or more transitions to other steps based on the result of the step. If there are no transitions, then it's the end of the workflow.

Background

Steps are stored in the database with a unique id, which is used to instantiate them through reflection. I have the following right now:

IEnumerable<Workflow> workflows = _workflowRepository.GetWorkflows();
foreach(Workflow workflow in workflows) {
    // Retrieve the current step that must be execute
    WorkflowStep currentStep = getCurrentStep(); 
    var flowRunning = true;
    while (flowRunning) {
        IWorkflowStep instance = WorkflowStepFactory.GetStep(currentStep.StepId);
        Result result = instance.Execute();
        // Set currentStep based on defined transitions and the value of result
    }
}

The IWorkflowStep is the interface that steps must inherit:

public interface IWorkflowStep
{
    Result Execute();
}

Each class that is a step has a StepIdAttribute placed on the class with the id:

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
public sealed class StepIdAttribute : Attribute
{
    public StepIdAttribute(int stepId)
    {
      StepId = stepId;
    }

    public int StepId { get; }
}

A step must implement IWorkflowStep and must have the StepIdAttribute placed on that it:

[StepId(Constants.FIRST_STEP_ID)]
public sealed class FirstStep : IWorkflowStep
{
    public Result Execute()
    {
        // Execute step
    }
}

Lastly, the WorkflowStepFactory creates an instance of the interface through reflection:

public static class WorkflowStepFactory
{
    public static IWorkflowStep GetStep(int stepId)
    {
        var iWorkflowStepType = typeof(IWorkflowStep);
        var assemblies = AppDomain.CurrentDomain.GetAssemblies();

        foreach (var assembly in assemblies)
        {
            var typesThatImplementIWorkflowStep = assembly.GetTypes().Where(t => iWorkflowStepType.IsAssignableFrom(t));
            foreach (var type in typesThatImplementIWorkflowStep)
            {
                var appliedStepIdAttributes = type.GetCustomAttributes(typeof(StepIdAttribute), false).Cast<StepIdAttribute>();
                foreach (var appliedAttribute in appliedStepIdAttributes)
                {
                    if (appliedAttribute.StepId == stepId)
                    {
                        return (IWorkflowStep)Activator.CreateInstance(type);
                    }
                }
            }
        }

        throw new Exception("No implementation found");
    }
}

Problem

My problem is that none of the steps are guaranteed to require the same data. For instance, step one might need the following class:

public class Step1Data {
  public string SomeId { get; set; }
}

Whereas step two might need the following class:

public class Step2Data {
  public int MinimumThreshold { get; set; }
  public int MaximumThreshold { get; set; }
}

What I don't want, is for the main loop to become responsible for getting the data for a variety of steps. I want to make it as easy as possible to add new steps and data, so if possible, I want reflection to be able to care of it all.

What I want, is for the instance itself to request the data, that some class picks it up and gives it back to the instance.

My ideas

I was thinking of accomplishing it through delegates and events. To that end, I introduced a delegate:

public delegate void RequestingDataEventHandler<T>(object source, T e);

And added an event to the IWorkflowStep interface:

    public interface IWorkflowStep<T>
    {
        event RequestingDataEventHandler<T> RequestingData;
        Result Execute();
    }

A step could then be like this:

public sealed class FirstStep : IWorkflowStep<Step1Data>
{
    public event RequestingDataEventHandler<Step1Data> RequestingData;

    public Result Execute()
    {
        var myData = new Step1Data();
        if (RequestingData != null)
        {
            RequestingData.Invoke(this, myData);
        }

        // Execute step based on retrieved
    }
}

Then, there could be a class that listens to the event, a StepDataBuilder if you will. There would be one for each T and T could be the Step1Data type or the Step2Data type, etc.. Essentially: T represents the type that should hold the data that the step needs. Something like this:

public class Step1DataBuilder<Step1Data> {
    public void WireEvent(IWorkflowStep<Step1Data> step) {
      step.RequestingData += GetData;
    }

    public void GetData(object source, Step1Data dataObj) {
        dataObj.SomeId = "some id retrieved from somewhere else";
    }
}

However, the above setup requires the loop or outer program to know what type T should be, which I don't think it really doesn't need to at all. I want the outer program to instantiate the classes, wire up the events and to execute the steps. So I'm not really sure what T I should supply, if any. Maybe I can create the classes use Type.MakeGenericType but I'm not too sure if it could accomplish what I want.

Question(s)

  1. What would I need to do to get the above working if I want to supply data using events and delegates?
  2. Is this even a relatively sane approach? It feels a bit convoluted and I'm wondering if there's an easier way that I'm overlooking. An extra layer of indirection, a long-lost design pattern or something else entirely.

If you need any more information, please let me know.





jeudi 14 mai 2020

Reflective Method Invocations With Injection In Spring

I am trying to replicate (to an extent) the method-level injection functionality found in Spring Rest Controllers and Spring @Bean methods. These annotations add support for Spring-context and request-context parameters to be resolved for the invocation.

Take the following two examples as a reference:

// A Spring Rest Controller
@PutMapping(value = "/{id}")
@ResponseStatus(HttpStatus.OK)
public void update(@PathVariable( "id" ) Long id, @RequestBody Foo resource) {
    // both `id` and `resource` are injected based on the request context
}
// Configuration Class
@Bean
public AnObject anObject(AnotherBean anotherBean) {
    // `anotherBean` is injected from the Spring Application Context
}

I would like to extend this functionality in one way or another to create my own injected invocations of methods. This would look something like the following:

@Command
String command(AnObject springApplicationContextObject, int invocationSpecificObject) {
   ...
   return "output"
}

{
   MyInvocationThing invoker;
   Method commandMethod;
   output = invoker.invoke(commandMethod)
}

Does Spring offer any flexible extension points to implement this sort of mechanism? I've been searching for quite a while with no luck.


Note: It is easy to resolve the parameters naively using the ApplciationContext::getBean method, but this excludes support for parameter-level annotations such as @Qualifier or @Resource.

Thank you all so much for your help.





In .NET, is it possible to determine if an override method in its implementation calls its base method that it's overriding?

I have a project with more than a dozen classes implementing .NET's Stream class (and more implementations likely to be added in the future). As I have recently discovered, asynchronous WriteAsync() and ReadAsync() operations are not safe on implementers if they rely on Stream.WriteAsync() or Stream.ReadAsync() if, as MSDN prescribes, implementor only provides implementation for synchronous Write() and Read() methods, and leaves asynchronous methods' functionality to be serviced by default implementation provided in Stream.WriteAsync() and Stream.ReadAsync(). (TL;DR: on some usages it can lead to a deadlock.)

Some derivations in my project intentionally provide their own override implementation of async variants, without call the base implementation at all. Others just rely on base implementation without having override methods. These two cases it seems I can determine at runtime with reflection, and act accordingly in the code for safe operation - use one way of doing things if it overrides; use another way if it doesn't.

However, there's a third, elusive case and that is if deriving class overrides the base's method, but in the body of the implementation eventually makes base.WriteAsync() or base.ReadAsync() calls to ultimately seek the service of the base implementation - and that potentially causing issue if I use the class in doing this as if it overrides, but really should use it as if it doesn't override.

So the question is: is it possible to inspect a class using reflection to determine if overriding method in its body makes a call to the base member that it overrides?





How to render only few properties of ViewModel in MVC?

I have following code. I am trying to render only FirstName and LastName using loop in View. How can I do using reflection MVC 5?

Model:

public class SomeViewModel
{
public int Id{get;set;}
public string FirstName{get;set;}
public string LastName{get;set;}
public string Address{get;set;}
}

View:

@foreach(var property in ViewData.ModelMetadata.Properties)
{
    <div class="editor-line">
        <label>@(property.DisplayName??property.PropertyName)</label>
        @Html.Editor(property.PropertyName)
    </div>
}




Reference POCO object properties in CsvHelper

I have some nested classes used in generic methods, as defined below;

Base Class:

public class Model
{
public int Id {get; set; }
public string Name {get; set; }
}

Class 1:

public class Foo: Model
{
public string Description {get; set; }

    [Name("Parent")]
    [HeaderPrefix("z_Parent")]
public Foo ParentFoo {get; set; }
}

Class 2:

public class Bar: Model
{
public Foo MyFoo {get; set; }
}

When i export to CSV an instance of Foo, I get the fields from both the "Foo" instance i've passed in, as well as all of the fields from "ParentFoo". Ideally i'd like to only have ParentFoo.Name. Similarly, when I export an instance of "Bar", I'd like the field "MyFoo" to actually export "MyFoo.Name" as the value.

I've tried playing around with the configuration options, and all i can think is to set the class to ignore the references, which works in that all of the parent fields aren't included, but also the reference to the parent is also missing;

var csv = new CsvWriter(writeFile, CultureInfo.InvariantCulture);
csv.Configuration.IgnoreReferences = true;
csv.WriteRecords(Items);

Is there a way to achieve this, or should I look into writing my own CSV exporter?

TIA





How can you use CsvHelper Map to bind two objects dynamically?

for CsvHelper i have used Map function for simple use for object

 MemberInfo dMember = new Contact().GetType().GetProperty("FirstName"));
 Map(typeof(Contact), dMember).Name("fname"); //works simple conversion

Here FirstName and fname both comes from configuration which is in Json file \

Now next object which is a List of another class i cannot do.Name i need use .ConvertUsing and do some merging of fields from CSV file i will have 3 fields Email1,Email2,Email3 which has to map to List where Email is a class and has property of an email address.

I was successful to find a way to use dynamic lambda function because Map(x=>x.Email) has to be custom and it should be able to do conversion for any object

    string field = "EmailAddresses"; //field name of a class
    string exp = $"c.{field}";
    var p = Expression.Parameter(typeof(Contact), "c");
    var e = DynamicExpressionParser.ParseLambda(new[] { p }, null, exp);

   // now here e.ReturnType is List<Email> but i cannot use List<Email> instead of dynamic because this 
    //function will also be called for other types so it has resolve at runtime. This maping fails with cannot convert Type Email to Type Object
 Map((Expression<Func<Contact, List<dynamic>>>)e).ConvertUsing(row =>
    {
        dynamic list = new List<ExpandoObject>();
        dynamic email = new ExpandoObject();
        var emailAddress = row.GetField("email_address");
        email.EmailAddress = (emailAddress != null) ? emailAddress:"abc@g.com";
        list.Add(email);
        return list;
    }