vendredi 31 juillet 2020

Field returning 0 while IDE debug shows it at the proper initialised value

I'm using reflection to create instances of all classes derived from ItemPart as follows:

        //Create UI from reflection
    private void DisplayParts(string partGroup)
    {
        List<ItemPart> validParts = GetPartsList(partGroup);
        foreach(ItemPart part in validParts)
        {
            GameObject obj = Instantiate(UIController.ObjectPrefabs[UIController.ObjectPrefabsEnum.ButtonDescription], UI_PartsList.transform);
            DescriptionButton button = obj.GetComponent<DescriptionButton>();
            button.Title.text = part.PartName;
            button.Description.text = part.Description;
            button.ActivateAction = delegate { DesignBench.CreatePart(part); };
        }
    }
    
    //Get classes derived from ItemPart and return a list of instances
    private List<ItemPart> GetPartsList(string partGroup)
    {
        List<Type> types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes()).Where(p => typeof(ItemPart).IsAssignableFrom(p) && p != typeof(ItemPart) ).ToList();

        List<ItemPart> validParts = new List<ItemPart>();

        foreach(Type type in types)
        {
            ItemPart part = (ItemPart)Activator.CreateInstance(type);
            if (part.PartGroup == partGroup)
            {
                validParts.Add(part);
            }
        }
        return validParts;
    }

After accessing variables in this class, I've found while the IDE is claiming they are correctly at their initialised values, they are reading by the program as being 0:

public class Handle : ItemPart 
{
//...
        public new PartModifiableStats ModifiableStats = new PartModifiableStats()
        {
            SizeX = new ModifiableStat<float>() { IsEnabled = false, Value = 5 },
            SizeY = new ModifiableStat<float>() { IsEnabled = true, Value = 20, Bounds = new Vector2(10, 150) },
            Material = new ModifiableStat<Materials.Material>() { IsEnabled = true, Value = Materials.MaterialDict[Materials.MaterialTypes.Iron] }
        };
//...
}

https://puu.sh/GcS8h/9a3c26de2b.png https://puu.sh/GcS8L/4911fbd3d8.png

Supposedly, Activator.CreateInstance(type) uses the type's empty constructor, which if I'm not mistaken, should also properly initialise all the variables in the type it is creating. Why is this value still reading as zero, and why is there a discrepency between what the program is reading and what the IDE believes the value to be?

        public struct ModifiableStat<T>
        {
            public bool IsEnabled;
            public T Value;
            public Vector2 Bounds;
        }
        public struct PartModifiableStats
        {
            public ModifiableStat<float> SizeX;
            public ModifiableStat<float> SizeY;
            public ModifiableStat<Materials.Material> Material;
        }




Get the list of invoking method name's from Hashmap put()

Can you help me to get the list method name's from the HashMap put method.

 Book book= new Book();
        book.setTitle("The Little Prince");
        book.setAuthor("Antoine de Saint-Exupery");
        book.setPrize(9.99);
        book.setPublisher("Delux Pop-up book");
        
        
        HashMap<String,String> map= new HashMap<String,String>();
        map.put("title",book.getTitle());
        map.put("author",book.getAuthor());
        map.put("prize",String.valueOf(book.getPrize()));
        map.put("publisher",validatePuplisher(book.getPublisher()));
        

Excepted result is : book.getTitle(),book.getAuthor(),String.valueOf(book.getPrize()),validatePuplisher(book.getPublisher()) ie just method name's not value from the method.





How to convert protobuf wireformat to JSON with just a message descriptor?

Normally, to convert a protobuf message from wire format to JSON, you simply unmarshal the wire format into a proto.Message whose dynamic type is a concrete Go type (generated by protoc-gen-go), and then unmarshal that to JSON with the protojson package.

I would like to know how to do the same if you don't have a concrete Go type, but a protoreflect.MessageDescriptor instead. The descriptor should have all the information necessary to parse the wire format and construct a JSON (or other formats) from it, but I can't seem to find an API for that. It seems like I need something like the following:

func UnmarshalFromWire(b []byte, desc protoreflect.MessageDescriptor) (protoreflect.Message, error)

func MarshalToJSON(m protoreflect.Message) ([]byte, error)

Is there an API like that or similar?





Does anyone has a nice built in PropertyAccessor object that could easily be used?

I have something similar to his:

public class ClassA
{
  public ClassB PropAnyStart {get;set;}
  public ClassB PropAnyEnd {get;set;}
}

public class ClassB
{
  public string Name {get;set;}
}


public void ProcessSomething(Accessor<ClassB> accessor) 
{
  ...
  if (accessor.Name = "Eric")
  {
       accessor = new ClassB(){Name = "SomeoneElse"};
  }
  ...
}

Accessor class does not exists, that's what I'm looking for. I want to call twice ProcessSomething like this:

{
  ClassA a = new ClassA();
  ...
  ProcessSomething(a.PropAnyStart.Accessor());
  ProcessSomething(a.PropAnyEnd.Accessor());
}

What is the closest way to do that in C# in 2020?

Update

I'm actually using this class:

public class PropertyAccessor<T>
    {
        Func<T> _getter;
        Action<T> _setter;

        public PropertyAccessor(Func<T> getter, Action<T> setter)
        {
            _getter = getter;
            _setter = setter;
        }

        public T Get()
        {
            return _getter();
        }

        public void Set(T val)
        {
            _setter(val);
        }
    }

But I have to pass arguments like that and its very tedious and take a long time:

ProcessSomething(new PropertyAccessor<ClassB>(() => a.PropAnyStart, (bArg) => a.PropAnyStart = bArg));

It should exists a better way to achieve my goal?





Getting UnsupportedClassVersionError: JVMCFRE003 error when using reflection Library

I use the org.reflection library in my code, and i have this error when i run it.

Error 500: javax.servlet.ServletException: java.lang.UnsupportedClassVersionError: JVMCFRE003 version majeure incorrecte; classe=org/reflections/Reflections, décalage=6

My java compiler is 1.6, it is running on a v8.5 web sphere server. And here's my dependency in my pom.xml :

<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.12</version>
</dependency>

Any idea?





Is dynamic method invocation using LambdaMetafactory thread safe?

I'm using Java reflection to invoke method dynamically in runtime. But i'm advised not to use it since its not thread safe. So i searched for alternatives for reflection and found this LambdaMetaFactory Implementation. I want to know if it's thread safe or not to proceed further.





Using Reflection with Classes and JavaScript Modules

I'm at the point where I've spent over 8 hours tinkering with this and would love some advice. My objective is to implement the approach which is most likely to be native to JavaScript at some point in the future. I want the solution to work both in web browsers and on a Node server. That being the case, I want to avoid anything besides vanilla JavaScript as much as possible.

Here is my dilemma. I have two classes, each in their own file. My problem is shown in the get() method of the Model class.

ChildModel.js

import Model from './Model.js';

class ChildModel extends Model {

    // Data which describes where data is stored on the server
    static meta = {
        url: 'api/child-model/';
    }

}

export default = ChildModel;

Model.js

class Model {

    // A convenient method which all models use to get their data from the server
    async get() {
        // Use reflection to get the name of the extended child class
        var modelClassName = this.name; // "ChildModel"

        // Nice, now I know the name of my class
        // Now, I just need to get to the actual class definition so I can access the static .meta property
        // I have three options that I can think of to do this:

        // Option 1 - Use a global
        var ModelClass = window[modelClassName]; // or global[modelClassName]
        // Pros: looks straightforward
        // Cons: pollutes the global namespace and requires me to write 
        // nasty code to put all of my models onto window or global.
        // Does not work because inside module there is no access to window or global

        // Option 2 - Use require()
        var ModelClass = require('./models/'+modelClassName+'.js');
        // Pros: works perfectly on server side in Node
        // Cons: does not work at all in the browser without third party software

        // Option 3 - Use import()
        var importedModelClass = await import('./models/'+modelClassName+'.js');
        var ModelClass = importedModelClass.default;
        // This is basically the same as Option 2

        // Option 4 - ???
    }

}

export default = Model;

To solve the issue for now, I'm currently using Rollup to put all of my files into a single index.js file. I am then using a dynamic import plugin to implement option #3. It works, but I am sitting here at the end of coding all day and thinking this can't be the best way to do things in 2020. Did I miss something obvious or is this how it's done?





jeudi 30 juillet 2020

C# System.Reflection.Emit: How can I generate a type with a property of the same type that is being defined (like a TreeNode class)

I need to create a new type in a dynamic assembly using the c# System.Reflection.Emit namespace. This type contains a property of the same type as the one I need to define. Think about a parent / child kind of type:

public class Node 
{
   public Node ChildNode {get; set;}
}

How can I do this?

Regards, H





How to get original function parameter names in production webpack build

I'm trying to implement something similar to dependency injection, By getting parameter names from a function exposed by a javascript module, something like this:

module.exports = (router,form,query,url) => {

    // Do something with these parameters ...

    return response;
};

I can solve this problem by parsing the string representation of the function. There's already a SO thread for that.

My problem becomes apparent when the code is bundled for production with webpack, all the parameter names get mangled, and the original names are lost.

I couldn't find any option in the webpack config that can help me with that.

Is there a way to do what I want without making the module that exports the function worry about anything related to this problem?





How to find the function call chain

I want to find the call chain of each method in the given project cs files. I made a parser to do that. But it is taking so much of time. I think that by adding a class in the project, and using reflection I may get the call chain. There are functions to extract methods for a class. But how can I get the calls inside the method. How to use reflection for it. Or is it not possible using reflection? Than how to find the calling methods inside the function apart from parsing?





Bind class properties from string in c#

I have a string like "dataSource=ReportDataSource;storedProcedure=GetUserEmails;tableName=Users". Is there a way to bind the class properties from this type of string. I have a class with all 3 properties dataSource,storedProcedure and tableName.





Java how to get Class reference for a fuly parameterized GenericType

I'm trying to get a Class reference to a GenericType. Note that OtherType isn't just a place-holder - this is a fully parameterized type. And an example we could use List.

For a non-generic type I could do something like Class c = String.class

However if I try to do Class c = List<String>.class it doesn't compile....

How do I get a fully parameterized generic type Class reference?

EDIT: My goal is to use mokito to mock a TypedQuery for a unit test

Thank you





mercredi 29 juillet 2020

Java reflection : what modifying at runtime means?

I'm learining Java reflection API. I have read a lot, use java.lang.reflect package. But there is still something I don't understand : the idea that with introspection, you can modify objects at runtime.

Basically you do not need introspection/reflection to do that. With a simple setter() method, you can also modify your object at runtime. What's the difference between using simple setters or using reflection ? In both cases you can achieve the same result.





Setting a final field for an ENUM variable

I want to change the final value of an attribute "name" declared in my enum class using reflection with the name of the enum itself to use it in custom annotations. But I am facing a strange behaviour which I am not able to debug.

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;


@Service
@Slf4j
public class EnumNameEditor {

    public static void throwErrorForNotDefinedErrorCodes() throws Exception {
        Reflections reflections = new Reflections("com.");
        Set<Class<? extends CustomClass>> classes = reflections.getSubTypesOf(CustomClass.class);
        log.info("classes: {}",classes);
        for (Class c : classes) {
            if(c.isEnum()) {
                changeNameInEnum(c);
            }
        }
    }

    private static<C extends Enum<C>> void changeNameInEnum(Class<C> c) throws Exception {
        C[] codes = c.getEnumConstants();
        String uniqueIdentifier = "uniqueIdentifier";
        String name = "name";
        log.info("c: {}",Arrays.asList(codes));
        for (C e : codes) {
            System.out.println("\n\n=============== changing: " + e.ordinal());
            getValue(c,name,e);
            setValue(c,e);
            System.out.println("Ee : " + e);
            getValue(c,name,e);
            setFieldValue(c,e);
        }

        codes = c.getEnumConstants();
        log.info("after c: {}",Arrays.asList(codes));
    }

    private static <C extends Enum<C>> void setFieldValue(Class<C> c, C e) throws Exception {
        System.out.println("e: "+ e);
        Field $VALUESField = c.getDeclaredField("$VALUES");
        makeAccessible($VALUESField);
        C[] oldValues = (C[]) $VALUESField.get(null);
        oldValues[e.ordinal()] = e;
        $VALUESField.set(null, oldValues);

        $VALUESField = Class.class.getDeclaredField("enumConstants");
        makeAccessible($VALUESField);
        $VALUESField.set(c, oldValues);

        try {
            $VALUESField = Class.class.getDeclaredField("enumConstantDirectory");
            makeAccessible($VALUESField);
            Map<String,C> map = (Map<String, C>) $VALUESField.get(c);
            System.out.println("map: " + map);
            if(map != null) {
                map.put(e.name(),e);
                $VALUESField.set(c, map);
            }

        } catch (Exception exc) {
            exc.printStackTrace();
            log.debug("exception while setting new enum values in enumConstantDirectory for class: {}",c);
        }


    }

    static<C extends Enum<C>> Object getValue(Class<C> c, String fname, C e) throws Exception {
        Field field = c.getDeclaredField(fname);
        makeAccessible(field);
        Object value = field.get(e);
        System.out.println("value defined: " + value + " for: " + fname);
        return value;
    }

    static<C extends Enum<C>> C setValue(Class<C> c, C e) throws Exception {
        Field field = c.getDeclaredField("name");
        makeAccessible(field);
        field.set(e,e.name());
        return e;
    }

    static void makeAccessible(Field field) throws Exception {
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~ Modifier.FINAL);
    }

    public static void main(String[] args) {
        try {
            System.out.println("name: " + GenericResponseErrorCodes.UNEXPECTED_ERROR.name);
            throwErrorForNotDefinedErrorCodes();
            System.out.println("name: " + GenericResponseErrorCodes.UNEXPECTED_ERROR.name);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

My Enum class is as below.

public enum  GenericResponseErrorCodes implements CustomClass {

    UNEXPECTED_ERROR(1,"Unexpected error has occurred. Please try again later."),
    UNEXPECTED_ERROR2(2,"Unexpected error2 has occurred. Please try again later."),
    UNEXPECTED_ERROR3(3,"Unexpected error3 has occurred. Please try again later.","def.prop"),
    UNEXPECTED_ERROR4(4,"Unexpected error4 has occurred. Please try again later."),
    UNEXPECTED_ERROR5(5,"Unexpected error5 has occurred. Please try again later.");



    final String uniqueIdentifier = "G";
    String key;
    String message;
    Integer code;
    public final String name = "name";

    GenericResponseErrorCodes( Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    GenericResponseErrorCodes(Integer code, String message, String key) {
        this.code = code;
        this.key = key;
        this.message = message;
    }

}

I am getting the below logs when I execute the main function.

name: test_name

c: [GenericResponseErrorCodes(uniqueIdentifier=G, key=null, message=Unexpected error has occurred. Please try again later., code=1, name=test_name), GenericResponseErrorCodes(uniqueIdentifier=G, key=null, message=Unexpected error2 has occurred. Please try again later., code=2, name=test_name), GenericResponseErrorCodes(uniqueIdentifier=G, key=def.prop, message=Unexpected error3 has occurred. Please try again later., code=3, name=test_name), GenericResponseErrorCodes(uniqueIdentifier=G, key=null, message=Unexpected error4 has occurred. Please try again later., code=4, name=test_name), GenericResponseErrorCodes(uniqueIdentifier=G, key=null, message=Unexpected error5 has occurred. Please try again later., code=5, name=test_name)]


=============== changing: 0
value defined: test_name for: name
Ee : GenericResponseErrorCodes(uniqueIdentifier=G, key=null, message=Unexpected error has occurred. Please try again later., code=1, name=test_name)
value defined: UNEXPECTED_ERROR for: name


=============== changing: 1
value defined: test_name for: name
Ee : GenericResponseErrorCodes(uniqueIdentifier=G, key=null, message=Unexpected error2 has occurred. Please try again later., code=2, name=test_name)
value defined: UNEXPECTED_ERROR2 for: name


=============== changing: 2
value defined: test_name for: name
Ee : GenericResponseErrorCodes(uniqueIdentifier=G, key=def.prop, message=Unexpected error3 has occurred. Please try again later., code=3, name=test_name)
value defined: UNEXPECTED_ERROR3 for: name


=============== changing: 3
value defined: test_name for: name
Ee : GenericResponseErrorCodes(uniqueIdentifier=G, key=null, message=Unexpected error4 has occurred. Please try again later., code=4, name=test_name)
value defined: UNEXPECTED_ERROR4 for: name


=============== changing: 4
value defined: test_name for: name
Ee : GenericResponseErrorCodes(uniqueIdentifier=G, key=null, message=Unexpected error5 has occurred. Please try again later., code=5, name=test_name)
value defined: UNEXPECTED_ERROR5 for: name

after c: [GenericResponseErrorCodes(uniqueIdentifier=G, key=null, message=Unexpected error has occurred. Please try again later., code=1, name=test_name), GenericResponseErrorCodes(uniqueIdentifier=G, key=null, message=Unexpected error2 has occurred. Please try again later., code=2, name=test_name), GenericResponseErrorCodes(uniqueIdentifier=G, key=def.prop, message=Unexpected error3 has occurred. Please try again later., code=3, name=test_name), GenericResponseErrorCodes(uniqueIdentifier=G, key=null, message=Unexpected error4 has occurred. Please try again later., code=4, name=test_name), GenericResponseErrorCodes(uniqueIdentifier=G, key=null, message=Unexpected error5 has occurred. Please try again later., code=5, name=test_name)]
name: test_name

Process finished with exit code 0

I am not able to identify why the name accessed using reflection is different from the one present in the enum object? Also how should I change the name field permanently? Thanks in advance.

PS: I have taken reference from this blog.





Looking for a more concise way to put a C# setter into a Dictionary<> for mapping

This is a representation of a larger bit of code I’m working on that’s a mapper. Originally it was written as a large switch statement, but I prefer to make the mapping stand out as a table rather than a long, long switch.

My first pass looks something like this (from LINQPad):

    Dictionary<string, Action<Foobar, decimal>> map
        = new Dictionary<string, Action<Foobar, decimal>> {
                { "one", (f,d) => f.One = d },
                { "double", (f,d) => f.Two = d },
                { "tricycle", (f,d) => f.Three = d },
        };
    
    void Main()
    {
        Foobar obj = new Foobar();
        decimal amount = 100M;
        var x = map["one"];
        x(obj, amount);
    
        Console.WriteLine(obj.One);   // Prints 100 as expected
    }
    public class Foobar
    {
        public decimal One { get; set; }
        public decimal Two { get; set; }
        public decimal Three { get; set; }
    }

The real Foobar class is large, has many properties, but they’re all the same type: decimal.

What I’m looking for is a more concise way of expressing the table above. This is fine:

{ "one", (f,d) => f.One = d },          // It works, but … can it be better?

I really don’t want to do it as strings with full-on reflection in the invocation:

{ "one", "One" },                       // No
{ "one", nameof(Foobar.One) },          // Really, just no.

I seem to remember there’s a more concise way to do it, but my Google-fu fails me. I can get to the getter more concisely by changing the signature to Dictionary<string, Func<Foobar, decimal>> and then doing this:

   { "one", f.One }                        // The getter, not the setter.

but that doesn’t get me to the setter. Ideas?





scala how to use pattern matching with inheriance and templated class

We use at our company a data structure that looks like that:

trait Resource

case class templatedResource[T](t: T) extends Resource

case class BParameter()
case class CParameter()

object B {
  type Resource = templatedResource[BParameter]
}

object C {
  type Resource = templatedResource[CParameter]
}

At some point, given some unknown Resources we want to use pattern matching to determine their inner types and launch some different processings.

But due to Type Erasure, simple pattern matching doesn't work. So we have tried to use TypeTags, but without success :

import scala.reflect.runtime.universe._

object Service {

  def process(resource: Resource)(implicit tag: WeakTypeTag[Resource]) = {
    (tag.tpe, resource) match {
      case (t, b: B.Resource) if t =:= typeOf[B.Resource] =>
        println("b !!")
      case (t, c: C.Resource) if t =:= typeOf[C.Resource] => 
        println("c !!")
      case _ => 
          throw new IllegalStateException(s"Unexpected resource type")
    }
  }
}

val bParam = BParameter()
val bResource: B.Resource = templatedResource(bParam)

Service.process(bResource)
//  throws java.lang.IllegalStateException: Unexpected resource type
//         at Service$.process(<console>:26)

It seems that the t =:= typeOf[B.Resource] are always false because t only knows the Resource trait ( t =:= typeOf[Resource] ) and not the concrete implementation.

How can I get this pattern matching to work ?





How to mock inject a config value in test class

I have an injection like

@Inject
    @ConfigProperty("BEHOLD_UDSLUS_BEREGNING_MND")
    private String maxMonths;

Now i want to mock this in my test class so that the value of "60" can be passed onto the main method. I tried using ReflectionTestUtils.setfield() but somehow its not getting mocked.

List<UdbKonfiguration> udbKonfigList = new ArrayList<UdbKonfiguration>();
        UdbKonfiguration udbKonfig = new UdbKonfiguration();
        udbKonfig.setKode("BEHOLD_UDSLUS_BEREGNING_MND");
        udbKonfig.setValue("60");
        udbKonfigList.add(udbKonfig);
        try {
            ReflectionTestUtils.setField(udbKonfig, "BEHOLD_UDSLUS_BEREGNING_MND", "60", null);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }




Getting NoClassDefFoundError using reflection library

I'm getting this error when i try to run code using reflection library.

Here's the error :

[29/07/20 09:56:37:154 CEST] 00000086 ContainerResp E   The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
                                 java.lang.NoClassDefFoundError: org/reflections/Reflections
    at cnaf.oma.checkenv.rest.checks.Checks.doGetListe(Checks.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:611)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1232)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:781)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:480)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1114)
    at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:87)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:940)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:287)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1881)

[29/07/20 09:56:37:159 CEST] 00000086 ServletWrappe E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0014E: Cause root de l'exception non interceptée générée par la méthode service() OmegaEnvCheckAPI : javax.servlet.ServletException: java.lang.NoClassDefFoundError: org/reflections/Reflections
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:420)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1232)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:781)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:480)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1114)
    at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:87)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:940)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:287)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1881)
Caused by: java.lang.NoClassDefFoundError: org/reflections/Reflections
    at cnaf.oma.checkenv.rest.checks.Checks.doGetListe(Checks.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:611)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    ... 26 more

[29/07/20 09:56:37:160 CEST] 00000086 webapp        E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Erreur de servlet]-[OmegaEnvCheckAPI]: java.lang.NoClassDefFoundError: org/reflections/Reflections
    at cnaf.oma.checkenv.rest.checks.Checks.doGetListe(Checks.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
    at java.lang.reflect.Method.invoke(Method.java:611)
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$ResponseOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:205)
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
    at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
    at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
    at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
    at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1232)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:781)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:480)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1114)
    at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:87)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:940)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:287)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
    at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1881)

Here's the code where there is the bug :

public Response doGetListe()
        throws ServletException, IOException {
    Response.ResponseBuilder rb = Response.status(Response.Status.OK);
    Reflections reflections = new Reflections("testclass", new SubTypesScanner());
    try{
        Set<Class<? extends ICheckingClass>> checkingClasses = reflections.getSubTypesOf(ICheckingClass.class);
        String json = "[";
        for(Class checkingClass : checkingClasses){
            Object status;
            Object checkingClassInstance = checkingClass.getConstructor().newInstance();
            status = checkingClass.getMethod("check").invoke(checkingClassInstance);
            json += ((Status)status).getJSON();
            json += ",";
        }

        json = json.substring(0,json.length() - 1);
        json += "]";
        System.out.println(json);
    }catch(Exception e){
        System.out.println(e.toString());
    }
    rb.entity("[{ 'test' : ' test ' }]");
    return rb.build();
}

And here's the depedencies of my pom.xml if it can help :

<dependencies>
        <!--  jersey rest -->
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-servlet</artifactId>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-json</artifactId>
    </dependency>

    <!--  LOG4J -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <scope>compile</scope>
    </dependency>
    <!-- JAVASSIST -->
    <dependency>
        <groupId>javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.12.1.GA</version>
    </dependency>
    <!-- REFLECTIONS -->
    <dependency>
        <groupId>org.reflections</groupId>
        <artifactId>reflections</artifactId>
        <version>0.9.12</version>
    </dependency>
    <dependency>
        <groupId>cnaf.ddd.omega.ome</groupId>
        <artifactId>ome-service</artifactId>
        <version>${project.version}</version>
    </dependency>

</dependencies>

I suppose the problem is with how i import the library but i can't find what i've done wrong since i imported the library in the java file and in my pom.xml. Any idea? If you need any informations just ask me, thanks





mardi 28 juillet 2020

Obtaining type class from java class using reflections

I currently have a setup like this:

public abstract class Configurable<T> {
    //...
}
public class ConfigurableBoolean extends Configurable<Boolean> {
    //...
}

I'm looking to obtain a Boolean class from ConfigurableBoolean but Integer on a ConfigurableInt (similar setup)





Cast object of anyonymous type to a concrete object in VB.NET with Strict On

we have a product where we can run VB.NET functions within a C# API. We can pass arguments to these VB.NET functions with an Object[]. Lets say we have the following invocation within the C# API where we pass 3 Parameters to a VBFunction:

var scriptParameters = new object[]
{
    new List<Object>() 
    {
        new { FirstName = "Dave", LastName = "King" },
        new { FirstName = "Aron", LastName = "Lee" },
        new { FirstName = "Gabbi", LastName = "Cole" },
    },
    "Managers",
    "de-DE"
};

var scriptResult = scriptRunner.Invoke("VBFunction", scriptParameters);

Now the first argument -- a List of Objects with Property FirstName, LastName -- is received by the VBFunction as a List of anonymous objects. These anonymous objects should be casted into an Object that is known to the VBFunction in order to be able to work with these objects. For a reason, we cannot set Option Strict off in the code or the compiler in order to use late binding.

Using CType() in order to cast the anonymous object into a similar type in VB.NET didn't worked either and raised an exception.

Do you know an elegant way to transform these anonymous objects into a useful object in the VB.NET script?

Best regards





Field value set using reflection from listner class is set to null when corresponding test class is executed

I am working on testng java and trying to set value of a test class field using reflection from listner class. The value is set and retrieved successfully from listner class but produces null when utilizing the same variable field in @test method

@Listners(Testrunner.class)
public class testclass{
    String strvalue;
   
    @Test
    public void m1(){
      Sysout(strvalue)------> produces null when testng runs @test method but not testvalue
    }
}

Testrunner implements ITestListener{

  @Override
    public void onTestStart(ITestContext arg0) {
        testclass cls = new testclass();
        Field f1 =  testclass.class.getDeclaredField("strvalue");
        f1.setaccessible(true);
        f1.set(cls,"testvalue");
        Sysout(f1.get(cls));---------> i am able to get the value s "testvalue"
        
    }
}

Am i missing any logic in this code, help me in complete this




lundi 27 juillet 2020

Dynamic cast in c# in runtime

I have 2 classes as you can see :

  static void Main(string[] args)
    {

        object m = (??????)"salam";
    }


public class A
{
    public string name { set; get; }
    public static implicit operator A(string _name)
    {
        A aa = new A();
        aa.name = _name;
        return aa;
    }
}
public class B
{
    public string family { set; get; }
    public static implicit operator B(string _family)
    {
        B bb = new B();
        bb.family = _family;
        return bb;
    }
}

I need to cast my string in runtime in this line :

object m = (??????)"salam";

Is there any solution to pass my class name as a string to cast my value .for example in runtime I need to cast "salam" to A or maybe B

The static cast is working good like this

 object m = (A)salam";
 object m = (B)"salam";

But I need to cast my string in runtime

Type x=null;
If(condition) 
x can be type of A
else 
x can be type of B

object m = (x)"salam";




How do I pass a struct argument to a MethodInfo if the struct has a ReadOnlySpan field

I have a MethodInfo object that represents a method, and that method takes a struct as an argument, and that struct has a ReadOnlySpan<byte> field. How do I invoke the method via the MethodInfo object? I can't use MethodInfo.Invoke because Invoke requires the parameters as an object?[]? array and a struct with a ReadOnlySpan<byte> field can't be cast to an object.

So how can I invoke a method via reflection and pass it a struct value where that struct has a field of type ReadOnlySpan?





C# Validate that generic type extends generic abstract class with type parameters

I've am stuck and I'm looking for some clarification.

I'm having an issue with reflection, I have a WPF app and I've implemented a plugin system as documented here: https://docs.microsoft.com/en-us/dotnet/core/tutorials/creating-app-with-plugin-support

However, I've modified and extended this a bit where my plugins extend an Abstract class instead of an Interface directly because I have some stuff in the constructor.

On my project, the overall structure is the following:

    public abstract class AbstractPlugin<TSignatureFile, TLoadedFile> : 
        IPlugin<TSignatureFile, TLoadedFile> 
        where TSignatureFile : IFileSignature
        where TLoadedFile : LoadedFile { }

    public interface IPlugin<out TSignatureFile, TLoadedFile> 
        where TSignatureFile : IFileSignature
        where TLoadedFile : LoadedFile { }

    public class MyPlugin : AbstractPlugin<MyPluginFileSignature, MyPluginFile { }

    public class MyPluginFileSignature : IFileSignature { }

    public class MyPluginFile : LoadedFile { }

I have then a class I call the "PluginManager" which loads instantiates the plugins. This load and instantiate mechanic is mostly based on this: https://github.com/dotnet/samples/tree/master/core/extensions/AppWithPlugin/AppWithPlugin

The problem I'm having is that the "CreatePlugin" method will list all types found in the assembly until it finds a match and instantiate that, which is not working.

The code is something like this:

foreach (Type type in assembly.GetTypes())
{
   if (type.IsClass && !type.IsAbstract && type.IsInheritedFrom(typeof(AbstractPlugin<IFileSignature, LoadedFile>)))
   {
      AbstractPlugin<IFileSignature, LoadedFile> result = Activator.CreateInstance(type, notificationCallBack) as AbstractPlugin<IFileSignature, LoadedFile>;

      if (result != null)
      {
          count++;
          yield return result;
      }
   }
}

From one of the StackOverflow posts someone recommended creating a extension method on Type which is what that "IsInheritedFrom" is.

Here is the current status of it / mess of me trying to get it to work.

public static bool IsInheritedFrom(this Type type, Type lookup)
{
    var baseType = type.BaseType;
    if (baseType == null)
        return false;

    var isAbstract = lookup.IsAbstract;
    var areEqual = baseType == lookup;
    var isSubClass = type.IsSubclassOf(lookup);

    if (baseType.IsGenericType
            && baseType.GetGenericTypeDefinition() == lookup)
        return true;

    return baseType.IsInheritedFrom(lookup);
}

From this, areEqual and isSubClass always returns false. Any ideas?

Thank you.





dimanche 26 juillet 2020

injecting a variable using Java annotation

I have created an annotation and I need to inject a variable (like in SLF4j log variable) using JAVA. Below is my code so far ...

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public  @interface ClassLevelAnno {
    public String testVariable = "abc";
}

And I am trying to use this annotation in the following class

package test;

@ClassLevelAnno
public class UsingTestAnno {
// I need to use testVariable defined in ClassLevelAnno class directly like follow.
    public void testMethod() {
        System.out.println(testVariable);
    }
}

As in the above class, I need to print the variable directly. Why this class level annotation didn't inherit its fields.





MethodInfo.Invoke with custom Class List as parameter

I'm actually writing a simple application that calls functions of an external DLL's based on a command line. First I do have a parameter Class that holds all parameters after parsing from command line:

public class ParserFunctionParameter
{
    string parameterName = "";
    string parameterValue = "";

    public ParserFunctionParameter(string parameterName, string parameterValue)
    {
        this.parameterName = parameterName;
        this.parameterValue = parameterValue;
    }
}

Then I wrote a FunctionLoader Class which basically contains a list of all pre registered DLL's. A single function within this Class looks like this:

public class Function
{
    private Assembly assemblyReference;
    private string functionName;
   
    public Function(Assembly assembly)
    {
        this.assemblyReference = assembly;
        AssemblyName an = assembly.GetName();
        Type type = assembly.GetType(an.Name + ".Class1");
        object o = Activator.CreateInstance(type);
        MethodInfo mi = type.GetMethod("GetFunctionName");
        this.functionName = (string)mi.Invoke(o, null);
    }

    public double[] CallFunction(List<ParserFunctionParameter> parameters)
    {
        AssemblyName an = assemblyReference.GetName();
        Type type = assemblyReference.GetType(an.Name + ".Class1");
        object dllClassObject = Activator.CreateInstance(type);
        MethodInfo mi = type.GetMethod(functionName);
        object[] objParamArray = { parameters };
        return (double[]) mi.Invoke(dllClassObject, objParamArray);
    }
}

So far, this is the application that makes use of the DLL. The DLL itself, looks like this:

public class Class1
{
    public string GetFunctionName()
    {
        return "importcsv";
    }

    public double[] importcsv(List<ParserFunctionParameter> parameters)
    {
        // do some stuff depending on parameters 
    }
}

Let's assume I use it this way, after I've compiled the DLL to ImportCSV.dll:

class Program
{
    static void Main(string[] args)
    {
        List<ParserFunctionParameter> par = new List<ParserFunctionParameter>();
        par.Add("file", "C:\test.csv");
        par.Add("skiplines", "1");

        Function func = new Function(Assembly.LoadFile("ImportCSV.dll",)
        double[] result = func.CallFunction(par);
    }
}

The (not very helpful) exception:

System.ArgumentException: 'Object of type 'System.Collections.Generic.List`1[BML.Parser.ParserFunctionParameter]' cannot be converted to type 'System.Collections.Generic.List`1[BML.Parser.ParserFunctionParameter]'.'

How can I pass the List of ParserFunctionParameter ? I've tried simple 'build in' types like string. This works pretty straight forward. But with this 'custom' type this isn't working.

Since this is just a coding for fun project and to check feasibility of a simple plugin interface, I can provide the complete code, if needed.

Edit: Thaks for the comment on the reserved keyword, but that's not causing the exception. This was just an example of calling. I'm sorry for that -> Corrected it.

Thank you.





samedi 25 juillet 2020

How can I load a jar at runtime and replace it for later use without closing it first?

public class Test
{

    int counter = 1;
    long constructedMillis = System.currentTimeMillis();

    public Test()
    {
        System.out.println("Test constructed! " + constructedMillis + " counter=" + counter);
    }

    public void methodA(String arg1)
    {
        System.out.println("Test methodA called: "+ constructedMillis + " counter=" + counter);
        new Test2();
    }
}
public class Test2
{
    public Test2()
    {
        System.out.println("Test 2 constructed");
    }
}


// another .java
    public static Class loadJar(String pathToJar, String classPkg, boolean closeClassLoader)
    {
        URL[] urls = new URL[]
        {
            new File(pathToJar).toURI().toURL()
        };
        classLoader = new URLClassLoader(urls);
        Class cls = Class.forName(classPkg, true, classLoader);
        if (closeClassLoader) classLoader.close();
        return cls;
    }

public static void main(String[] args)
{
     // example 1: it works but I cannot rebuild the jar so I can reload it for different situation as it is locked from the classLoader since I don't close it in this case.
     {
         boolean closeClassLoader = false;
         Class test = loadJar(args[0],args[1], closeClassLoader);
         Object instance = test.newInstance();
         Method method = test.getDeclaredMethod("methodA", String.class);
         method.invoke(instance, "alpha");
     }

    // example 2:
    // if I do closeClassLoader = true then I get the following exception
    // at the method.invoke(instance, "alpha");
    // because it does new Test2();

    Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)

}

please note, I want the loaded jar to remain functional where I use it, however I also want the after jar to be loaded as well on the same path for the later usages.

For example I want to load a jar that has some functionality and assign user commands on it. But later on I want new users that will arrive to use the next one.

any suggestions?





How do I access type use annotations in kotlin through reflection?

A library I'm using utilises type use annotations to add constraints to variables. For example, if you wanted a configurable opacity (in percent, represented by a float), you'd annotate the float type:

public @Setting.Constrain.Range(min = 0, max = 1, step = 0.1) float opacity = 1f;

I could not get the same library to work on identical kotlin code.

To simplify the question, let's declare the annotation and usage ourselves:

@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JavaAnnot { }
public class TestJava {

    @JavaAnnot int a = 5;

    public static void main(String[] args) {
        System.out.println(TestJava.class.getDeclaredFields()[0].getAnnotatedType().isAnnotationPresent(JavaAnnot.class));
    }

}

Running TestJava#main yields true, indicating that the JavaAnnot annotation is present on the type.

If we introduce a new kotlin class TestKotlin with a similar a field and annotated type:

class TestKotlin {

    val a: @JavaAnnot Int = 5

}

The previous check, now on the TestKotlin class:

TestKotlin.class.getDeclaredField("a").getAnnotatedType().isAnnotationPresent(JavaAnnot.class)

yields false, indicating that the JavaAnnot annotation is NOT present on the Int type of a, even though we clearly did annotate it.

I've tried:

  • Annotating a with @JvmField. This did not change the behaviour.
  • Declaring an identical annotation in kotlin:
@Target(AnnotationTarget.TYPE)
@Retention(AnnotationRetention.RUNTIME)
annotation class KotlinAnnot
val a: @KotlinAnnot Int = 5

Did not fix the problem.

  • Inspecting other metadata accessible through reflection: I did not find anything useful.

Is this a kotlin bug? Do type use annotations not exist in kotlin, or is the syntax different? What am I doing wrong?

Thanks.





Controlling Reflection Intensity

I’m trying to achieve a result similar to [this example] attached an image where the blue and black objects are reflective.

I saw this example: https://threejs.org/examples/?q=mirror#webgl_mirror that uses THREE.Reflector but couldn’t find how to control the reflection intensity (so it won’t be like a mirror) or the reflective object color.

How would you go about this?

Thanks!





Force return statement on caller function

I am just curious if it's possible to force parent method to return a value from within method called in that parent method? Let's say I have:

    public function myApiEndpoint()
    {
      // I DO NOT want to to have return statement here
      $this->validOrUnprocessable();

      // some other code

      //return value
      return $someValue;
    }
    public function validOrUnprocessable()
    {
       if ($condition) {
         ... here goes the code that forces return statement on myApiEndpoint function without putting the word `return` in front of this call...
       }
    }

So in other words validOrUnprocessable method, when it needs to do so forces or tricks PHP into thinking that myApiEndpoint returns the value. I do not want to use return statement when validOrUnprocessable is called or any if conditions.

I do know other ways of doing what I want to do but I wanted to know if something like that is possible. I am not interested in any workarounds as I know very well how to implement what I need to achieve in many other ways. I just need to know if this what I described is possible to do exactly how I described it.

I did try to get there with reflections and other scope related things but so far no luck. Any ideas?

Just to add. I am doing this because I want to check how far I can push it. I am building a tool for myself and I want it to be as convenient and easy to use as possible.

If it's not possible I have another idea but that's a bit out of the scope of this post.





Using reflection to annotated methods that have attributes, and only if the interface is implemented

Given a class and attributes, I would like to use reflection to get the implemented interfaces and the annotate methods that have attributes applied.

In the below class, ITopicNotificationHandler<CommandRequested> and ITopicNotificationHandler<CommandUpdated> are implemented and marked.

The method Task Handle(SomeOtherPoco notification, string topic, CancellationToken cancellationToken) is marked with an attribute but not implemented as an interface on the class.

public class CommandRequestedEventHandler : ITopicNotificationHandler<CommandRequested>, ITopicNotificationHandler<CommandUpdated>
{
    [BusSubscription("{\"symbol\": [\"TVIX\"],\"timespan\": [\"1s\"]}")]
    [BusSubscription("{\"symbol\": [\"MSFT\"],\"timespan\": [\"1s\"]}")]
    public Task Handle(CommandRequested notification, string topic, CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }

    [BusSubscription("{\"symbol\": [\"OTHER\"],\"timespan\": [\"1s\"]}")]
    public Task Handle(SomeOtherPoco notification, string topic, CancellationToken cancellationToken)
    {
        // this is not implemented as an interface, and should ignored
        return Task.CompletedTask;
    }

    [BusSubscription("{\"symbol\": [\"TVIX\"],\"timespan\": [\"1s\"]}")]
    public Task Handle(CommandUpdated notification, string topic, CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}

As per Find methods that have custom attribute using reflection I can get the methods:

var methods = assembly.GetTypes()
                  .SelectMany(t => t.GetMethods())
                  .Where(m => m.GetCustomAttributes(typeof(MenuItemAttribute), false).Length > 0)
                  .ToArray();

However, since i do container registration and other tasks based on scanning for implemented interfaces (of type ITopicNotificationHandler), as important that the method is marked with [BusSubscription] attribute, it should only be considered valid if it is implemented in the interface list of the class.

Would i get the list of methods then check the interface is implemented, or would one get the list of interfaces then check the method and read the attribute?

Essentially i would need the function below, but I am unsure of the best way and appreciate any pointers:

IEnumerable<BusSubscriptionAttribute> subscriptions = GetSubscriptionAttributes(typeof(ComamndHandler));




vendredi 24 juillet 2020

Passing additional information to event handler in dynamic event hooking

I am trying to hook to an event dynamically using reflection. The code is successfully getting execution to handler function HandleInfoMessage. The issue I need to address, at times different events with same evernt args type raise events and from the event args I am not able to identify the name of the event particularly raised. Is there any way that I can get the event name in handling function when it get raised?

public void AsyncRegisterForEventInternal(string eventName, ToolComponent toolComponent) {
    EventInfo ev = toolComponent.GetType().GetEvent(eventName);
    var handler = Create(ev, HandleInfoMessage);
    ev.AddEventHandler(toolComponent, handler);
}

private Delegate Create(EventInfo evt, Action < object, EventArgs > d) {
    var handlerType = evt.EventHandlerType;
    var eventParams = handlerType.GetMethod("Invoke").GetParameters();
    var parameters = eventParams.Select(p = >Expression.Parameter(p.ParameterType, "x")).ToArray();
    var body = Expression.Call(Expression.Constant(d), d.GetType().GetMethod("Invoke"), parameters[0], parameters[1]);
    var lambda = Expression.Lambda(body, parameters.ToArray());
    return Delegate.CreateDelegate(handlerType, lambda.Compile(), "Invoke", false);
}

protected virtual void HandleInfoMessage(object obj, EventArgs eventArgs) {
    Console.WriteLine("InfoMessage {0}:{1}", obj.GetType().ToString(), eventArgs.GetType().ToString());
}




SecurityException when trying to cast Field in Reflection

I've started learning Reflection API.

In this test, I need to invoke a method that is sitting inside the instance cache of object Cache.

Reflection returns it as an instance of Field, and I am trying to cast it to Cache. But to no avail.

How could I fix this?





Get subclass back when stored as superclass

So I've been trying to fix this for a few hours now, to no avail.

Basically, I have class A, and class B which extends A. A has a string field "name", and another field "id", class B changes name when instantiated. B is then later stored as A, and the only thing identifying that A class to the B class is the "id" field.

I need a way to get the changed "name" that the B class has, from the A class.

Here's a code example:

class A {
    public String name = "test";
    public String id = "A_ID";
    
    public A(String id) {
        if (id.equals("B_ID") {
            // how would I get the name field of the B class, without instantiating B
        }
    }
}
class B extends A {
    {
        name = "test1";
        id = "B_ID";
    }
}

And here's what I've tried:

class A {
    public static Map<String, Class<? extends A> REGISTRY = new HashMap<>();
    
    public String name = "test";
    public String id = "A_ID"; // is B_ID when changed
    
    public Object getField(String key) {
        Field field = REGISTRY.get(this.id).getSuperclass().getDeclaredField(key);
        return field.get(this); // <- the issue
    }
}
class B extends A {
    static {
        REGISTRY.put("B_ID", B.class);
    }
    public B() {
        name = "test1";
        id = "B_ID";
    }

}

Here's the problem with my solution, passing this to field.get(this) returns the fields of the current A object, which is what we already have. I need the fields that B changes when instantiated, but when B gets instantiated it calls getField a few times, which then causes a perpetual loop, I need a way to get the fields from B without instantiating B.

I've tried casting A to B but that causes a ClassCastException.

Sorry that this is confusing, I can't send the entire class as it's literally 1k+ lines, but basically the ID field is the only data stored with A that remains from B, and I need a way to get the fields from B without instantiating it





C# Compiled expression to create new instance of T and copy values to its properties from another instance of T

I would like to know if it is possible to create an instance of a type known only at runtime and assign values to the properties of this instance by using compiled expressions and if so how it is to be done.

I have a generic class with a method which accepts an instance of T and returns a copy. T is only known at runtime or rather is user/consumer defined. I know how to do so with reflection (assuming it has an empty constructor in this example and without exception handling or null checks for simplification).

public class MyClass<T>
{
    public T CreateCopy(T source)
    {
        var type = typeof(T);
        var copy = type.GetConstructor(Type.EmptyTypes).Invoke(null);
        foreach(var pi in type.GetProperties())
        {
            pi.SetValue(copy, pi.GetValue(source));
        }
        return copy;
    }
}

Reflection is quite expensive and after some digging i found an option to at least create an instance of T with compiled expressions.

var type = typeof(T);
Expression.Lambda<Func<T>>(Expression
   .New(type.GetConstructor(Type.EmptyTypes)
       ?? throw new InvalidOperationException(
           $"Type has to have an empty public constructor. {type.Name}")))
   .Compile();

After some benchmarking i have found out that it performs around 6 times faster than the CreateCopy(...) method. The thing is that i do not know which type will be passed in as a generic and how many properties it will have. Is there a way to do all of the operations from CreateCopy(...) method with compiled expressions?

Ihave looked into Expression.Asign, Expression.MemberInit but i am not able to find anything appropriate. The problem with Expression.MemberInit ist that it expects to have an Expresssion.Bind and Expression.Constant but i cant get the values of the properties from the passed instance of T into it. Is there a way?

Thank you.

P.S. So i am looking for something like:

var type = typeof(T);
var propertyInfos = type.GetProperties();
var ctor = Expression.New(type.GetConstructor(Type.EmptyTypes));
var e = Expression.Lambda<Func<T, T>>(Expression
            .MemberInit(ctor, propertyInfos.Select(pi => 
                Expression.Bind(pi, Expression.Constant(pi.GetValue(source)))))).Compile();




Is it possible to get all the test categories from mstest solution dll using reflection?

Is it possible to get all the test categories from mstest solution dll using reflection? I tried, Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");

but when i attempt to get types from this assembly using, var types = testAssembly.GetTypes();

it throws ReflectionTypeLoadException. I believe once i get the types i can look for CutomAttribute 'TestCategoryAttribute'.





Iron Python: can I reflect over compiled Python assembly from within .NET

I have a .NET application that makes significant use of reflection, reflecting over C# and VB class libraries. I would like to add the option to include Python class libraries, written using Iron Python and compiled to .NET assemblies. Will that work? The only references I have so far found to reflection in Iron Python refer to reflecting over external .NET assemblies from within Iron Python code. I need it the other way around.

(I know that the correct response in Stack Overflow is 'Have you tried it?'. I have not yet tried Iron Python at all. I don't want to invest the time learning how to use Iron Python if my fundamental requirement is a wild goose chase. So if anyone knows whether what I require will definitely/definitely-not work, I would appreciate it.)





Distinguish overloaded methods in Kotlin reflection

I have two methods:

class Example {
    fun method(name: String): String {}

    fun method(name: String, length: Int): String {}
}

And at some point in my code I need to use the second version of method via reflection, like so:

val func = Example::method

This can't compile because the compiler can't tell the difference between the two definitions of this overloaded method. I can't find a way to specify the parameteres for the function. The documentation says:

Alternatively, you can provide the necessary context by storing the method reference in a variable with an explicitly specified type:

val predicate: (String) -> Boolean = ::isOdd // refers to isOdd(x: String)

But in my case, the function assigned to func can be arbitrary, it does not necessarily has two parameters of types String and Int, and in other cases the function assigned to this property only has the single String parameter. But in this case, I need the version with two parameters.

So, is there any way to specify which function I'm using, and if not, is there any workaround?





jeudi 23 juillet 2020

Why MethodHandle is slow than Reflection in JDK 1.8?

I have two performance tests using JMH. The code is very easy,one is using Java Reflection,Another is using MethodHandle(Introduced in JDK1.7),By The way,isEmptyMethod and MH_isEmpty is declared as static final,like this:

private static final MethodHandle MH_isEmpty;
private static final Method isEmptyMethod;

static {
    try {
        MH_isEmpty = MethodHandles.publicLookup().findVirtual(String.class, "isEmpty", MethodType.methodType(boolean.class));
        isEmptyMethod = String.class.getDeclaredMethod("isEmpty");
    } catch (Exception ex) {
        throw new UnsupportedOperationException();
    }
}

` Java Reflection:

@BenchmarkMode(Mode.Throughput)
public void testReflectionGetIsEmpty() throws Exception {
    isEmptyMethod.setAccessible(false);
    final Object result = isEmptyMethod.invoke("SmartLee");
}

` MethodHandle:

@Benchmark
@BenchmarkMode(Mode.Throughput)
public void testFindVirtual() throws Throwable {
    final MethodHandle isEmpty = MH_isEmpty.bindTo("SmartLee");
    isEmpty.invoke();
}

Beblow is the performance results: performance results

According to JDK docs.Why MethodHandle is not faster than java reflection? What's wrong with above code?





Compare 2 of the same .NET objects and detect properties that are missing from one but present in the other

I have a .NET Core Web API + Entity Framework Core, and I am trying to cater for clients sending incomplete / partial JSON Payloads to update an existing Customer (and associated Entities) record. For instance, they may not send the date_of_birth attribute at all, so would like this to mean that the date_of_birth already in the database is not updated at all. At the moment I have the following method,

private static T CheckUpdateObject<T>(T dbEntity, T updateEntity) where T : class 
{
    foreach (var property in updateEntity.GetType().GetProperties())
    {
        if (property.GetValue(updateEntity, null) == null)
        {
            Console.WriteLine($"Entity property {property.Name} is NULL. It will not be updated.");
            property.SetValue(updateEntity, dbEntity.GetType().GetProperty(property.Name)
            .GetValue(dbEntity, null));
        }
    }
    return updateEntity;
}

Which ensures that if for example, date_of_birth is passed as Null, we overwrite it with the value already in the database before saving the Entity (and if other values are non Null, we accept those new values). However, I am unclear how to extend this to cater for when the attribute is missing completely? So, the dbEntity (taken from the existing record in the Database) will have a date_of_birth attribute, but the incoming updateEntity object may not. In this case, I'd like to leave the attribute alone.

I want this to be generic enough to apply to any attribute that is absent from the incoming payload. E.g. if the client wants to update address_line_2 of the customers Address, they don't need to pass

Address:
 address_line_1: 23 spooner
 address_line_2: some new value
 post_code: 3030

They can just pass

Address:
 address_line_2: some new value 

And be comfortable that address line 1 and post code won't be touched. My method works if they pass

Address: 
 address_line_1: null
 address_line_2: some new value
 post_code: null

But I think it's a bit cumbersome, and NULLs attributes not passed in at all.





How can I group an array of properties by their attribute?

I have an array of properties (System.Reflection.PropertyInfo[8]). Each of these properties have a custom attribute set on them. I want to group them all by which custom attribute they have and am trying to use reflection to do this. So far I have tried:

            var searchableProperties = properties.GroupBy(a => a.GetCustomAttribute(typeof(IsSearchableAttribute)));
            var filterableProperties = properties.GroupBy(a => a.GetCustomAttribute(typeof(IsFilterableAttribute)));

However these are coming back as null rather than grouping by attributes.

Can anyone point out to me where I am going wrong here? Thanks





How to list-unpacking in C#?

Python-like list unpacking in C#?

there are already same question on stackoverflow, but there are just brief answer that says "Use reflection and Invoke!". I totally can't understand the answer so I re-questioning here.

I really want to know how to do list-unpacking in c# like python.





Fully qualified name of a class?

class MethodFinder {

    public static String findMethod(String methodName, String[] classNames) {
            for(String cn: classNames){
                if(cn.getMethods() == methodName){
                    return methodName.getName();
                }
            }
    }
}

The method should return fully qualified name of a class.How to fix it? For example, the method name is abs and possible classes are String, StringBuffer and Math.

String and StringBuffer have no method with the name abs. So they are not the class we are looking for. Math class has a method with the name abs. The method should return the fully-qualified name of Math class, java.lang.Math in this case.





mercredi 22 juillet 2020

Go: Get return type of a function

I'm writing higher order functions in Go, and am trying to figure out the return type of the inner function f.

As a simple example, let's say I want to return the default value of the return type of the inner function:

  • if f returns string, GetDefault(f) returns ""
  • if f returns []byte, GetDefault(f) return []byte{}
func GetDefault(func(interface{})) {
  // How would I write this function?
}

Is it possible to write such a function in Go, without running f?





How to get custom options through a protobuf descriptor file

I have this in the .proto file:

test.proto:

syntax = "proto3";
import "google/protobuf/descriptor.proto";
extend google.protobuf.FileOptions{
    optional string myOption = 50000;
}

option (myOption) = "foo";

I then create the the descriptor file by doing: protoc --include_imports --descriptor_set_out="test.desc" test.proto

In the Java code I then open "test.desc" and get the FileDescriptor object for it. I want to be able to get the custom option I created.

When I print out FileDescriptor.getOptions() it shows my custom option but I don't know how to get myOption specifically.





Why is reflection not showing my C# attribute [duplicate]

I have the following class:

 public class LookUpModel
    {

        [Key]
        public string Id { get; set; }

        [IsSearchable]
        public string Code{ get; set; }

        [IsSearchable]
        public string Name { get; set; }

        [IsSearchable]
        public string Address { get; set; }

        [IsSearchable]
        public string PostCode { get; set; }  
        

In order to make a comparison with some other data, I am trying to get the number of attributes back. I.e. I want to know that there are 4 'IsSearchable' attributes on this class. I have tried the following code:

                    var lookupModel= new LookUpModel() { Id = "1", Address = "", Name = "", PostCode = ""};
                    var attributes = gpModel.GetType().GetCustomAttributes(true).Where(a => a.GetType() == typeof(IsSearchableAttribute));
                    var attributeCount = attributes.Count();

However this returns 0? Can anyone please point me in the right direction here/point out where I am using reflection incorrectly? Thanks





C# Assembly.Load() method loads the wrong dll?

Problem Statement

I'm implementing some sort of a Shadow Copy in C# when loading dll, to prevent the dll file from being locked. It works as follows:

  1. Say I have sample.dll and want to load it into the appdomain without locking it
  2. First I make a copy of the assembly with the name sample_shadow.dll in the same directory
  3. Then I load sample_shadow.dll with Assembly.Load (Assembly.LoadFrom and AssemblyName.GetAssemblyName are also tried)
  4. After that, the loaded assembly appears to have a base location of sample.dll instead of sample_shadow.dll, and sample.dll is locked

Questions

  1. I'd like to know how can I load sample_shadow.dll correctly and thus prevent sample.dll to be locked
  2. I'd appreciate very much if someone can elaborate on the mechanisms in the background

Thanks in advance!

P.S. To load assembly with bytes is not an option due to the use of multiple dll and static variables (I think the load-bytes version missed some information compared to the load-with-file-name version of Assembly.Load)





Exception is thrown when i try to call a reflection method

I am new to java and trying to use Java reflection to set value to static final field I found below example code and trying to compile in JAVA 11.

static void setFinalStatic(Field field, Object newValue) throws Exception {
        field.setAccessible(true);
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true); 
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        field.set(null, newValue);
    }

But below Exception is thrown in Java 11 . Field class has a field called "modifiers" Could not figure out what is the issue here . It works for ArrayList , Set etc .

 Time elapsed: 2.383 s  <<< FAILURE!

java.lang.NoSuchFieldException: modifiers
        at java.base/java.lang.Class.getDeclaredField(Class.java:2412)




Can i read file properties from unmanged .dll or .exe in .NET

How can i read file informations like title, description, copyright etc from unmanaged dlls and exe, written in c++, with C#?

I know how to get these informations from managed code with MetadataLoadContext, but loading an C++ Exe/DLL will throw an exception: System.BadImageFormatException: This PE image is not a managed executable.





mardi 21 juillet 2020

Deep Clone ICollection

Consider there is method which performs deep clone of any type

T Clone<T>(T obj) { /**/ }

and also consider that method which performs a copy of singular object smth like this

object CopyObject(object obj)

already implemented

So I need return

ICollection<T>

after iterating and copying each object seperately

Expected Result

            var collection = new Collection<int>();
            collection.Add(1);
            collection.Add(2);
            ICollection<int> things = collection;
            var cloned = Clone(things);
            //Assert cloned is ICollection<int> , not List, not IList, not anything else

Solution like this

     var collectionGenericType = typeof(Collection<>).MakeGenericType(underlyingType);
                        var genericCollectionInstance = Activator.CreateInstance(collectionGenericType, buffer);
                      
return (T)Convert.ChangeType(genericCollectionInstance, typeof(T));
        

not worked it throws "System.InvalidCastException: Object must implement IConvertible"

This solution what I currently use

 var collectionGenericType = typeof(List<>).MakeGenericType(underlyingType);
                            var genericCollectionInstance = Activator.CreateInstance(collectionGenericType, buffer);
                          
    return (T)Convert.ChangeType(genericCollectionInstance, typeof(T));

is working, but it is creating List.

buffer is an array where all items of source are already deep cloned

underlyingType is Type which lays under generic class (e.g. ICollection it will be System.Int32)





Opengl : Render To Cubemap?

I am trying to render 3d scene to a cubemap but the cubemap only renders the skybox, here is my RenderToCubemap function:

GLuint RenderToCubemap(glm::vec3 position, float resolution, float nearPlane, float farPlane)
{
    unsigned int CM_FBO;
    unsigned int textureID;
    glGenFramebuffers(1, &CM_FBO);
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);

    for (unsigned int i = 0; i < 6; i++)
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGBA, resolution, resolution, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

    // attach depth texture as FBO's depth buffer
    glBindFramebuffer(GL_FRAMEBUFFER, CM_FBO);
    glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureID, 0);

    if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
        std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl;
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    glm::mat4 shadowProj = glm::perspective(glm::radians(90.0f), (float)resolution / (float)resolution, nearPlane, farPlane);
    std::vector<glm::mat4> shadowTransforms;
    shadowTransforms.push_back(shadowProj * glm::lookAt(position, position + glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)));
    shadowTransforms.push_back(shadowProj * glm::lookAt(position, position + glm::vec3(-1.0f, 0.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f)));
    shadowTransforms.push_back(shadowProj * glm::lookAt(position, position + glm::vec3(0.0f, -1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f)));
    shadowTransforms.push_back(shadowProj * glm::lookAt(position, position + glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, -1.0f)));
    shadowTransforms.push_back(shadowProj * glm::lookAt(position, position + glm::vec3(0.0f, 0.0f, -1.0f), glm::vec3(0.0f, -1.0f, 0.0f)));
    shadowTransforms.push_back(shadowProj * glm::lookAt(position, position + glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, -1.0f, 0.0f)));

    // Render scene to cubemap
    // --------------------------------
    glViewport(0, 0, (int)resolution, (int)resolution);
    glBindFramebuffer(GL_FRAMEBUFFER, CM_FBO);

    Camera capture_cam;
    capture_cam.temp_cam = true;
    capture_cam.projectionMatrix = shadowProj;
    capture_cam.transform.Position = position;
    for (size_t i = 0; i < 6; i++)
    {
        capture_cam.viewMatrix = shadowTransforms[i];

        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, textureID, 0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        RenderScene(capture_cam);
    }

    return textureID;
}

RenderScene function :

void RenderScene(Camera& cam)
{
    glm::mat4 proj = cam.GetProjectionMatrix();
    glm::mat4 view = cam.GetViewMatrix();
    glm::vec3 viewPos = cam.transform.Position;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        Shader* shader = &materials.main_shader;

        shader ->use();
        shader ->SetMat4("projection", proj);
        shader ->SetMat4("view", view);
        shader ->SetVec3("CamPos", viewPos);

        // Render all meshs
        // ----------------------------------------------------
        for (size_t i = 0; i < Meshs.size(); i++)
        {
            if (Meshs[i].Material == nullptr)
                continue;

            Meshs[i].Material->setShaderProperties(shader);

            shader->SetMat4("model", Meshs[i].Transform);
            Meshs[i]->Draw();
       }    
    
    // render skybox 
    // ----------------------------------------------------
    glDepthFunc(GL_LEQUAL);  // change depth function so depth test passes when values are equal to depth buffer's content
    Shader* bg = &materials.background;
    bg->use();
    bg->SetMat4("view", view);
    bg->SetMat4("projection", proj);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_CUBE_MAP, envCubemap); 
    renderCube();
    glDepthFunc(GL_LESS); // set depth function back to default
}

I am using RenderScene for main rendering and it works, but when i use it in renderToCubemap it shows only the skybox.

Any help or correction?





C# : Assign generic Multicast-Delegate to Action with different amount of parameters via reflection

So in my class are some delegates all being Action<...> fields. Example:

public Action<int> onDiceRolled;
public Action<Turn, Round> onTurnEnded;

and I want to assign an anonymous function to each of them using reflection.

    GetType().GetFields()
    .Where(field => field.FieldType.ToString().Contains("Action"))
    .ToList()
    .ForEach(field =>
    {
        Type type = field.FieldType; // e.g. Action<Turn, Round>
        if (!type.IsGenericType)
            return;

        Type[] para = type.GetGenericArguments(); // in example cases: {int} or {Turn, Round}
        MethodInfo debugMethod = (new Action(() => Console.WriteLine(field.Name + " was called."))).Method;
        field.SetValue(this, Delegate.CreateDelegate(type, debugMethod));
    });

Of course this does not work since the created delegate does not have any parameter while the parameters it needs are stored in para. Unfortunately I cannot find any way to create a delegate by an array of types.

So basically I want to do

onDiceRolled += (i) => Console.WriteLine("onDiceRolled was called.");

for each action field in my class





php, refreshing ReflectionClass after dynamic change

I'm trying to build a tool that add/remove methods for me in a class, basically saving me the time to type some standard methods I use in my framework.

However, it seems to me that the getMethods method of the ReflectionClass uses some sort of cache, because if I call getMethods once, then change the methods dynamically (for instance replacing the class file with another one with the same class name but different methods), then call getMethods again, it doesn't take into account my dynamic changes.

I tried sleep, but it was obviously not that.

I was wondering if there is a way (but I'm afraid there is not) in php to "refresh" the ReflectionClass, so that it can "reflect" on the actual content rather than on some sort of cache.

As a work around, I can rely on tokens, but that requires a bit more work than just using the Reflection classes, so it would be great if I could "reset" the Reflection cache somehow.





Get InterfaceMethod-pendant from TargetMethod by InterfaceMapping

I have a property on a class which is implemented by an interface. Now I want to get all attributes from a specific type declared on that property and their interface Pendants.

In order to regard multi implementation wich implicit and explicit members I wrote an test-class (with xUnit).

    [DebuggerDisplay("{Tooltip}")]
    [AttributeUsage(AttributeTargets.Property)]
    public class TooltipAttribute : Attribute
    {
        public TooltipAttribute(string tooltip)
        {
            Tooltip = tooltip;
        }

        public string Tooltip { get; set; }
    }

    public interface IAmGood
    {
        [Tooltip("GOOD: I am a very generic description.")]
        int Length { get; }
    }

    public interface IAmBad
    {
        [Tooltip("BAD: This description is not wanted to be shown.")]
        int Length { get; }
    }

    public class DemoClassImplicit : IAmGood, IAmBad
    {
        [Tooltip("GOOD: Implicit")]
        public int Length => throw new NotImplementedException();

        [Tooltip("BAD: Explicit")]
        int IAmBad.Length => throw new NotImplementedException();
    }

    public class DemoClassExplicit : IAmGood, IAmBad
    {
        [Tooltip("GOOD: Explicit")]
        int IAmGood.Length => throw new NotImplementedException();

        [Tooltip("BAD: Implicit")]
        public int Length => throw new NotImplementedException();
    }

    public class DemoClassImplicitForBoth : IAmGood, IAmBad
    {
        [Tooltip("I am GOOD and BAD")]
        public int Length => throw new NotImplementedException();
    }

    public class TestClass
    {
        [Fact]
        public void GetTooltipFromImplicit()
        {
            var demoClassImplicit = new DemoClassImplicit();
            var propertyInfo = demoClassImplicit.GetType().GetRuntimeProperty("Length");

            var tooltips = GetTooltipAttribute<TooltipAttribute>(propertyInfo);

            Assert.Equal(2, tooltips.Count());
            Assert.All(tooltips, o => Assert.Contains("GOOD", o.Tooltip));
        }

        [Fact]
        public void GetTooltipFromExplicit()
        {
            var demoClassImplicit = new DemoClassExplicit();
            var propertyInfo = demoClassImplicit.GetType().GetRuntimeProperties().First(o => o.Name.EndsWith(".Length"));

            var tooltips = GetTooltipAttribute<TooltipAttribute>(propertyInfo);

            Assert.Equal(2, tooltips.Count());
            Assert.All(tooltips, o => Assert.Contains("GOOD", o.Tooltip));
        }

        [Fact]
        public void GetTooltipFromImplicitForBoth()
        {
            var demoClassImplicit = new DemoClassImplicitForBoth();
            var propertyInfo = demoClassImplicit.GetType().GetRuntimeProperty("Length");

            var tooltips = GetTooltipAttribute<TooltipAttribute>(propertyInfo);

            Assert.Equal(3, tooltips.Count());
        }

        /// <summary>
        /// The core method.
        /// </summary>
        public IEnumerable<T_Attribute> GetTooltipAttribute<T_Attribute>(PropertyInfo propInfo)
            where T_Attribute : Attribute
        {
            var result = new List<T_Attribute>(propInfo.GetCustomAttributes<T_Attribute>());

            var declaringType = propInfo.DeclaringType;
            // The get method is required for comparing without use the prop name.
            var getMethodFromGivenProp = propInfo.GetGetMethod(true);

            // Check for each interface if the given property is declared there 
            // (it is not a naming check!).
            foreach (var interfaceType in declaringType.GetInterfaces())
            {
                var map = declaringType.GetInterfaceMap(interfaceType);

                // Check if the current interface has an member for given props get method.
                // Attend that compare by naming would be cause an invalid result here!
                var targetMethod = map.TargetMethods.FirstOrDefault(o => o.Equals(getMethodFromGivenProp));
                if (targetMethod != null)
                {
                    // Get the equivalent get method on interface side.
                    // ERROR: The error line!
                    var interfaceMethod = map.InterfaceMethods.FirstOrDefault(o => o.Name == targetMethod.Name);
                    if (interfaceMethod != null)
                    {
                        // The get method does not help to get the attribute so the property is required.
                        // In order to get the property we must look which one has the found get method.
                        var property = interfaceType.GetProperties().FirstOrDefault(o => o.GetGetMethod() == interfaceMethod);
                        if (property != null)
                        {
                            var attributes = property.GetCustomAttributes<T_Attribute>();
                            if (attributes != null)
                            {
                                result.AddRange(attributes);
                            }
                        }
                    }
                }
            }

            return result;
        }
    }

The test method 'GetTooltipFromExplicit' failes because in the core method is a comparison by name. I marked the line above with // ERROR: The error line!.

I have no idea how to find the method-pendant inside of 'InterfaceMapping'-class.





Adding custom attributes to ReturnParameter using reflection or IL

I am trying to create some types on runtime using IL. I have an original MethodInfo which I have to replicate.

var parameters = OriginalMethod.GetParameters();

MethodBuilder methodBuilder = Builder.DefineMethod(
    $"<{OriginalMethod.Name}>k__BackingMethod",
    OriginalMethod.Attributes,
    CallingConventions.HasThis,
    OriginalMethod.ReturnType,
    parameters.Select(i => i.ParameterType).ToArray()
);

foreach (var attribute in OriginalMethod.GetCustomAttributesData().ToCustomAttributeBuilder())
    methodBuilder.SetCustomAttribute(attribute);

foreach (var attribute in OriginalMethod.ReturnParameter.GetCustomAttributesData().ToCustomAttributeBuilder())
    methodBuilder.SetCustomAttribute(attribute); // <---- Problem here

ILGenerator il = methodBuilder.GetILGenerator();
// Some code removed for brevity

return methodBuilder;

As you can see, I can successfully copy the method level custom attributes. I can even get the attributes on ReturnParameter. However, I cannot seem to add new attribute to ReturnAttribute. Using the above code, the return attribute is applied as a regular method attribute. Any idea how I would do something like this?

EDIT: Added code for ToCustomAttributeBuilder

internal static CustomAttributeBuilder[] ToCustomAttributeBuilder(this IEnumerable<CustomAttributeData> CustomAttributes)
=> CustomAttributes.Select(attribute => attribute.ToCustomAttributeBuilder()).ToArray();

internal static CustomAttributeBuilder ToCustomAttributeBuilder(this CustomAttributeData CustomAttribute)
{
    var attributeArgs = CustomAttribute.ConstructorArguments.Select(a => a.Value).ToArray();

    var propertyArgs = CustomAttribute.NamedArguments.Where(i => i.MemberInfo is PropertyInfo);
    var propertyInfos = propertyArgs.Select(a => (PropertyInfo)a.MemberInfo).ToArray();
    var propertyValues = propertyArgs.Select(a => a.TypedValue.Value).ToArray();
    
    var fieldArgs = CustomAttribute.NamedArguments.Where(i => i.MemberInfo is FieldInfo);
    var namedFieldInfos = fieldArgs.Select(a => (FieldInfo)a.MemberInfo).ToArray();
    var namedFieldValues = fieldArgs.Select(a => a.TypedValue.Value).ToArray();
    
    return new CustomAttributeBuilder(CustomAttribute.Constructor, attributeArgs, propertyInfos, propertyValues, namedFieldInfos, namedFieldValues);
}