vendredi 31 mai 2019

Java ThreadLocal dump values from all threads

I have ThreadLocal that store instances of MyClass. I wish to dump (print, sysout) values (instances) of MyClass from all threads.

I have two implementations, but all of them print value only from the current thread (Thread.currentThread()). Any ideas what I've missed?

P.S. Unfortunately, ThreadLocal API is private so I have to use reflection to get access to ThreadLocalMap that actually keeps values (e.g. see Thread.threadLocals etc.)

public class ThreadLocalT{
    private Method getMap;
    private Field tableField;
    private Field value;
    private Method getEntry;

    public ThreadLocalT() {
        try {
            getMap = ThreadLocal.class.getDeclaredMethod("getMap", Thread.class);
            getMap.setAccessible(true);

            Class<?> threadLocalMapClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap");
            getEntry = threadLocalMapClass.getDeclaredMethod("getEntry", ThreadLocal.class);
            getEntry.setAccessible(true);
            tableField = threadLocalMapClass.getDeclaredField("table");
            tableField.setAccessible(true);

            Class<?> entryClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap$Entry");
            value = entryClass.getDeclaredField("value");
            value.setAccessible(true);            
        } catch (NoSuchMethodException | SecurityException | ClassNotFoundException | NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void dump(ThreadLocal<MyClass> pThreadLocal) {
        // Implementation I
        for (Thread item : Thread.getAllStackTraces().keySet()) {
            try {
                Object data = getMap.invoke(pThreadLocal, item);
                if (data != null) {
                    Object entry = getEntry.invoke(data, pThreadLocal);
                    if (entry != null) {

                        Object obj = value.get(entry);
                        if (obj != null) {
                            System.out.println(item);
                            System.out.println("data = " + data);
                            System.out.println("entry = " + entry);
                            System.out.println("obj = " + obj);
                        }
                    }
                }
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        // Implementation II
        for (Thread item : Thread.getAllStackTraces().keySet()) {
            try {
                Object result = getMap.invoke(pThreadLocal, item);
                if (result != null) {
                    Object table = tableField.get(result);
                    if (table != null) {
                        int threadLocalCount = Array.getLength(table);
                        for (int i=0; i < threadLocalCount; i++) {
                            Object entry = Array.get(table, i);
                            if (entry != null) {
                                Object obj = value.get(entry);
                                if (obj instanceof MyClass) {
                                    System.out.println("obj = " + obj);
                                }
                            }
                        }
                    }
                }
            } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}





Dynamically convert double? to PropertyInfo.PropertyType?

I'm trying to dynamically convert a double? to the property type of a PropertyInfo, which may be int? or decimal?, and maybe other types down the road. An explicit cast works, but then I'd need something like:

if(prop.PropertyType == typeof(int?))
{
    prop.SetValue(obj, (int?)value);
}
else if(prop.PropertyType == typeof(decimal?))
{
    prop.SetValue(obj, (decimal?)value);
}
// etc...

I considered using a Dictionary<Type, Action<...>> containing actions to perform the casts, but I'm looking for something even more elegant. Is there a single line of code I can write to dynamically convert to the property type? Something like this, which throws an InvalidCastException:

prop.SetValue(obj, Convert.ChangeType(value, prop.PropertyType));





When I try to know if there is an annotation in my method, it returns null (even when there is one)

In a bukkit project, something to simplify the creation of commands, I did something that worked but I want to try new things (to learn how to use these things: Annotations!!) but in my code when I look in my code if there is an annotation "Command" on my method it returns "null" and I do not understand why 🤔

My code that looks for the annotation "Order" in my class :

for(Method method : clazz.getMethods()) {
    Command ann = method.getAnnotation(Command.class);
    if(ann != null) {
         // Creates the command
    }
}

My annotation class :

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
public @interface Command {
    String command();
    String name();
    String desc() default "";
    String[] aliases() default {};
    boolean admin() default true;
}

I hope you'll help me find out where my mistake is. And I want to apologize for my English because I am a kind of French and I know that my English is not very good:/

PS: I am a young developer so don't blame me if the answer is obvious, I try to learn by myself, everything I have learned is not with a teacher or another....





how to append nil to dynamic type slice by reflect.Append

Code below will raise a runtime error when append reflect.Value of nil:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var list []interface{}
    v := reflect.ValueOf(list)
    v = reflect.Append(v, reflect.ValueOf(1))   // [1]
    v = reflect.Append(v, reflect.ValueOf("1")) // [1, 1]
    v = reflect.Append(v, reflect.ValueOf(nil)) // runtime error
    fmt.Println(v)
}

So

  • why there is a runtime error?
  • how can I use reflect.Append to add a nil to interface{} slice?




Reflection using generics

I'd like to return the properties of a series of DbSet objects I have saved to a class using reflection, but in order to access this data in a single method I'd need to pass a variable as an accessor to return the properties of that object.

Currently I've managed to return the properties of all of the DbSet objects, but the code looks very DRY.

public List<List<string>> GetProperties()
{
DbContext client = new DbContext();
List<List<string>> allProperties = new List<List<string>>();
List<string> DbSetAProperties = 
client.DbSetA.GetType().GetProperties().Select(e => e.Name).ToList();
List<string> DbSetBProperties = 
client.DbSetB.GetType().GetProperties().Select(e => e.Name).ToList();
allProperties.Add(DbSetA);
allProperties.Add(DbSetB);
}

My intention is to refactor this so that it accepts a DbSet name as an argument and returns a single list of properties, rather than a list of all properties.





Is it possible to remove a property from a java object at run time?

I have a pojo with jpa anntations. One of the string properties is marked as not nullable. There is some code downstream which sets the value if it is not set. In certain cases this code needs to be triggered but if set the value to empty string this is treaded as a value and its not triggered. I can't set the non null value to null and so I can't edit theobject to trigger the code in a conventional way.

To be honest this bit of code needs a refactoring anyway and I do have a work around but I'm sure I've seen a way to 'remove' the peroperty somewhere before (perhaps reflection ?)

So the class looks something like this...

@Entity
@Table(name="Example")
@SequenceGenerator(name = "seq1", sequenceName = "seq1")
public class Example implements Serializable {

    @Column(name="name", nullable=true, length = 100)
    private java.lang.String name;

    @Column(name="id", nullable=false)      @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ1_Type_SEQ")
    @Id
    private long oID;

    @Column(name="extraval", nullable=false, length = 100)
    private java.lang.String entityVersion;4

...

And extraVal gets set by various jpa/db constraints if it isn't set in the pojo. Sometimes I would like to trigger this, even though it has already been set, but setting the value to empty string sets it to a value and setting to null triggers an error.

I can actually simulate the value in advance and I hope to refactor the code at some point so that I can do all my checks before I create the object in the first place so I'm not look to copy/recreate the object etc. Like I say I'm just sure there is an elegant way to remove the property as a short term solution ?





jeudi 30 mai 2019

Operator '<' cannot be applied to operands of type 'method group' and 'Type'

I'm trying to register automatically the classes for Dependency Injection in a loop instead of manually. However the method I'm using is not compiling.

Method that is working:

containerBuilder.RegisterType<MyClass>().As<IMyClass>();

Method that doesn't compile:

List<Type> servicesList = GetTypesInNamespace(Assembly.GetExecutingAssembly(), "MyNamespace.Services").Where(type => type.IsClass && !type.IsAbstract && !type.IsGenericType && !type.IsNested).ToList<Type>();
for (int i = 0; i < servicesList.Count; i++)
{
    containerBuilder.RegisterType<servicesList[i]>();
}

The compiler throws this error message:

Operator '<' cannot be applied to operands of type 'method group' and 'Type'





Find Class by static value in the class in Java/Kotlin

I have a JSON serialized object, that looks like this

{
  "someData" : ... // data, structure of which varies based on the type of the serialized object
  "typeID" : 42 // integer constant that uniquely identifies type of the serialized object
}

I also have a Java library that looks like this:

abstract class GeneralClass {
  public abstract int getTypeID();
}

class SomeDataClass1 extends GeneralClass {
  public SomeDataClass1(/*arguments depend on type*/) {/*init data fields with arguments*/}

  /*public data fields*/

  public static final int typeID = 42

  @Override
  public int getTypeID() {
    return typeID;
  }
}

Each typeID uniquely identifies one of many classes from the Java library in the manner from the example. To use the functions from the library I need to construct the instance of the class from the serialized data; for that I will use gson. In order for gson to deserialize JSON into an object I need to pass it an instance of the Class object that corresponds to the typeID. How can I get the Class object corresponding to the class if I have its typeID?





How to get all members on a type elegantly?

I've been through "Questions that may already have your answer" and didn't find the thing I'm looking for. I want to get all members on a type via reflection. When I try

var type = typeof(int);
var members = type.GetMembers();
for(var i = 0; i < members.Length; i++)
    Console.WriteLine($"{i, 2} {members[i]}");

I get

0 Int32 CompareTo(System.Object)
1 Int32 CompareTo(Int32)
2 Boolean Equals(System.Object)
// etc. Total 19 items.

I found that some members need specific BindingFlags. Since I don't know those flags and different members have different flags I pass all flags like this:

var type = typeof(int);
var flags =
    BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Instance |BindingFlags.Static |
    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.InvokeMethod |
    BindingFlags.CreateInstance | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty |
    BindingFlags.SetProperty | BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty | BindingFlags.ExactBinding |
    BindingFlags.SuppressChangeType | BindingFlags.OptionalParamBinding | BindingFlags.IgnoreReturn;
var members = type.GetMembers(flags);
for(var i = 0; i < members.Length; i++)
    Console.WriteLine($"{i, 2} {members[i]}");

It gives me 34 members. That's exactly what I need.

But is where a more elegant way to get all members?





Casting classes in generic methods in MEF

I have some classes and interface:

interface IAnimal
{

}

class Cat : IAnimal, ILiveInZoo
{

}
interface ILiveInZoo
{

}

Also, I have some methods and generic methods:

class Context
{
    public ILiveInZoo GetWhoLivesInZoo(string name)
    {
        if (name == "Cat")
            return new Cat();
        return null;
    }
    static CompositionContainer Container = null;
    public void GiveFood<T>(T animal) where T : IAnimal
    {
        var methods = Container.GetExports<Action<T, EventArgs>, AttributeMetadata>();
        //execute methods
    }
}

And here is a use case:

Context context = new Context();
var cat = context.GetWhoLivesInZoo("Cat");
if (cat is IAnimal animal)
{
   context.GiveFood(animal);
}

As you can see in GiveFood metod I'm using MEF. In use case when I cast cat to IAnimal, in GiveFood method typeof(T) will be IAnimal not Cat. First question is: Instance of cat variable is Cat class. Why when I cast it typeof(T) will be IAnimal. My problem is when I cast cat to IAnimal interface, in GiveFood method, GetExports method returns method related to IAnimal not to Cat class. I found solution to fix that issue, it is using reflection:

Context context = new Context();
var cat = context.GetWhoLivesInZoo("Cat");
if (cat is IAnimal animal)
{
   MethodInfo method = typeof(Context).GetMethod(nameof(Context.GiveFood));
   MethodInfo generic = method.MakeGenericMethod(animal.GetType());
   generic.Invoke(context, new object[] { animal });
}

Now typeof(T) is Cat class and in GiveFood I can get methods related to Cat class. Is there another way (without using reflection) to solve this issue?





set visible false to button using reflection, is posible?

I just trying hide button through relfection

Class userClass = Class.forName("vistas.RegistroPersonal");

Field f = userClass.getDeclaredField("btneliminar");

f.setAccessible(true);

f.setVisible(false);

Please help.

Is this possible?.





mercredi 29 mai 2019

OpenGL Water Reflection moves incorretly with camera

Note: This is a copy pasted question from Stack Exchange from a couple years ago but it was never solved and im having literally the exact same problem and our code is pretty much identical because I think we followed the same tutorial. I feel like it is a problem with the matrices being used, but im not sure which one or how to fix it. https://gamedev.stackexchange.com/questions/138306/opengl-water-reflection-seems-to-follow-camera-yaw-and-pitch

I'm attempting to add reflective water to my procedural terrain. I've got it to a point which seems like it's reflecting however when I move the camera left/right/up/down the reflections move with it.

I believe the problem has something to do with the way I convert from world space to clip space for the projective texture mapping.

Here is a gif of what is happening. http://i.imgur.com/PDta5Qu.gifv

Vertex Shader

#version 400
in vec4 vPosition;
out vec4 clipSpace;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main ()
{
  clipSpace = projection * view * model * vec4(vPosition.x, 0.0, vPosition.z, 1.0);
  gl_Position = clipSpace;
}

Fragment Shader

#version 400
in vec4 clipSpace;
out vec4 frag_colour;
uniform sampler2D reflectionTexture;

void main ()
{
    vec2 ndc = (clipSpace.xy / clipSpace.z) / 2.0 + 0.5;
    vec2 reflectTexCoords = vec2(ndc.x, -ndc.y);
    vec4 reflectColour = texture(reflectionTexture, reflectTexCoords);

    frag_colour = reflectColour;
}

I'm using this code to move the camera under the water's surface to get the reflection

float distance = 2 * (m_camera->GetPosition().y - m_water->GetHeight());
m_camera->m_cameraPosition.y -= distance;
m_camera->m_cameraPitch = -m_camera->m_cameraPitch;

If this is insufficient code to diagnose the problem, I'll post more. I tried to keep it to what I thought could be the problem.





java get value of field from array of fields and set field

Wondering how I can get a value of a field from an Array of fields and then depending on that value, set another field in the same array to some value.

For Example:

public void fieldAlter(Field[] fieldArr) {
    for (int i = 0; i < fieldArr.length; i++) {
        Field fieldObj = fieldArr[i];

        if (fieldObj.getName().equals("exampleFieldOne") &&
          fieldObj.getDeclaringClass().getName().equals("some.directory.path.SomeClass")) {
              //Find the index of where field named "exampleFieldTwo" is in 
              //the `fieldArr` array and then set the value for it.
        }
    }
}

Currently, the fieldObj variable will be an object such as:

private java.lang.String some.directory.path.SomeClass

I tried doing the example here, but did not seem to work https://docs.oracle.com/javase/tutorial/reflect/member/fieldValues.html





GetTypeDescriptor(Type objectType, object instance) never gets called?

I'm not so sure about the similar code in .NET but I'm interested in .NET Standard or .NET Core, my custom CustomTypeDescriptor never has a chance to be injected/used because the custom TypeDescriptionProvider does not seem to work, here is a simple implementation (actually not any custom logic added yet):

public class CustomTypeDescProvider : TypeDescriptionProvider
{
    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
    {
        //set breakpoint here and wait forever for its jumping in.
        return base.GetTypeDescriptor(objectType, instance);
    }
}

I've tried adding the custom description provider like this:

public class MyType {
    static MyType(){
       TypeDescriptor.AddProvider(new CustomTypeDescProvider(), typeof(MyType));      
    }
    //...
}

as well as using the TypeDescriptionProviderAttribute like this:

[TypeDescriptionProvider(typeof(CustomTypeDescProvider))]
public class MyType {
   //...
}

It never comes to my set breakpoint inside GetTypeDescriptor(Type objectType, object instance). So with my knowledge, it should be invoked at least when any code accessing the metadata info (attributes, properties, ... such as by using reflection) of the type MyType, but it always seems to use the default provider.

Not any exception raised to tell me that Hey your code will not work, stop hoping for it working, and actually I can even see this event TypeDescriptor.Refreshed triggered after the call TypeDescriptor.AddProvider, which as documented means that it succeeded, well really ridiculous, maybe I don't understand its definition of the so-called success.

Could you please give me any explanation to its not-working in this case? Don't we have any way to make it work? This is especially important to me to make my library project not depend on some dependencies. Thanks!





UnsatisfiedDependencyException: Error creating bean with name 'trafficMapper'

I work with a Spring boot application and get the error provided below,

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'trafficMapper': Unsatisfied dependency expressed through field 'config'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ratepay.iris.ella.config.MasterConfig' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1378)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:575)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:846)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:863)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:88)
    at com.ratepay.iris.ella.service.EllaServiceIntegrationTest.setup(EllaServiceIntegrationTest.java:72)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at com.github.tomakehurst.wiremock.junit.WireMockRule$1.evaluate(WireMockRule.java:73)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ratepay.iris.ella.config.MasterConfig' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1644)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1203)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1164)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
    ... 38 more

The error occurred when I try to do the setup for designing an integration test.

    @Before
    @SuppressWarnings( "resource" )
    public void setup() {
        int port = wireMockRule.port();

        System.setProperty( "ella.uri", "http://localhost:" + port + ELLA_ENDPOINT );
        //        System.setProperty( "freud.master.config", "src/test/resources/test-master-config.json" );
        System.setProperty( "ella.shadowmode", "enabled" );

        ApplicationContext context = new AnnotationConfigApplicationContext( EllaConfiguration.class );
        ellaService = context.getBean( EllaService.class );
    }

This is the LOC that provides the error,

ApplicationContext context = new AnnotationConfigApplicationContext( EllaConfiguration.class );

The EllaConfiguration class is provided below,

@Configuration
@ComponentScan( "com.ratepay.iris.ella" )
public class EllaConfiguration {

    public static final String ELLA_CONNECTOR_BEAN_NAME = "ellaConnector";

    private static final String URI_CONFIG_KEY = "ella.uri";
    private static final String CONNECTION_TIMEOUT_CONFIG_KEY = "ella.connection_timeout";
    private static final String READ_TIMEOUT_CONFIG_KEY = "ella.read_timeout";

    private static final int DEFAULT_CONNECTION_TIMEOUT = 100;
    private static final int DEFAULT_READ_TIMEOUT = 800;

    public static final String ELLA_SHADOW_MODE_KEY = "ella.shadowmode";
    public static final String ELLA_SHADOW_MODE_ENABLED_VALUE = "enabled";

    @Bean( name = ELLA_CONNECTOR_BEAN_NAME )
    public EntityServiceConnectable<EllaResponse> timeoutConfiguration( final Environment env ) {
        return ServiceConnectorBuilder.create( createConnectionConfiguration( env ) ).timeout( createTimeoutConfiguration( env ) ).build();
    }

    private SimpleTimeoutConfiguration createTimeoutConfiguration( final Environment env ) {
        return new SimpleTimeoutConfiguration( env.getProperty( CONNECTION_TIMEOUT_CONFIG_KEY, Integer.class, DEFAULT_CONNECTION_TIMEOUT ),
                                               env.getProperty( READ_TIMEOUT_CONFIG_KEY, Integer.class, DEFAULT_READ_TIMEOUT ) );
    }

    public boolean isEllaShadowModeEnabled( final Environment env ) {
        return env.getRequiredProperty( ELLA_SHADOW_MODE_KEY ).equals( ELLA_SHADOW_MODE_ENABLED_VALUE );
    }

    private PostConnectionConfiguration<EllaResponse> createConnectionConfiguration( final Environment env ) {
        return new SimplePostConnectionConfiguration<>( env.getRequiredProperty( URI_CONFIG_KEY ), EllaResponse.class );
    }
}

The EllaService class is provided,

@Service
public class EllaService {

    public static final int IRIS_ACCEPT = 0;
    public static final int IRIS_REJECT = 100;

    @Autowired
    @Qualifier( ELLA_CONNECTOR_BEAN_NAME )
    private EntityServiceConnectable<EllaResponse> connector;

    @Autowired
    private TrafficMapper trafficMapper;

    @Autowired
    private EllaConfiguration config;

    @Autowired
    private Environment env;

    @Getter
    private boolean shadowModeEnabled = false;

    /**
     * Initialize the service.
     */
    @PostConstruct
    public void initialize() {
        this.shadowModeEnabled = config.isEllaShadowModeEnabled( env );
    }

    /**
     * Asynchronously call Ella. Determine if traffic is applicable for Ella and if yes forward to Ella.
     *
     * @param irisEo
     * @return List<ResultBo>
     * @throws EllaGatewayUnsuccessfulResponseException
     */
    @Async
    public void invokeEllaAsync( final IrisEo irisEo ) throws EllaGatewayUnsuccessfulResponseException {
        invokeEllaSync( irisEo );
    }

    /**
     * Synchronously call Ella. Determine if traffic is applicable for Ella and if yes forward to Ella.
     *
     * @param irisEo
     * @return List<ResultBo>
     * @throws EllaGatewayUnsuccessfulResponseException
     */
    public List<ResultBo> invokeEllaSync( final IrisEo irisEo ) throws EllaGatewayUnsuccessfulResponseException {

        Optional<String> mapId = trafficMapper.getApplicableMapId( irisEo );

        if( mapId.isPresent() && StringUtils.isNotEmpty( mapId.get() ) ) {

            try {
                return irisEo.getOrder().getProducts().stream().map( product -> fetchEllaResult( irisEo, mapId.get(), product ) )
                        .collect( Collectors.toList() );
            }
            catch( EllaGatewayUnsuccessfulResponseException ex ) {
                throw new EllaGatewayUnsuccessfulResponseException( ex.getMessage(), ex.getCause() );
            }
        }
        return Collections.emptyList();
    }

    private ResultBo fetchEllaResult( final IrisEo irisEo, String mapId, String product ) throws EllaGatewayUnsuccessfulResponseException {

        HttpHeaders freudHeaders = createRequestHeaders( irisEo );

        ServiceResponse<EllaResponse> response = connector
                .call( EllaDtoConverter.convertToRequest( irisEo, mapId, product ), freudHeaders );

        if( !response.isSuccess() ) {
            throw new EllaGatewayUnsuccessfulResponseException( response.getErrorMessage(), response.getException().getCause() );
        }

        EllaResult prediction = response.getResponse().getResult();

        return convertToResultBo( prediction, product );

    }

    private ResultBo convertToResultBo( EllaResult prediction, String product ) {

        ClassificationResult classification = prediction.getClassification();
        final int irisPrediction = ClassificationResult.FRAUD.equals( classification ) ? IRIS_REJECT : IRIS_ACCEPT;
        //        final int irisPrediction = Integer.valueOf( classification.getValue() ) < 900 ? IRIS_REJECT : IRIS_ACCEPT;

        return new ResultBo( product, irisPrediction );
    }

    private HttpHeaders createRequestHeaders( final IrisEo irisEo ) {

        HttpHeaders freudHeaders = new HttpHeaders();

        freudHeaders.add( ACCEPT, APPLICATION_JSON_UTF8_VALUE );
        RatepayHeaders.append( freudHeaders, irisEo.getRequestInfo() );

        return freudHeaders;
    }

}

I get an NPE from the invokeEllaSync method in the LOC,

Optional<String> mapId = trafficMapper.getApplicableMapId( irisEo );

The TrafficMapper class is provided,

@Component
public class TrafficMapper {

    @Autowired
    private MasterConfig config;

    private final Map<Integer, String> shopIdToMapId = new HashMap<>();

    /**
     * Initialize the component.
     */
    @PostConstruct
    public void initialize() {
        fillShopIdMap();
    }

    /**
     * Return an optional holding a specific map id.
     *
     * @param irisEo
     * @return Optional<String>
     */
    public Optional<String> getApplicableMapId( IrisEo irisEo ) {

        Integer shopId = irisEo.getOrder().getShopId();
        return Optional.ofNullable( this.shopIdToMapId.get( shopId ) );
    }

    private void fillShopIdMap() {

        this.config.getTrafficMappings().stream().forEach( trafficMapping -> trafficMapping.getTrafficDescription().getShopIds().stream()
                .forEach( shopId -> this.shopIdToMapId.put( shopId, trafficMapping.getMapId() ) ) );
    }
}

The MasterConfig class is provided,

@Getter
@Setter
@ToString
public class MasterConfig {

    @NotNull
    @JsonProperty( "traffic_mappings" )
    private List<TrafficMapping> trafficMappings;
}

The reason I provided the classes is I am unable to find the issue and wanted to provide more information for the investigation.

How do I solve the UnsatisfiedDependencyException error?





Mockito default behaviour and custom behaviour with methods with identical return types

Supossing I have the following code to test UserController by mocking UserService:

public class UserControllerTest {
    private final List<User> users1 = new ArrayList<>();
    private final List<User> users2 = new ArrayList<>();

    @Before
    public void initUsers() {
        User user = new User();
        user.setId(1L);
        users1.add(user);

        User user = new User();
        user.setId(2L);
        users2.add(user);
    }

    @Test
    public void testList() throws Exception {
        UserService userService = mock(UserService.class); //line1

        when(userService.findAll1()).thenReturn(users1); //line2
        when(userService.findAll2()).thenReturn(users2); //line3


        SingerController singerController = new SingerController();
        ReflectionTestUtils.setField(singerController, "singerService", singerService);
        List<User> users3 = singerController.findAll1(); //line4
        List<User> users4 = singerController.findAll2(); //line5

        ...
    }
}

I have the following doubts:

  1. When the line1 is reached, what would be the default behaviour for userService.findAll1() and userService.findAll2()?
  2. When the line3 is reached, as userService.findAll1() and userService.findAll2() return the same result type (List<User>). Will the line3 override the behaviour defined in line2? I mean, will userService.findAll1() return users2 instead of users1?




mardi 28 mai 2019

AppDomain.CurrentDomain.GetAssemblies() didn't give the project reference

I have many projects in my solutions (.net core).

enter image description here

API and Web.Framework are used by API.IntegrationTest project. When I compile solution, dll files of API and Web.Framework are created in API.IntegrationTest but while API.IntegrationTest is running, I can't reach those dll files. To do this, I use AppDomain.CurrentDomain.GetAssemblies() method and I'm sure and see dll files in domain folder but they don't come using AppDomain.CurrentDomain.GetAssemblies(). Is there anyone who has any theory about this scenario?





GetType return Int instead of System.Int32

GetType().ToString() returns the FullName of the object. I want the name that you usually use to instantiate that object, i.e, int instead of Int32. Is there a way to do this?





How to get the type of each union case for a given union type in F#

I am wondering in the F# code below how to fetch the type associated with each union case via reflection

type AccountCreatedArgs = {
    Owner: string
    AccountId: Guid
    CreatedAt: DateTimeOffset
    StartingBalance: decimal
}

type Transaction = {
    To: Guid
    From: Guid
    Description: string
    Time: DateTimeOffset
    Amount: decimal
}

type AccountEvents =
    | AccountCreated of AccountCreatedArgs
    | AccountCredited of Transaction
    | AccountDebited of Transaction


I tried using FSharpType.GetUnionCases(typeof<AccountEvents>) but UnionCaseInfo does not provide any information about the case type (only the declaring type aka AccountEvents so not really useful in my case) =/





How to get function from function type?

Suppose I have hold of the concrete type of a normal, named Julia function, typeof(f). Is it possible to get back f from that? I assume this should work in principle, since typeof(f) is a singleton type.





Generate a swagger file from unknown objects (.net)

I want to develop a new API. It must connect a Dynamics CRM and front developers.

Today, the developed "workaround" is :

  1. Fill an Excel file to describe the CRM and custom objects (with fetchXml, ...)
  2. Write and concatenate strings to write a YAML file.
  3. Copy this file to swagger editor and make tests with Postman

In a first step, I want to generate the schema without strings concatenations... (temporarily, waiting to replace the Excel file with OData and ASP.NET Core to have something more powerful)

For the moment, I use reflection to build my objects from the Excel file:

using System.Reflection;
using System.Reflection.Emit;
using Swashbuckle.Swagger;
...

var assemblyName = new AssemblyName(Guid.NewGuid().ToString();
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("Module");
var typeBuilder = moduleBuilder.DefineType(entity.CrmEntityName);
foreach (var attribute in entity.Attributes)
{
    Type t = typeof(int);
    switch (attribute.DataType.ToLower())
    {
        case "string":
            t = typeof(string);
            break;
        case "integer":
            t = typeof(int);
            break;
        case "date":
            t = typeof(DateTime);
            break;
    }
    typeBuilder.DefineField(attribute.CrmName, t.GetType(), FieldAttributes.Public);
    var type = typeBuilder.CreateType();

    // create the Swagger models here
}

How can I generate my swagger from these types and properties? I've view an object named Schema which contains a name and another Schema, I don't know if is a wrong way...





Use type to access properties instead of concrete instance

I'm having trouble figuring out how to ask this question (the title is not worded well), so let me start with an example using the NameOf() method, because it does something similar to what I'm trying to accomplish.

If I have a class like this:

Public Class MyClass
    Public Property Foo As Bar
End Class

and then I declare an instance of it Dim instance As New MyClass, I can then use the NameOf() method in one of two ways:

' Both of these lines will print "Foo"
Console.WriteLine(NameOf(instance.Foo))
Console.WriteLine(NameOf(MyClass.Foo))

I would like to implement a method that can accept similar types of parameters, but I cannot figure out how. Here is the (extension) method I wrote:

<Extension()>
Public Function GetPathOfProperty(Of T As Class, TProp)(myObj As T, prop As Expression(Of Func(Of TProp))) As String
    Dim result As String = String.Empty
    Dim foundName As String = String.Empty
    Dim className As String = myObj.GetType().Name
    Dim p As MemberExpression = TryCast(prop.Body, MemberExpression)

    While p IsNot Nothing
        If className = p.Member.DeclaringType.Name Then
            foundName = className + "."
        End If

        result = foundName + p.Member.Name + "." + result
        If Not String.IsNullOrEmpty(foundName) Then
            Exit While
        End If
        p = TryCast(p.Expression, MemberExpression)
    End While

    Return IIf(String.IsNullOrEmpty(foundName), "", result.Substring(0, result.Length - 1))
End Function

Using my above example, I can use it like this:

' Prints "MyClass.Foo"
Console.WriteLine(instance.GetPathOfProperty(Function() instance.Foo)) 
' Prints "MyClass.Foo.SomeBarProperty"
Console.WriteLine(instance.GetPathOfProperty(Function() instance.Foo.SomeBarProperty)) 

I would like to create another version of this method that is not an extension method, but rather a static method that can be called like (or similar to) this:

Console.WriteLine(GetPathOfProperty(Function() MyClass.Foo) ' Prints "MyClass.Foo"

This way I'd be able to use the function without actually creating an instance of MyClass first. And this is where I need help. Since MyClass is not a static class, I'm not able to put MyClass.Foo in the function call. My first thought was to use Reflection, but I can't figure out how. Is there a parameter type I could use to allow me to do this (and if so, how would that look)? Or is this just a pipe-dream and not possible?





Combining reflection, enums and generics in Kotlin, type inference fails, but I don't know it as well

I'm using reflection to load an Enum class I'm using to integrate with an existing Java application. In Java this is written as (in a class ValueUtil):

static <E extends Enum<E>> Class<E> getEnumType(String typeAsString) { ..reflection stuff.. }

In Kotlin I try to use the result of this method.

private fun createEnumParameter(type: String, value: String, id: String?): EnumParameter<*> {
    val clazz = getEnumType(type)
    return createParam(clazz, value, id)
}

private fun <E: Enum<E>> getEnumType(type: String): Class<E> {
    return ValueParseUtil.getEnumType<E>(type)
}

private fun createParam(...): ... { ... }

However, the compiler states: Type inference error

So I try as best as I can to specify what I know (Enum<*>): Enum<*> error

This fails due to enum recursion in the generics (which I/Kotlin/Java need(s) by the way).

Is reflection + enums + generics a recipe for compiler errors?

Any suggestions how to fix this?

Best regards,

Michiel





Identifying the class type for arguments required in gerDeclaredMethod in java

I am using Java Reflection to invoke a method xyz with these 4 parameter types:

Set<LineItems> 
Document
String
Profiler

While using getDeclaredMethod I am required to give the method argument type. If String's argument type is String.class, what should be done for Set<LineItems>?

Also the function xyz is a default function in interface abc. This interface is being implemented in multiple other classes, so method should be reflected in this only. Here is my code:

Class c = abc.getClass();

Class args[] = new Class[4];
args[0] = Set.class;
args[1] = String.class;
args[2] = Event.class;
args[3] = Profiler.class;

Method m = c.getMethod("xyz",args) ;

I know there are multiple flaws in this. Any help?





Unable to use java.lang.reflect.Field.modifiers in Java 11

Recently passed from Java 9 to Java 11 where the code below used to work fine :

        final Field a = bb.class.getDeclaredField("a");
        a.setAccessible(true);
        final Field b = bb.class.getDeclaredField("b");
        b.setAccessible(true);
        final Field modifersField = Field.class.getDeclaredField("modifiers");
        modifersField.setAccessible(true);
        modifersField.setInt(a, ~Modifier.FINAL & a.getModifiers());
        modifersField.setInt(b, ~Modifier.FINAL & b.getModifiers());
        a.set(null, BigInteger.valueOf(5));
        b.set(null, BigInteger.valueOf(5));
        modifersField.setAccessible(false);

But in Java 11 i get this error :

java.lang.reflect.InaccessibleObjectException: Unable to make field private int java.lang.reflect.Field.modifiers accessible: module java.base does not "opens java.lang.reflect" to module 

I tried added VM Parameters like :

--add-exports
javafx.base/java.lang.reflect=com.goxr3plus.applicationName

But again nothing ... just a warning and application crashes :

WARNING: package java.lang.reflect not in javafx.base

What am i doing wrong ?





Is there a way to invoke a generic method from an async thread?

In order to avoid boilerplate, and handling a very specific SDK with customised API transactions, I would try to pass on a generic method, that would be invoked and executed asynchronously.

I have tried using RxJava, the EventBus and AsyncTask. However, whenever it would get there, I would always get a android.os.NetworkOnMainThreadException.

I did use an interface, which obviously works perfectly fine, but I was wondering why can't the same apply to a generic method? Is it because I don't specifically send the whole object on the new thread?

If I would send an instance of an object, then, given that each method has a different name, it would not be convenient invoking the specific method (unless the name was passed on as a String, perhaps?).

The code that would run on the new thread would be a variation of the following:

public <T> void invokeMethod(T item) throws InvocationTargetException, IllegalAccessException {
        if (item instanceof Method) {
            ((Method) item).invoke(this, (Object[]) null);
        }
    }

Obviously, usually methods run properly when I do that, but they are always executed on the main thread.





Replace a parameter in an expression with a constant

I have an expression of type Expression<Func<TElement, TElement, bool>> and a constant of type TElement. I need an expression of type Expression<Func<TElement, bool>> with one of the parameters replaced by the constant. In other words, I need the body to the following method:

public static Expression<Func<TElement, bool>> ReplaceParameter<TElement>
(
    Expression<Func<TElement, TElement, bool>> inputExpression,
    TElement element
)
{
    ...
}

If I call ReplaceParameter((i1, i2) => i1 > i2, 5), I expect the result to be i => i > 5.

I was thinking, it might be able to recursively deconstruct and then reconstruct the input expression and replace all occurrences of the second parameter with a constant expression. Since there are so many different kind of expressions, I'm unsure on how to do that, though.





lundi 27 mai 2019

MethodHandles throws IllegalAccessException when accessing sun.nio.ch in Java 11

I upgraded my jdk from 8 to 11, and then the ChronicleMap failed to init itself, throwing exceptions like

Caused by: java.lang.IllegalAccessException: member is private: sun.nio.ch.FileChannelImpl.unmap0[Ljava.lang.Object;@21f50d2c/invokeStatic, from net.openhft.chronicle.core.OS (unnamed module @8bc0696)
  at java.base/java.lang.invoke.MemberName.makeAccessException(MemberName.java:942)
  at java.base/java.lang.invoke.MethodHandles$Lookup.checkAccess(MethodHandles.java:2215)
  at java.base/java.lang.invoke.MethodHandles$Lookup.checkMethod(MethodHandles.java:2155)
  at java.base/java.lang.invoke.MethodHandles$Lookup.getDirectMethodCommon(MethodHandles.java:2299)
  at java.base/java.lang.invoke.MethodHandles$Lookup.getDirectMethodNoSecurityManager(MethodHandles.java:2292)
  at java.base/java.lang.invoke.MethodHandles$Lookup.unreflect(MethodHandles.java:1756)
  at net.openhft.chronicle.core.OS.<clinit>(OS.java:79)
  ... 52 common frames omitted

This exception is caused by the source code in net.openhft.chronicle.core.OS at line 79:

Method unmap0 = Jvm.getMethod(FileChannelImpl.class, "unmap0", long.class, long.class); // this line worked
UNMAPP0_MH = MethodHandles.lookup().unreflect(unmap0); // this line failed

MethodHandles.lookup() failed to unreflect this method in java 11 (most possibly because of modularity)

I tried to add arguments to jvm like this issue suggests: https://github.com/OpenHFT/Chronicle-Core/issues/15

And my jvm param now includes:

--add-exports java.base/sun.nio.ch=ALL-UNNAMED 

(Or add-opens, not working either)

--add-opens java.base/sun.nio.ch=ALL-UNNAMED 

The maven plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <source>11</source>
        <release>11</release>
        <compilerArgs>
            <arg>--add-opens</arg>
            <arg>java.base/sun.nio.ch=ALL-UNNAMED</arg>
        </compilerArgs>
    </configuration>
....

But it didn't work.

It seems chronicle-map had solved this issue, but I'm still getting these exceptions in Java 11.

chronicle-map version:

<groupId>net.openhft</groupId>
<artifactId>chronicle-map</artifactId>
<version>3.17.2</version>





Parametr does not have correct annotation

I am trying to perform null checks on my methods using simple custom @NotNull annotation i.e. I declare method as myMethod(@NotNull String name, String description) and when someone calls this method with null value passed as the 'name' argument an exception is thrown.

I already have an implementation of a simple aspect using aspectj. This solution works quite well for me. The one exception is constructors of inner classes. In such case the aspect crashes because of an exception inside java.lang.reflect.Parameter (I changed some method names):

....
Caused by: java.lang.ArrayIndexOutOfBoundsException: 2
  at java.lang.reflect.Parameter.getDeclaredAnnotations(Parameter.java:305) ~[na:1.8.0_161]
  at java.lang.reflect.Parameter.declaredAnnotations(Parameter.java:342) ~[na:1.8.0_161]
  at java.lang.reflect.Parameter.getAnnotation(Parameter.java:287) ~[na:1.8.0_161]
  at java.lang.reflect.Parameter.getDeclaredAnnotation(Parameter.java:315) ~[na:1.8.0_161]
  at my.package.core.common.validation.ValidationAspect.checkNotNullArguments(ValidationAspect.java:42) ~[ybus-web-1.0.jar:na]
  at my.package.server.web.admin.commission.MyOuterClass$MyInnerAnonymousClass.<init>(MyOuterClass.java:344) ~[ybus-web-1.0.jar:na] at 
....

As far as I can tell this is caused by java passing the enclosing class object as the first argument to the constructor of the inner class (which I was told is standard behavior). The problem is, that params[i].executable.getParameterAnnotations() does not seem to know about the additional argument and returns annotations only for the "normal" parameters

Relevant part of the aspect:

 @Before("anyConstructorWithNotNullParam() || anyMethodWithNotNullParam()")
  public void checkNotNullArguments(
      final JoinPoint joinPoint
  ) {
    final Signature signature = joinPoint.getSignature();
    final Object[] args = joinPoint.getArgs();
    final Parameter[] params = signature instanceof ConstructorSignature
        ? ((ConstructorSignature) signature).getConstructor().getParameters()
        : ((MethodSignature) signature).getMethod().getParameters();

    for (int i = 0; i < args.length; i++) {
        if (args[i] == null && params[i].getDeclaredAnnotation(NotNull.class) != null) {
          throw new IllegalArgumentException("Illegal null argument");
        }
    }
  }

I feel like this is a bug in either aspectj or java.lang.reflection. But as I cannot find any bug report for this, it seems more likely to me that I am doing something wrong. The app runs on java 8 (tried multiple different builds of the oracle jdk and the last openjkd build) and aspectj 1.8.13 (but tried also 1.9.4).

So my question(s): Is this a known bug? Is there some flaw in my implementation? Is there some workaround? (I guess it would not be that hard to match the annotations to the parameters manually. But as I have very limited knowledge about java reflection, I am not really able to foresee the consequences).





dimanche 26 mai 2019

What if an object's fields is an object...is there a way to get the latter object's fields?

I'm writing a program wherein I need to check an object's field values. For example, I have a class called Book which has String bookName, String publisher, and Author author. In Author, it has fields such as String firstName, String lastName, String dateOfBirth. I want to get the author's last name and change it to a new last name by looking through the fields of the Book. Also, I have to implement my method in a way wherein any kind of object can be used so method can also be used when changing first name of just the author.

I have used getDeclaredFields() to loop through the fields of my Book object, and am trying to find if one of the fields is its own object.

I have used "instanceof" Author but I need to find a way that doesn't need my hardcoding of the class name "Author"

public ArrayList<String> makeChanges(Object book){
ArrayList<String> changeList= new ArrayList<String>;
try{
Field[] bookFields = book.getClass().getDeclaredFields();

String changes = "";

for (Field field: bookFields){
    field.setAccessible(true);
    if (field.getName().equals("firstName")){
        if (!(field.get(book).equals("Twilight"))){
            changes = field.getName() + changed to "Twilight";
            changeList.add(changes);
        }
    if (field.get(book) instanceof Author){
        List<String> authorChanges = makeChanges(field.get(book));
        changes = Arrays.toString(authorChanges.toArray()).replace("[","").replace("]","");
        changeList.add(changes);
    }
}

catch(Exception e){
System.out.println(e.toString());
}

return changeList;
}

Actual result: [bookName changed to "Twilight", author changed to "demo.Address@16f65612"]

Expected result should be: [bookName changed to "Twilight", firstName changed to "Eli"]





C# reflection datatype

I would like to optimize the below code The only difference is the datatypes RadioButton, Label, and Button. Outside the method I have an loop that iterates over all the controls in the page.

if (control is RadioButton)
{
    try
    {
        (control as RadioButton).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as RadioButton).Text = "Key not found: " + control.ID;
    }
}
else if (control is Label)
{
    try
    {
        (control as Label).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as RadioButton).Text = "Key not found: " + control.ID;
    }
}
else if (control is Button)
{
    try
    {
        (control as Button).Text = SPContext.Current.Web.Locale.LCID == 1033 ?
        DataBinder.Eval(keys.en, control.ID).ToString() :
        DataBinder.Eval(keys.sv, control.ID).ToString();
    }
    catch (Exception)
    {
        (control as RadioButton).Text = "Key not found: " + control.ID;
    }
}





vendredi 24 mai 2019

Could not load type 'System.Runtime.CompilerServices.IAsyncStateMachine' from assembly 'System.Runtime'

I had previously been having issues getting reflection to work properly in T4 Templates targeting the .Net Core framework. I resolved that through the answer on my previous thread, which may be important as the binding redirect may have some impact on my current issue. T4 Template Could not load file or assembly 'System.Runtime, Version = 4.2.0.0'

I managed to get the templates to generate properly, but only if they were referencing assemblies other than their own. Now I have a case where I have a T4 Template referencing the assembly/project the file is currently located in, and am getting this error: System.TypeLoadException: Could not load type 'System.Runtime.CompilerServices.IAsyncStateMachine' from assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

My template code is as follows:

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Reflection" #>
<#@ assembly name="$(TargetDir)Services.dll" #>
<#@ assembly name="$(NuGetPackageRoot)\automapper\8.0.0\lib\netstandard2.0\AutoMapper.dll" #>
<#@ import namespace="Services" #>
<#@ import namespace="Services.Resources.Attributes" #>
<#@ import namespace="Services.Resources.DataTransferObjects.Infrastructure" #>
<#@ output extension=".cs" #>
//Autogen code
//This code is autogen. Do not make any changes to this file

namespace Services
{
    <#
    var classes = System.Reflection.Assembly.GetAssembly(typeof(BaseService))
                .GetTypes()
                .Where(p => !p.IsAbstract && p.BaseType == typeof(BaseService))
                .ToList();
    #>
}

As a reminder, I am forcibly using System.Runtime version 4.0.0.0 since that seems to be the only that to work properly for T4 Templates targeting .Net Core frameworks. Is there something similar I can do to point to the System.Runtime.CompilerServices namespace?





Java Proxy Wrapper - Reflection

I created this proxy wrapper to handle invoking of methods. Seems to work, I was just wondering if anyone can check and tell me if something can be improved and why?

Cheers!

stackover is complaining I need to write more so this is just fillers...lol

IGNORE

Video provides a powerful way to help you prove your point. When you click Online Video, you can paste in the embed code for the video you want to add. You can also type a keyword to search online for the video that best fits your document. To make your document look professionally produced, Word provides header, footer, cover page, and text box designs that complement each other. For example, you can add a matching cover page, header, and sidebar. Click Insert and then choose the elements you want from the different galleries. Themes and styles also help keep your document coordinated. When you click Design and choose a new Theme, the pictures, charts, and SmartArt graphics change to match your new theme. When you apply styles, your headings change to match the new theme. Save time in Word with new buttons that show up where you need them. To change the way a picture fits in your document, click it and a button for layout options appears next to it. When you work on a table, click where you want to add a row or a column, and then click the plus sign. Reading is easier, too, in the new Reading view. You can collapse parts of the document and focus on the text you want. If you need to stop reading before you reach the end, Word remembers where you left off - even on another device.

Ok HERE IS THE CODE

import java.lang.reflect.Method;

public class ProxyWrapper
{
    Class<?> c = null;
    Object o = null;
    String namespace = null;
    String className = null;
    Thread tCleanup;
    HouseKeeping houseKeeping = null;
    Boolean closing = false;
    long idle_start = System.currentTimeMillis();
    int timeout = 10000;

    public ProxyWrapper()
    {
        CreateHouseKeeping();
    }

    public ProxyWrapper(String namespace, String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException, Exception
    {
        msg("new ProxyWrapper");
        this.namespace = namespace;
        this.className = className;

        msg("calling INIT");
        INIT();

        CreateHouseKeeping();
    }

    private void CreateHouseKeeping()
    {
        msg("creating housekeeping");
        houseKeeping = new HouseKeeping();
        houseKeeping.SetParent(this);
        tCleanup = new Thread(houseKeeping);
        tCleanup.start();
    }

    public void msg(Object e)
    {
        if(e.getClass() == String.class)
        {
            System.out.println((String)e);
        }
        if(e.getClass() == Exception.class)
        {
            System.out.println(((Exception)e).toString());
        }
    }

    public int GetTimeout()
    {
        return timeout;
    }

    public long GetIdleTime()
    {
        return idle_start;
    }

    public void SetIdleTime(long value)
    {
        idle_start = value;
    }

    public Boolean GetClosing()
    {
        return closing;
    }

    public void SetClosing(Boolean value)
    {
        closing = value;
    }

    private void INIT()throws ClassNotFoundException, InstantiationException, IllegalAccessException, Exception
    {
        if(namespace == null || namespace.length()==0)
            throw new Exception("Namespace property not set");
        if(className == null || className.length()==0)
            throw new Exception("Classname property not set");

        c = Class.forName(namespace+"."+className); 
        o= c.newInstance(); 
    }

    private class HouseKeeping implements Runnable
    {
        ProxyWrapper parent = null;

        public HouseKeeping()
        {

        }

        public void SetParent(ProxyWrapper parent)
        {
            this.parent = parent;
        }

        @Override
        public void run()
        {
            long t = 0;
            while (!parent.GetClosing())
            {
                try
                {
                    t = (System.currentTimeMillis() - parent.GetIdleTime()); 
                    msg("Housekeeping, checking idle session: " + t);
                    Thread.sleep(200);
                    if( t > parent.GetTimeout() )
                    {
                        msg("Session idle expired, finilizing");
                        parent.SetIdleTime(System.currentTimeMillis());
                        parent.finalize();
                        //break;
                    }
                }
                catch (Throwable e)
                {
                    msg(e);
                }
            }
        }
    }

    public Object Invoke(String method, Object[] args) throws Exception
    {
        //Method m = null;
        Method[] methods = null;

        try
        {
            if(method==null ||method.length()==0)
                throw new Exception("Method name is null/empty");

            msg("Invoking method " + method);

            if(o==null)
                INIT();

            SetIdleTime(System.currentTimeMillis());

            //m = o.getClass().getMethod(method);

            methods = c.getMethods();

            for (Method m : methods) {
                msg(m.getName());
                if (method.equals(m.getName())) {
                    return m.invoke(null, args);
                }
            }

            throw new ClassNotFoundException("Method not found " + method);
        }
        finally
        {
            methods = null;
        }

    }

    @Override
    public void finalize() throws Throwable
    {
        try
        {
            msg("entering finalize");
            closing = true;
            c = null;
            o = null;
        }
        catch(Throwable t)
        {
            msg(t);
            throw t;
        }
        finally
        {
            msg("leaving finalize");
            super.finalize();
        }
    }
}





jeudi 23 mai 2019

Is it possible to make a foreach loop for fields in a class using IEnumerable?

I was wondering if it would be possible to make the fields of a class enumerable so you could iterate over them with a for or foreach loop. I have seen a few versions describing how to make a structure containing other structures be enumerated in that way.

I am also aware I may have completely misread the MSDN article on the subject.

So my question is, is it possible to iterate over fields in a class using IEnumerable or a similar Interface?

I would like to do something like this:

private class Integers
{
    public int int1;
    public int int2;
    public int int3;
    public int int4;
    public int int5;
    public int int6;
    public int int7;
    public int int8;
}

foreach(int I in Integers){
    Console.WriteLine(I); 
}





How can I print all local and global variables in case of an unhandled exception?

As a part of logging system for a vb.net application I am developing, in case of an unhandled exception (MyApplication_UnhandledException call in the Application Events) I want to dump the names and values of every global variable in every class, and the local variables of the function/sub that caused the exception, to a local .log file, which the clients could send back to me for debugging. I know this must be done through reflection, but I cannot figure out how to do it. I need this because the Stack Trace (which I also dump to the log file) doesn't store the values of function parameters, nor the values of global variables.

This is the part I have for global variables:

    Dim assbly As Assembly = [Assembly].GetExecutingAssembly()
    Dim types As Type() = assbly.GetTypes()

    For Each t As Type In types
        For Each p As FieldInfo In t.GetFields()
            Logger.addToLog(p.Name & "  - " & p.FieldType.Name) 'should also get value, maybe with p.getValue() ?
        Next
    Next

Unfortunately, it only prints the Public global variables of each class, while I need Private ones too. Also, this doesn't print the values. The p.getValue() call requires an object as a parameter, but I can't seem to understand what exactly should I give to it. As for the local variables, I haven't been able to come up with anything yet, and I hope someone here might know. I also get the feeling that there must be some better way to achieve what I want. Can someone advise, please?





Are there any concrete, easy-to-understand examples on how to dynamically invoke a function in C#?

I'm currently doing an internship where I am learning C# from the ground up. My mentor has given me an exercise to demonstrate dynamic invocation. However, since I am completely new to this language, I have no idea how to implement it. I have also found there aren't that many resources that explain it very well.

This is just for a learning ramp up so I have currently been fooling around with basic functions that I can call. I have seen that this is the way to call any function you want / multiple functions at once at runtime.

public void Invoke(string typeName, string functionName)
{

            Type type = Type.GetType(typeName);
            dynamic c = Activator.CreateInstance(type);
            //args contains the parameters(only string type)
            type.InvokeMember(functionName, BindingFlags.InvokeMethod, null, c, args);

}

I'm calling it like this (This gives an error)

Invoke("void", "StringDemoPrint");

I honestly do not understand what this function is supposed to do or what it is supposed to look like when called and executed correctly. I am completely lost as to what it means.





How to check if a MethodInfo is a specific interface method

Lets assume the following interface

interface Foo {
    void Bar();
    void Bar(string str);
    int Bar(int i);
    IEnumerable<string> Bar1();
    void Bar1(string str);
    void Bar1(int i);
    //...
}

lets assume a method that receives a method info. How can I check if this method info is about a specific method on the interface?

void DoStuff(MethodInfo method){
     //basically in pseudo code
     if(method is Foo.Bar(string)){
         //dostuff
     }
}

The closest I got is something like

if(method.ReflectedType.IsAssignableFrom(typeof(Foo))
   && method.Name == nameof(Foo.Bar) 
   && method.GetParameters().Length == 1
   && method.GetParameters()[0].ParameterType == typeof(string))

However, this is quite verbose, and not refactor proof.

In a next step I would like to have a method that can check against a list of MethodInfo. Something like

bool IsIn(this MethodInfo self, IEnumerable<??> methods){
     //again, pseudo code
     return methods.Any(m => m is self);
}

That can easly be used like

bool b = methodInfo.IsIn(new [] {
    Foo.Bar(str),
    Foo.Bar1(int)
});





Counting properties of a particular class?

I'm trying to retrieve the number of properties of a certain type. For example in class Player:

public Player(string name, Stat endurance, Stat sprint, Stat dribble, Stat passing, Stat shooting)
{
   //Some code
}

public Stat Endurance { get; private set; }
public Stat Sprint { get; private set; }
public Stat Dribble { get; private set; }
public Stat Passing { get; set; }
public Stat Shooting { get; private set; }

public double OverallSkillLevel { get; private set; }    {

public string Name { get; private set; }    

public void CalculateAverage()
{        
    double sumOfStat = this.Endurance.Level + this.Sprint.Level + 
                       this.Dribble.Level + this.Shooting.Level + 
                       this.Passing.Level;
    //MethodOne:
    Type type =    this.GetType();
    int countOne = type .GetProperties().Count(x => x.MemberType is Stat);

    //MethodTwo
    double countTwo = this.GetType().GetFields().Count(x => x is Stat);

    //this.OverallSkillLevel = Math.Round((sumOfStat /  ), 0);
}

I expect the variables "countOne " or "countTwo " to return me as a count only the properties that are Stat. But I always get 0





mercredi 22 mai 2019

Reflection with ViewPager

I've done a VerticalViewPager by extending the android.support.v4.view.ViewPager class..

Now I am trying to reflect a field of the class. My goal is to change the sensitivity of the scrolling effect of the (Vertical)ViewPager. Netherless nothings changes, it doesn't seem to have any effect on the fields of the super class. I already tried to change other fields such as "DEBUG" but there isn't any change right now. I can't understand why.

Thanks for any help in advance.

. . . . . . . . . . .

This is the reflection code right now:

Field mFlingDistance;
        mFlingDistance = ViewPager.class.getDeclaredField("mFlingDistance");
        mFlingDistance.setAccessible(true);

        // Set custom value:
        mFlingDistance.set(this, 20);

Whole VerticalViewPager Class:

package de.XXX.app.Activitys.fragments;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

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

public class VerticalViewPager extends ViewPager {
    public VerticalViewPager(Context context) {
        super(context);
        init();
    }

    public VerticalViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {

        try {
            Field mFlingDistance;
            mFlingDistance = ViewPager.class.getDeclaredField("mFlingDistance");
            mFlingDistance.setAccessible(true);

            // Set custom value:
            mFlingDistance.set(this, 20);
        }catch (Exception e){
            System.out.println("SMTH Happend!:(");
        }

        setPageTransformer(true, new VerticalPageTransformer());
        setOverScrollMode(OVER_SCROLL_NEVER);
    }

    private class VerticalPageTransformer implements ViewPager.PageTransformer {

        @Override
        public void transformPage(View view, float position) {

            if (position < -1) {
                view.setAlpha(0);
            } else if ( position <= 1) {
                view.setAlpha(1);

                view.setTranslationX(view.getWidth() * -position);

                float yPosition = position * (view.getHeight()/(1/0.6f));
                view.setTranslationY(yPosition);
            } else {
                view.setAlpha(0);
            }
        }
    }

    private MotionEvent swapXY(MotionEvent ev) {
        float width = getWidth();
        float height = getHeight();

        float newX = (ev.getY() / height) * width;
        float newY = (ev.getX() / width) * height;

        ev.setLocation(newX, newY);

        return ev;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean intercepted = super.onInterceptTouchEvent(swapXY(ev));
        swapXY(ev);
        return intercepted;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return super.onTouchEvent(swapXY(ev));
    }


    private static void setFinalStaticField(Class<?> clazz, String fieldName, Object value)
            throws ReflectiveOperationException {
        Field field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);
        Field modifiers = Field.class.getDeclaredField("modifiers");
        modifiers.setAccessible(true);
        modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, value);
    }

}





Creating POJO/beans dynamically and set values using CGLib

I have a requirement to parse a text file and generate JSON document. The text file has a pattern of text which contains a key which is a name and the value is a huge text of TSV with headers.

I could parse the text file and generate bean classes using the headers and now i want to set the data to this generated bean class. I am using reflection to do this.

Class<?> beanClass = BeanClassGenerator.beanGenerator(k, mapForBeanGeneration);
            try {
                Object beanClassObject = beanClass.newInstance();
                lines.forEach(line -> {
                    if (line != null && !line.isEmpty() && !line.equals("null")) {
                        String[] lineData = line.split("\t");
                        System.out.println("LineData length :: " + lineData.length);
                        Method[] methods = beanClass.getMethods();
                        System.out.println("Methods length :: " + methods.length);
                        int index = 0;
                        for (Method m : methods) {
                            m.setAccessible(true);
                            if (m.getName().startsWith("set")) {
                                try {
                                    if ((lineData.length <= index) && lineData[index] != null) {
                                        m.invoke(beanClassObject, lineData[index]);
                                        index++;
                                    } else {
                                        m.invoke(beanClassObject, " ");
                                    }
                                } catch (IllegalAccessException | InvocationTargetException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                });
                ObjectMapper om = new ObjectMapper();
                System.out.println(om.writeValueAsString(beanClassObject));
            } catch (InstantiationException | IllegalAccessException | JsonProcessingException e) {
                e.printStackTrace();
  }});

The problem with the approach is that most of the times all the column values may not have data it can be nulled.

I am wondering if there is an easier way of doing this. Any help is appreciated.

Here is the bean generation method.

public static Class<?> beanGenerator(final String className, final Map<String, Class<?>> properties) {
        BeanGenerator beanGenerator = new BeanGenerator();
        beanGenerator.setNamingPolicy(new NamingPolicy() {
            @Override
            public String getClassName(String prefix, String source, Object key, Predicate names) {
                return className;
            }
        });

        BeanGenerator.addProperties(beanGenerator, properties);
        return (Class<?>) beanGenerator.createClass();
    }





Populate Java Object using Map

I have a Map<String, Object> . Using this, I have to populate one java object. For example,

public void setBaseAttributes(BaseObject baseObj) {
  Map<String, Object> map = // some method call;
  org.apache.commons.beanutils.BeanUtils.populate(baseObj, map);
 }

I was using BeanUtils but got stuck since BeanUtils does not handle BigDecimal. My baseObj has BigDecimal and i can not get rid of it.

Question to experts are:

  • Is there a better alternative i can use here?
  • Using BeanUtils, can we do something to handle BigDecimal also?




Create weak delegate of Dynamic Method(ref object,object[] arr)

Source code:https://www.pastefile.com/4mzhyg

I'm trying to create delegate of format:

    public delegate TReturn MethodCallerR<TTarget, TReturn>(ref TTarget target, object[] args);

 /// <summary>
    /// Generates a strongly-typed open-instance delegate to invoke the specified method
    /// </summary>
    public static MethodCallerR<TTarget, TReturn> DelegateForCallR<TTarget, TReturn>(this MethodInfo method) {

        int key = GetKey<TTarget, TReturn>(method, kMethodCallerName);
        Delegate result;
        if (cache.TryGetValue(key, out result))
            return (MethodCallerR<TTarget, TReturn>)result;

        return GenDelegateForMember<MethodCallerR<TTarget, TReturn>, MethodInfo>(
                method, key, kMethodCallerName, GenMethodInvocationR<TTarget>,
                typeof(TReturn), typeof(TTarget).MakeByRefType(), typeof(object[]));
    }

weak type function:

    public static MethodCallerR<object, object> DelegateForCallR(this MethodInfo method) {
        return DelegateForCallR<object, object>(method);
    }

delegate creator:

   static TDelegate GenDelegateForMember<TDelegate, TMember>(TMember member, int key, string dynMethodName,
            Action<TMember> generator, Type returnType, params Type[] paramTypes)
    where TMember : MemberInfo
    where TDelegate : class {
        var dynMethod = new DynamicMethod(dynMethodName, returnType, paramTypes, true);

        emit.il = dynMethod.GetILGenerator();
        generator(member);

        var result = dynMethod.CreateDelegate(typeof(TDelegate));
        cache[key] = result;
        return (TDelegate)(object)result;
    }

and IL code generator:

 static void GenMethodInvocationR<TTarget>(MethodInfo method) {



        var weaklyTyped = typeof(TTarget) == typeof(object);



        // push arguments in order to call method
        var prams = method.GetParameters();
        var imax = prams.Length;
        for (int i = 0; i < imax; i++) {

            emit.ldarg1()        // stack<= paramsValuesArray[] //push array
            .ldc_i4(i)        // stack<= index push(index)
            .ldelem_ref();    // stack[top]<=paramsValuesArray[i]

            var param = prams[i];
            var dataType = param.ParameterType;

            if (dataType.IsByRef)
                dataType = dataType.GetElementType();

            emit.unbox_any(dataType);

            emit.declocal(dataType);

            emit.stloc(i);

        }



        if (!method.IsStatic)
        {
            var targetType = weaklyTyped ? method.DeclaringType : typeof(TTarget);
            emit.ldarg0();  //stack[top]=target;
            emit.ldind_ref();//stack[top]=ref target;
            if (weaklyTyped)
                emit.unbox_any(targetType); //stack[top]=(TargetType)target;
        }


        //load parms from local 'list' to evaluation 'steak'
        for (int i = 0; i < imax; i++) {
            var param = prams[i];

            emit.ifbyref_ldloca_else_ldloc(i, param.ParameterType);
        }

        // perform the correct call (pushes the result)
        emit.callorvirt(method);


        //check of ref and out params and
        for (int i = 0; i < prams.Length; i++) {

            var paramType = prams[i].ParameterType;
            if (paramType.IsByRef)
            {
                var byRefType = paramType.GetElementType();
                emit.ldarg1() // stack<= paramsValuesArray[]
                .ldc_i4(i) // stack<= i //push(index)
                .ldloc(i); // stack<= list[i] //push local list element at 'i' on steak
                if (byRefType.IsValueType)
                    emit.box(byRefType);   // if ex. stack[top] =(object)stack[top]
                emit.stelem_ref(); //  // paramsValuesArray[i]= pop(stack[top]);
            }
        }

        if (method.ReturnType == typeof(void))
            emit.ldnull();
        else if (weaklyTyped)
            emit.ifvaluetype_box(method.ReturnType);

        emit.ret();


    }

Example for stuct I'm using is Vector3 with Set method:

  public struct Vector3{
    public float x;
    public float y;
    public float z;

    public Vector3(float x,float y,float z){
        this.x=x;
        this.y=y;
        this.z=z;
    }

    public void Set(float x,float y,float z){
        this.x=x;
        this.y=y;
        this.z=z;
    }
}

so I'm doing:

   Vector3 vector3=new Vector3(4,5,6);
    MethodInfo method=typeof(Vector3).GetMethod("Set");
      MethodCallerR<object,object> m = methodInfo.DelegateForCallR();
             m(ref vector3,new object[]{1f,2f,3f});
    Console.Write(vector3.x);

Never get to the executing delegate, but it blows when it calls Delegate.CreateDelegate:

see line: dynMethod.CreateDelegate(typeof(TDelegate));

with error: InvalidProgramException: Invalid IL code in (wrapper dynamic-method) object:MC<> (object&,object[]): IL_004f: call 0x00000009 refereeing that actual IL code has error at emit.call(method), but when I use helper function:

    FastReflection.GenDebugAssembly<object>("my.dll",null,null,methodInfo,this.__anyObject.GetType(),new Type[]{typeof(float),typeof(float),typeof(float)});

which will generate my.dll and open with ILSpy I can see that method from same IL code is generated just fine.

    public static object MethodCallerR(ref object ptr, object[] array)
{
    float num = (float)array[0];
    float num2 = (float)array[1];
    float num3 = (float)array[2];
    ((Vector3)ptr).Set(num, num2, num3);
    return null;
}





Invoking generic method having generic type parameter using reflection

I want to invoke a generic method having two different generic type parameters. Below is what my method looks like:

public class ABC<T> : IABC<T> where T: class,new()
{
    public T Merge<T1>(T child, T parent, T1 rule){

    }
}

I want to invoke the Merge method from another method. Below is what I have tried to invoke it.

Type mergerType = GetType().GetGenericTypeDefinition();

Type constructed = mergerType.MakeGenericType(new[]
{
    childValue.GetType()
});

object mergerInstance = Activator.CreateInstance(constructed);

MethodInfo methodInfo = GetType().GetMethod("Merge");

MethodInfo method = methodInfo.MakeGenericMethod(ruleValue.GetType());

mergedObject = method.Invoke(mergerInstance, new[]
                {
                    childValue,
                    parentValue,
                    ruleValue
                });

While doing this I am getting a exception "object does not match target type invoke" after method.invoke(). I cannot change the class or method definition of ABC class or Merge method because many other classes are implementing the IABC interface. So can someone answer how can I invoke the Merge method.





C# order List of Parent objects by Child's property via Reflection

I have a method that orders a queryable by a property via reflection, like so:

   public static IQueryable<TEntity> OrderBy<TEntity>(this IQueryable<TEntity> source, string orderByProperty, bool desc)
   {
       string command = desc ? "OrderByDescending" : "OrderBy";
       var parts = orderByProperty.Split('.');
       var parameter = Expression.Parameter(typeof(TEntity), "p");
       Expression body = parameter;
       if (parts.Length > 1)
       {
           for (var i = 0; i < parts.Length - 1; i++)
           {
               body = Expression.Property(body, parts[i]);
           }
       }

       body = Expression.Property(body, property.Name);
       var orderByExpression = Expression.Lambda(body, parameter);
       resultExpression = Expression.Call(typeof(Queryable), command, 
                                       new Type[] { typeof(TEntity), property.PropertyType },
                                       source.Expression, Expression.Quote(orderByExpression));
       return source.Provider.CreateQuery<TEntity>(resultExpression);
   }

And it works if I use it for the object's properties or its children's properties, but it doesn't work when a child property is a List.

    // Success
    db.Users.OrderBy("Name", true)
    db.Users.OrderBy("CurrentAddress.City.Name", false)

    // Fail
    db.Users.OrderBy("PhoneLines.RenewalDate", true)

My model is like so:

    public class User {
        public string Name { get; set; }
        public Address CurrentAddress{ get; set; }
        public List<Phone> PhoneLines { get; set; }
    }

And I am trying to do something like this work:

    db.Users.OrderByDescending(x => 
        x.PhoneLines
          .OrderByDescending(y => y.RenewalDate)
          .Select(y => y.RenewalDate).FirstOrDefault()
    );

Right now I am only interested in making this work for first level List children, that is, I am not concerned about a cascading list scenario, just one child in the chain is a list.

Is it possible to achieve this via reflection?





mardi 21 mai 2019

C# - See if MemberInfo matches BindingFlags

I need to see if a MemberInfo matches a particular BindingFlags. The closest method to this is Type#GetMember(string, BindingFlags)

I cannot find any method to do this.

I want to do something like this

private List<MemberInfo> _members;

public IEnumerable<MemberInfo> GetMembers(BindingFlags flags)
{
    foreach(var member in _members)
    {
        if(member.MatchesFlags(flags))
        {
             yield return member;
        }
    }
}





How to invoke a method in a C# generics class

I am new to C# generics. I have several classes with identical methods. I want to create a generic class which will be of type belonging to any of those classes and invoke the methods from them. I am not sure whether this is possible, or there is a different way of doing it. I have given my code sample below. I have included two representative classes named, EastCoastStores and WestCoastStores. When I try to invoke the method using reflection, I am getting null reference exception for GetMethod("GetZipCode") in the GetZipCode() method of the MyGenerics class. I have searched the internet, but could not an appropriate solution.

//Two classes with identical methods
public class EastCoastStores
{
    private string zip;

    public void SetZipCode(string zip)
    { this.zip = zip; }

    public string GetZipCode()
    { return zip; }
 }

public class WestCoastStores
{
    private string zip;

    public void SetZipCode(string zip)
    { this.zip = zip; }

    public string GetZipCode()
    { return zip; }
}

//Generic class which can accept either of the above classes
public class MyGenerics<T>
{
    private T selectedValues;
    public MyGenerics(T selectedValues)
    {
        this.selectedValues = selectedValues;
    }
    public String GetZipCode()
    {
        Type typeParameterType = typeof(T);
        var getZipCode = typeParameterType.GetMethod("GetZipCode");
        var val = 

typeParameterType.GetType().GetMethod("GetZipCode").Invoke(typeParameterType, 
 null);
        return val.ToString();
    }
}

//Accessing the class method
public static void Main(string[] args)
    {
        EastCoastStores eastCoastStores = new EastCoastStores();
        eastCoastStores.SetZipCode("12345");
        MyGenerics<EastCoastStores> orderAction = new 
  MyGenerics<EastCoastStores>(eastCoastStores);
        var val = orderAction.GetZipCode();

    }





Convert Class name to generic type [duplicate]

This question already has an answer here:

Instead of having the type, I have the className, and what I need is to use this class name in a generic class.

As maybe this could be confusing I will put a simple example.

To create a List of Integer we put:

List<Integer>

Now imagine that, instead of Integer we have an string with the following value: "java.lang.Integer".

How I could convert this string intro the Integer type.

I have tried lots of thinks but thew one that makes more sense and that doesn't work is the following:

List<Class.forName("java.lang.Integer")>

Maybe this question is repeated but i didn't find it in anywhere.





Where will TypeBuilder.CreateType() stored, memory or filesystem?

Will TypeBuilder.CreateType() generate a local file or just keep it in memory? If it creates a local file, where will it be stored? I have seen files that sugests that it saves them to C:\Users[My Account]\AppData\Local\Temp but if I remove them they are not created again when running the code? I also read that the generated types are saved in the some folder as current executing assembly? But there is no generated files?

So where is it stored? If its even stored on disc?

Here is the code I use to create the type in runtime :

        private static Type CreateRaportType(List<PropertieInformation> propertieList, string className)
    {
        AssemblyName assemblyName;
        AssemblyBuilder assemblyBuilder;
        ModuleBuilder module;
        TypeBuilder typeBuilder;
        FieldBuilder field;
        PropertyBuilder property;
        MethodAttributes GetSetAttr;
        MethodBuilder currGetPropMthdBldr;
        MethodBuilder currSetPropMthdBldr;
        ILGenerator currGetIL;
        ILGenerator currSetIL;

        Type caType;
        CustomAttributeBuilder caBuilder;

        List<Object> objList = new List<object>();

        assemblyName = new AssemblyName();
        assemblyName.Name = "ReportAssembly";

        assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
        module = assemblyBuilder.DefineDynamicModule("ReportModule");

        typeBuilder = module.DefineType(className, TypeAttributes.Public | TypeAttributes.Class, typeof(GeneratedClassBase));

        foreach (PropertieInformation propertieInfo in propertieList)
        {
            field = typeBuilder.DefineField("_" + propertieInfo.PropertieName, propertieInfo.PropertieType, FieldAttributes.Private);

            property = typeBuilder.DefineProperty(propertieInfo.PropertieName, PropertyAttributes.None, propertieInfo.PropertieType, new Type[] { propertieInfo.PropertieType });
            GetSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig;

            currGetPropMthdBldr = typeBuilder.DefineMethod("get_value", GetSetAttr, propertieInfo.PropertieType, Type.EmptyTypes);

            currGetIL = currGetPropMthdBldr.GetILGenerator();
            currGetIL.Emit(OpCodes.Ldarg_0);
            currGetIL.Emit(OpCodes.Ldfld, field);
            currGetIL.Emit(OpCodes.Ret);

            currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, null, new Type[] { propertieInfo.PropertieType });

            currSetIL = currSetPropMthdBldr.GetILGenerator();
            currSetIL.Emit(OpCodes.Ldarg_0);
            currSetIL.Emit(OpCodes.Ldarg_1);
            currSetIL.Emit(OpCodes.Stfld, field);
            currSetIL.Emit(OpCodes.Ret);

            // Last, we must map the two methods created above to our PropertyBuilder to
            // their corresponding behaviors, "get" and "set" respectively. 
            property.SetGetMethod(currGetPropMthdBldr);
            property.SetSetMethod(currSetPropMthdBldr);

            caType = typeof(Reportable);
            objList.Clear();
            objList.Add(propertieInfo.MemberToDataBind);
            objList.Add(propertieInfo.ControlToUse);
            objList.Add(propertieInfo.PropertieName);

            objList.Add(propertieInfo.PropertieInnerCollectionType);
            objList.Add(propertieInfo.PropertieInnerCollectionName);
            objList.Add(propertieInfo.DisplayName);
            objList.Add(-1);
            objList.Add(FieldListIcon.UnUsedItem);
            objList.Add(propertieInfo.SystemItemKey);
            objList.Add(null);

            var conInfo = caType.GetConstructor(Type.EmptyTypes);
            var conArgs = new object[] { };
            var caTypeFields = caType.GetFields();

            caBuilder = new CustomAttributeBuilder(conInfo, conArgs, caTypeFields, objList.ToArray());

            property.SetCustomAttribute(caBuilder);

            caType = typeof(DisplayNameAttribute);

            if (propertieInfo.IsList)
                caBuilder = new CustomAttributeBuilder(caType.GetConstructor(new Type[] { typeof(string) }), new string[] { propertieInfo.DisplayName });
            else
                caBuilder = new CustomAttributeBuilder(caType.GetConstructor(new Type[] { typeof(string) }), new string[] { propertieInfo.DisplayName });

            property.SetCustomAttribute(caBuilder);
        }
        return typeBuilder.CreateType();
    }





Writing a wrapper for different dependency injection containers in .net core

I wanted to write a wrapper around dependency injection containers in my .net core project, so that whenever I need to inject something in my application, I can use my own injector which is actually using third-party containers like Autofac and SimpleInjection for injection. This way I can change my injector without ever changing my code.

I've written an interface for this purpose which has some needed methods:

  interface IDependencyBuilder
    {
        void CreateContainer();

        IContainer Build();

        void RegisterModule<T>() where T : Module, new();

    }

And I've implemented it for the Autofac like this:

public class AutofacContainerBuilder : IDependencyBuilder
    {
        private readonly ContainerBuilder _containerBuilder;

        public AutofacContainerBuilder()
        {
            _containerBuilder = new ContainerBuilder();
        }
        public void CreateContainer()
        {
            throw new NotImplementedException();
        }
        public IContainer Build()
        {
            return _containerBuilder.Build();
        }

        public void RegisterModule<T>() where T : Autofac.Module,new()
        {
            _containerBuilder.RegisterModule<T>();
        }
    }

I think something is wrong with this kind of implementation and writing wrapper.

1.Signatures and Input/Output models: I don't exactly know what functions with what signatures should be written in the wrapper.

2. Implementations for Different Third Parties: For creating a container I've to have it in the constructor and the create container method cannot be implemented.

I expect to handle the dependency injection in my modular application with my wrapper.

What is the correct way of doing this for a modular web application?





Set location of TypeBuilder.CreateType()?

Im creating c# class during runtime in .NET 4.7.2 by using the TypeBuilder. The problem is that the DLL for the type is stored in the root folder of current application. The problem is that often the user have no write access to the local root folder.

So how do I set the location where the assemblies should be saved and loaded? And what user folder would be fitting for this?

//Jimmy





How to override property CanWrite = false using reflection [duplicate]

This question already has an answer here:

I have a class with two properties and I want to override the read-only property (Name) using reflection.

This is the class

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

This is how I attempt to override the property

var inst = new Test() { Id = 1 };
var prop = typeof(LogoutRequest).GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
prop.SetValue(inst, "a name");