mercredi 30 septembre 2020

Check if function belongs to namespace or global

I need check if called function belongs to the current namespace or it is defined globally.

<?php

namespace Test;

function is_string($str) { return false; }

var_dump(is_string('test'));  // will be always false, is the namespaced is_string()
var_dump(\is_string('test')); // will be the global is_string()

Now I need check if is_string() or \is_string() is defined inside the namespace or is global, and it will occur at the same file. Sometimes the namespaced version will not be defined.

I have tried to use the ReflectionFunction class, but it no works:

var_dump((new \ReflectionFunction('is_string'))->inNamespace());      // returns false, instead of true
var_dump((new \ReflectionFunction('is_string'))->getNamespaceName()); // returns '', instead of 'Test'

var_dump((new \ReflectionFunction('\\is_string'))->inNamespace());      // returns true, that is right
var_dump((new \ReflectionFunction('\\is_string'))->getNamespaceName()); // returns '', that is right

Seems that it always points to the global, but when I just run is_string() it uses the namespaced version (that is correct on this context).





Get property name and value only if there is a value

I'm trying to simulate a .csv file with a list of property names as a header row followed by the actual list of properties for a list of items.

Currently I have it working, but now there is a need to only include the properties' header and value where the item has a value for that property anywhere in the list.

This is what I have currently:

public static string LeadsToCSVString(List<Lead> leads)
{
    StringBuilder builder = new StringBuilder();
    PropertyInfo[] properties = typeof(Lead).GetProperties();
    builder.AppendLine(string.Join(",", properties.Select(x => x.Name)));

    foreach (Lead lead in leads)
    {
        builder.AppendLine(string.Join(",", properties.Select(x => x.GetValue(lead))));
    }

    return builder.ToString();
}

Where Lead is:

public Lead
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool IsOk { get; set; }
}

The List<Lead> isn't guaranteed to have a value for all property values and there can even be a case where there is no value for a property like below:

FirstName,LastName,IsOK
Joe,,false
Adam,,true

What needs to be done is to only have header values and row column values where the property has an actual value. If I take the above example list, the CSV string would look like:

FirstName,IsOk
Joe,false
Adam,true

How can I modify my code to do this?

Some examples of what should happen if any object in the list has a value for the property:

FirstName,LastName,IsOK
Joe,Dirt,
Adam,,true

FirstName,LastName,IsOK
,Dirt,
Adam,,true




Change discriminator value in Entity Framework

When using TPH(table per hierarchy) in EF core, the default behavior is to add a discriminator column that holds the derived type name. All subclasses are empty - they are only used to differentiate the rows in the database.

The scenario I'm facing is that I need to create and add some new types under runtime. Is this possible? I have tried to create a class dynamically, but I can't cast it to the subtype. When I'm inserting the value the discriminator value is the same as the base type. Another solution is that I could use raw SQL to insert the rows, but I don't know if it's possible to fetch the inserted rows from the database again. I tried the following:

            AssemblyName aName = new AssemblyName("DynamicAssemblyExample");
            AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(aName,
                    AssemblyBuilderAccess.RunAndCollect);
       
            ModuleBuilder modb = ab.DefineDynamicModule("test");

            TypeBuilder tb = modb.DefineType("testType", TypeAttributes.Public | TypeAttributes.Class);
            tb.SetParent(typeof(MyBaseType));
            var typeInfo= tb.CreateTypeInfo();

            var objToInsertInDb = (MyBaseType) Activator.CreateInstance(typeInfo);

            baseTypeRepository.Add(objToInsertInDb);




How can I get custom type with reflect?

The following data types are defined:

type Status int
type RealStatus Status

Is there a way to get from RealStatus type to Status type with reflection?





Passing a class object that only PostSharp can see

I'm not sure if this is possible or not.

I have a method call from client api to service api (two separate projects in two separate locations) that I want post sharp to intercept. Calls are from the client and postsharp is on the service

service.GetLogin(username)

The key here is I need to pass an authorization object that will show in the postsharp onentry method

 public class Authorization
    {
        public string client_id  { get; set; }
         public string client_secret { get; set; }
        public string access_token { get; set; }
        public string token_type { get; set; }
        public string expires_in { get; set; }
    }

var auth = new Authorization();
 auth.client_id = "xyz";
 auth.client_secret = "abc"

and in postsharp

 [Serializable]
    public class LoggingAspect : OnMethodBoundaryAspect
    {
        public override void OnEntry(MethodExecutionArgs args)
        {
           //I need the object to show up here
        }
    }

Problem: I do not want to pass this object in every single method call as I have over 1000 methods. Is there a way to attach that authorization object to each call so that postsharp can see it without doing something like this

service.GetLogin(username, auth);
service.Foo(auth)
service.Bar(auth);
service.xyz(auth);
services.abc(auth);

Can you imagine adding just this one object to over 1000 methods?





How to set a struct member that is a pointer to an arbitrary value using reflection in Go

Note: I want to do the same as How to set a struct member that is a pointer to a string using reflection in Go, but in a more generic way. The existing question does not solve my problem.

I have structs with different kinds of fields that I want to populate using reflection:

type MyStruct struct {
    SomeInt       int
    SomeString    string
    SomeIntPtr    *int
    SomeStringPtr *string
}

The value I want to write into the individual fields is retrieved from a configuration-store and parsed into the correct type, similar to this:

func getValueForField(fieldName string) interface{}

For int and *int types, the function returns an int (wrapped in an interface). For string and *string, the function returns string (behind an interface) and so on, for all types.

--> Note that it does NOT return *int/*string!

And now I want to assign the value to the struct fields:

var field reflect.Value  = reflect.ValueOf(ptrToMyStruct).Elem().Field(i)
var value interface{}    = getValueForField(....)
var isPointer bool       = field.Kind() == reflect.Ptr

// assign "value" to "field":
if isPointer {
    // ??
    field.Set(reflect.ValueOf(value).Addr()) // panic: reflect.Value.Addr of unaddressable value
} else {
    field.Set(reflect.ValueOf(value)) // works
}

Assigning those values to concrete types is easy and works as expected. But I can't assign an int type (returned from getValueForField) to an *int field without somehow getting an address. And since I only have an interface{}, this needs to be done via reflection.





How to create instance by interface using reflection?

I'm trying coding Spring's DI , just a simple example. There is a controller, and this @AutoWired is a Empty Annotation defined by me.

public class UserController {
    @AutoWired
    private UserServise userServise;
}

This is the code that implement Annotation injection:

UserController userController = new UserController();
Class<? extends UserController> clazz = userController.getClass();

Stream.of(clazz.getDeclaredFields()).forEach(field -> {
    AutoWired annotation = field.getAnnotation(AutoWired.class);
    if (annotation != null) {
        field.setAccessible(true);
        Class<?> type = field.getType();
        try {
            Object o = type.getDeclaredConstructor().newInstance();
            field.set(userController, o);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

When the program runs into

Object o = type.getDeclaredConstructor().newInstance();

throws

java.lang.NoSuchMethodException: com.learning.servise.UserServise.<init>()

I guess program cannot find a constructor for a interface, So how can I create this instance for the injection?





GO - add callback instead of using default implementation

im using the following code which works as expected.

User add to the config testers new entry which is returning a list of TAP that he needs to check and run them in parallel via http call.

There is another use-case which I need to support that the user will be providing also a function/method/callback which the function will implement the call via http/curl/websocket/whatever and the function will return response whether it's 200/400/500.

For example let say that user implement two functions/callback in addition the list of taps and the program will execute the functions the same as the list of testers and those functions will call to other sites like: "http://www.yahoo.com" and https://www.bing.com with curl or http (just to demonstrate the difference) .

How can I do it in a clean way?

package main

import (
    "fmt"
    "net/http"
    "time"
)

type HT interface {
    Name() string
    Check() (*testerResponse, error)
}

type testerResponse struct {
    err  error
    name string
    res  http.Response
    url  string
}

type Tap struct {
    url     string
    name    string
    timeout time.Duration
    client  *http.Client
}

func NewTap(name, url string, timeout time.Duration) *Tap {
    return &Tap{
        url:    url,
        name:   name,
        client: &http.Client{Timeout: timeout},
    }
}

func (p *Tap) Check() testerResponse {
    fmt.Printf("Fetching %s %s \n", p.name, p.url)
    // theres really no need for NewTap
    nt := NewTap(p.name, p.url, p.timeout)
    res, err := nt.client.Get(p.url)
    if err != nil {
        return testerResponse{err: err}
    }

    // need to close body
    res.Body.Close()
    return testerResponse{name: p.name, res: *res, url: p.url}
}

func (p *Tap) Name() string {
    return p.name
}

// makeJobs fills up our jobs channel
func makeJobs(jobs chan<- Tap, taps []Tap) {
    for _, t := range taps {
        jobs <- t
    }
}

// getResults takes a job from our jobs channel, gets the result, and
// places it on the results channel
func getResults(tr <-chan testerResponse, taps []Tap) {
    for range taps {
        r := <-tr
        status := fmt.Sprintf("'%s' to '%s' was fetched with status '%d'\n", r.name, r.url, r.res.StatusCode)
        if r.err != nil {
            status = fmt.Sprintf(r.err.Error())
        }
        fmt.Printf(status)
    }
}

// worker defines our worker func. as long as there is a job in the
// "queue" we continue to pick up  the "next" job
func worker(jobs <-chan Tap, results chan<- testerResponse) {
    for n := range jobs {
        results <- n.Check()
    }
}

var (
    testers = []Tap{
        {
            name:    "1",
            url:     "http://google.com",
            timeout: time.Second * 20,
        },
        {
            name:    "3",
            url:     "http://stackoverflow.com",
            timeout: time.Second * 20,
        },
    }
)

func main() {
    // Make buffered channels
    buffer := len(testers)
    jobsPipe := make(chan Tap, buffer)               // Jobs will be of type `Tap`
    resultsPipe := make(chan testerResponse, buffer) // Results will be of type `testerResponse`

    // Create worker pool
    // Max workers default is 5
    maxWorkers := 5
    for i := 0; i < maxWorkers; i++ {
        go worker(jobsPipe, resultsPipe)
    }

    makeJobs(jobsPipe, testers)
    getResults(resultsPipe, testers)
}




mardi 29 septembre 2020

Loading a .NET assembly from a byte array

I'm getting this error when I try to load a program in memory

error:

GAC    Version        Location
---    -------        --------
False  v2.0.50727

here my code:

$Path = "D:\calc.exe"
$bytes = [System.IO.File]::ReadAllBytes($Path)

$string = [System.Convert]::ToBase64String($bytes)

$bytees = [System.Convert]::FromBase64String($string)
[System.Reflection.Assembly]::Load($bytees)




Reflection Method invoke cache

I am attempting to use reflection Method.invoke() to execute a method based on user inputted text that specifies the Class, Method and parameters to execute. Something like this:

  public Object invokeInput(String className, String methodName, List<Object> list) {
        try {
            Class<?> cls = Class.forName(className);
            Method method = cls.getMethod(methodName, list.get(0).getClass());
            return method.invoke(null, list.get(0));
        } catch (Exception e) {
            System.out.println(e);
        }
        return false;
    }

Everything works as intended for the first execution of the method, but then the results of the first invoke() seem to be saved/cached and returned for all subsequent calls to the same method when supplied method parameter Object (first Object in "list") has the same reference, even though the internal fields of that parameter Object have changed and should result in a different method return.

Anyway to avoid this? or clear the cache somehow?

Any help is greatly appreciated.





PropertyDescriptor.SetValue Exception call stack

I have some code that uses a PropertyDescriptor to set a value. The problem is that when it fails, the exception does not contain information or a callstack that includes the executed code that threw the exception? In this case SetNameInternal(). The exception only has information up to the point SetValue was invoked. There is no inner exception. Is there any way to get this information so it can be logged? (such as when running the application outside of a debugger)

The following code demonstrates the issue. The string returned by Exception.ToString() only contains :

System.Exception: Ah! at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component, Object value) at ConsoleApp54.Program.Main(String[] args) ... ConsoleApp54.exe' has exited with code 0 (0x0).

Yet the problem is in SetNameInternal(). Of course in this simple example, it's obvious what is wrong, but a real world case will have a lot more going on, so the callstack is useful.

    public class Test
{
    public string Name
    {
        get { return m_name; }
        set
        {
            m_name = value;
            SetNameInternal();
        }
    }

    void SetNameInternal()
    {
        throw new Exception("Ah!");
    }

    private string m_name;
}

class Program
{
    static void Main(string[] args)
    {
        var t = new Test();
        try
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(t);
            var desc = properties.Find("Name", false);
            desc.SetValue(t, "Fail");
            //but this would return different StackTrace
            //t.Name = "Fail";
        }
        catch (Exception e)
        {
            Debug.Write(e.ToString());
        }
    }
}

fiddle





Java annotation cannot be found per reflection on a Kotlin data class

Given this Java annotation

@Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface JsonProperty

and this Kotlin data class

@JsonIgnoreProperties(ignoreUnknown = true)
data class LossDocument(@JsonProperty("id") val id: String)

I would expect to find the annotation either here

LossDocument::class.java.declaredFields[0].annotations

or here

LossDocument::class.java.declaredMethods.first { it.name == "getId" }

but both have zero annotations. Is this a bug? Per 53843771, my impression is this should work. I'm using Kotlin 1.4.0.





Why do I get a WrongMethodTypeException on invokeExact even though MethodHandle is OK

I am trying to call an invoke method and there is an error that I cannot explain. I have heard that the Invoke Exact method has to return but it did not work even then.

public void exec(String id, ChannelHandlerContext ctx, ByteBuf byteBuf) {
    assert ctx != null;
    assert byteBuf != null;
    try {
        MethodHandle methodHandle = this.methods.get(id);

        Boolean b = (Boolean) methodHandle.invokeExact(ctx, byteBuf);

        //            this.methods.get(id).invoke(massageExchanger, ctx, byteBuf);

        //            this.methods.get(id).invokeWithArguments(ctx, byteBuf);
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
}

on this code the Programm crash

Boolean b = (Boolean) methodHandle.invokeExact(ctx, byteBuf);

java.lang.invoke.WrongMethodTypeException: expected (,ChannelHandlerContext,ByteBuf)Boolean but found (ChannelHandlerContext,ByteBuf)Boolean
    at java.base/java.lang.invoke.Invokers.newWrongMethodTypeException(Invokers.java:476)
    at java.base/java.lang.invoke.Invokers.checkExactType(Invokers.java:485)
    at de.moldiy.spaceexplorer.MessageExchangerManager.exec(MessageExchangerManager.java:51)
    at de.moldiy.spaceexplorer.MessageHandler.channelRead0(MessageHandler.java:19)
    at de.moldiy.spaceexplorer.MessageHandler.channelRead0(MessageHandler.java:8)
    at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:99)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
    at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:324)
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:296)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357)
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:163)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:714)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:650)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:576)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:493)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.base/java.lang.Thread.run(Thread.java:835)

This is the class that contains the method I want to call

s.loadMessageExchanger(new ServerMessageExchanger() {
    @TrafficID(id = "cords")
    public Boolean setCords(ChannelHandlerContext ctx,ByteBuf byteBuf) {
       System.out.println("jaaa");
       return true;
    }
});




lundi 28 septembre 2020

dynamically parse json in flink map

I'm using flink to dynamically analyze json type data,to keyby and sum with the given column,in my mapFunction,I convert json to case class,but the result stream don't get compiler in keyBy function,got error Exception in thread "main" org.apache.flink.api.common.InvalidProgramException: This type (GenericType<java.lang.Object>) cannot be used as key..my code like this

//conf.properties
columns=a:String,b:Int,c:String,d:Long
declusteringColumns=a,c
statsColumns=b
//main function
stream.map(new MapFunc)
      .keyBy(declusteringColumns(0), declusteringColumns.drop(0).toSeq: _*)
      .sum(statsColumns)
class MapFunc extends RichMapFunction[String,Any]{
var clazz:Class[_]=_
override def open(parameters: Configuration): Unit = {
import scala.reflect.runtime.universe
import scala.tools.reflect.ToolBox
val tb = universe.runtimeMirror(universe.getClass.getClassLoader).mkToolBox() 
clazz = tb.compile(tb.parse(
"""|case class Test(a:String,b:Int,c:String,d:Long){}
   |scala.reflect.classTag[Test].runtimeClass"""
.stripMargin)).apply.asInstanceOf[Class[_]] 
}

override def map(value: String) {
val tmp = JSON.parseObject(value)
val values = Utils.loadProperties("columns").split(",").map(y => {
val name = y.substring(0, y.indexOf(":"))
val tpe = y.substring(y.indexOf(":") + 1)
tpe.toLowerCase match {
case "string" => tmp.getString(name)
case "int" => tmp.getInteger(name)
case "long" => tmp.getLong(name)
case _ => null}}).toSeq
clazz.getConstructors()(0).newInstance(values: _*) 
}}

how can I convert json to case class or tuple?





How to find a class instance name in other class in swift?

Imagine a situation that we have two classes like these:

class MyClass {
    func printInstanceName() {
        print(what?);
    }
}

class User {
    var myObject: MyClass!
}

I will instantiate an object of class User like this:

let user = User();

and call printInstanceName on user like this:

user.myObject.printInstanceName();

How should i implement the printInstanceName that print the name of the MyClass instance in User? (myObject)





How to convert JSON to scala shapeless.hlist?

I got json like {"name":"susan","age":25},and a hint to json keyset like "name:String,age:Int",how to create a HList from that json?





Servlet reflection throw targetinvocation error at init

I am using Netbeans and upgraded to JDK 15. Since then, I am having problems with reflection. The very same reflection works fine if I do the same code as application. However, if I want to use the same code in servlet init then it failes. Throwing an exception of TargetInvocation exception.

(These codes works perfectly fine with JDK 8)

My code is below (servlet init)

package servlet;

import java.io.IOException;
import java.lang.reflect.Constructor;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Administrator
 */
public class core extends HttpServlet
{
    @Override
    public void init() throws ServletException
    {
        Object id = null;
        try
        {
            Class<?> MyPackageClass = Class.forName("webapi.UI");
            boolean rc = MyPackageClass.isAssignableFrom(MyPackageClass);
            
            Constructor<?> constructor = MyPackageClass.getDeclaredConstructor();
            Object MyClassInstance = constructor.newInstance();
            
            String s = "";
        }
        catch(Exception e)
        {

            Throwable cause = e.getCause();
            String s1 = cause.getMessage();
            String s2 = backTrace(cause);
            String s = "";
        }
    }

    public String backTrace(Throwable e) 
    {
        StackTraceElement[] stack = e.getStackTrace();
        String trace = "";
        for (int i=0; i<stack.length; ++i) {
            trace += stack[i].toString() + "\n";
        }
        return trace;
    }

The exception stack trace

s2 = (java.lang.String) "webapi.UI.<init>(UI.java:1)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:64)
java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
servlet.core.init(core.java:31)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1134)
org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1089)
org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:983)
org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4864)
org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5173)
org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:717)
org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:690)
org.apache.catalina.core.StandardHost.addChild(StandardHost.java:706)
org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:631)
org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:487)
org.apache.catalina.startup.HostConfig.check(HostConfig.java:1642)
jdk.internal.reflect.GeneratedMethodAccessor45.invoke(Unknown Sourc...

Exception Details

e = (java.lang.reflect.InvocationTargetException) java.lang.reflect.InvocationTargetException
Cannot suppress a null exception

And the class I am trying to create the instance of

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package webapi;

/**
 *
 * @author Administrator
 */
public class UI 
{
    public int x = 0;
    
    public UI()
    {
    
    }
    
    public String test()
    {
        return "oops";
    }
    
}





Xamarin Forms Using Reflexion to get Property of Bindable Property

What i want is, when the value is changed, it should call CreateChart()and use the new values. I try to call in an onPropertyChange method OnValueChanged a bindable Property with reflection, but the property is always null and i dont get the value of the property Value

public partial class CorrectWrongRingChart : ContentView
    {
        public CorrectWrongRingChart()
        {
            InitializeComponent();
            
            
        }
        
        public static readonly BindableProperty ChartProperty =
            BindableProperty.Create(
                nameof(CorrectWrongChart),
                typeof(Chart),
                typeof(CorrectWrongRingChart));

        public Chart CorrectWrongChart
        {
            get { return (Chart)GetValue(ChartProperty); }
            set => SetValue(ChartProperty, value);
        }

        public static readonly BindableProperty ValueProperty =
          BindableProperty.Create(
              nameof(Value),
              typeof(CorrectWrongValue),
              typeof(CorrectWrongRingChart),
              propertyChanged: OnValueChanged);/*(b, o, n) => { ((CorrectWrongRingChart)b).OnPropertyChanged("Text");});*/

        public  CorrectWrongValue Value
        {
            get { return (CorrectWrongValue)GetValue(ValueProperty); }
            set => SetValue(ValueProperty, value);
        }

        private static void OnValueChanged(BindableObject bindable, object oldValue, object newValue)
        {
             ((CorrectWrongRingChart)bindable).OnPropertyChanged("Text");            
             //((CorrectWrongRingChart)bindable).OnPropertyChanged("Correct"); 
             //((CorrectWrongRingChart)bindable).OnPropertyChanged("Wrong");
            var valueProperty = ValueProperty.GetType().GetProperty("Value");
            var value = (CorrectWrongValue)valueProperty.GetValue("Value");
            var ChartProperty = ValueProperty.GetType().GetProperty("CorrectWrongChart");
            
            if (value != null)
            {

                ChartProperty.SetValue("CorrectWrongChart", CreateChart(value));
                
            }
            
            

        }

        public static readonly BindableProperty TextProperty =
            BindableProperty.Create(
                nameof(Text),
                typeof(string),
                typeof(CorrectWrongRingChart),
                defaultValue: string.Empty);

        public string Text => $"{Value?.CorrectCount ?? 0}/{Value?.TotalCount ?? 0}";
        //public double Correct => Value.CorrectPercentage;
        //public  double Wrong => Value.WrongPercentage;


        private static Chart CreateChart(CorrectWrongValue value)
        {
            var chart = new Microcharts.DonutChart();
            chart.IsAnimated = false;
            
            ChartEntry corretEntry = new ChartEntry((float)value.CorrectPercentage)
            {
                Color = SKColor.Parse("#00FF00")
            };
            ChartEntry wrongEntry = new ChartEntry((float)value.WrongPercentage)
            {
                Color = SKColor.Parse("#FF0000")
            };
            chart.Entries = new List<ChartEntry>() { corretEntry, wrongEntry };
            return chart;
        }
    }

Xaml:

<Grid >
            <forms:ChartView x:Name="chart1" WidthRequest="130" HeightRequest="130" Chart="{Binding CorrectWrongChart, Source={x:Reference Root}}">
               
</forms:ChartView>
            <Label Text="{ Binding Text, Source={x:Reference Root} }"                  
                   VerticalOptions="Center"
                   HorizontalOptions="Fill"
                   HorizontalTextAlignment="Center"
                   TextColor="Black"
                   FontSize="19"
                   FontFamily="{ StaticResource AppBoldFontFamily }" />
        </Grid>




dimanche 27 septembre 2020

Kotlin pass KType as generic parameter

I have a situation where I want to call a function to produce an object of a type for which I have just a KType description of.

Basically I have:

fun<T> coolFunction(from : String) : T = // Okay, I'll be honest - its a JSON parser
...
fun myOtherFunction(foo : KCallable<MyReturnType>) : MyReturnType {
    val args = mutableMapOf<KParameter, Any?>()
    ...
    for (parameter in foo.parameters) {
        ...
        val argValue = coolFunction<parameter.type>(someStringIhave)
        args[parameter.name] = argValue
    }
    ...
    return foo.callBy(args)
}

The issue is of course that the coolFunction<parameter.type>(someStringIhave) isn't correct syntax. I don't know how to get the right syntax though, I assume I'll have to use some more reflective API, but I can't seem to figure out how.





Golang check type a variable

I'm making a call to os/Create function and want to make sure in one of my test cases that the response is indeed of type *os.File.

Below is my code snippet. Though I made a lot of iterations but the motivation for these lines was this post.

//somevar -- gets *os.File from a function
var varType *os.File
tpe := reflect.TypeOf(varType).Elem()
fmt.Println(reflect.TypeOf(somevar).Implements(tpe)) // I expect a true or false

When I run this code I get a panic:

panic: reflect: non-interface type passed to Type.Implements [recovered]
    panic: reflect: non-interface type passed to Type.Implements

Please suggest what wrong I'm doing. All I want to check for is - some variable is of type *os.File - yes or no.

Thank you





How to prevent method invoking when Attribute return false? [duplicate]

I have a software that requires a license key validation on some methods. It a little bit uncomfortable to write a general wrapper for this purpose, so I want to write something like this:

    [EnsureThat(LicenseKeyAdded = true)]
    public static void SomeSeriousMethod()
    {
       // My very confidential code
    }

LicenseKeyAdded is a property inside the class, that was set somewhere outside. And the main idea is not to execute this method when the attribute's result is false (display alert message instead)





samedi 26 septembre 2020

Unable to fetch classes of a package using Reflection

enter image description here

From the above image, when i am trying to fetch all classes under "tests", i am getting empty array.

    Reflections reflections = new Reflections("tests");
    //Reflections reflections = new Reflections("src.test.java.tests"); Tried but still empty array

     Set<Class<? extends Object>> allClasses =  reflections.getSubTypesOf(Object.class); //Getting empty array here
     Class[] arrayCls=new Class[allClasses.size()];
     allClasses.toArray(arrayCls);

Can someone please help me how to get array of classes?





Why reflection let some compiler optimzation works well?

I know reflection can make java performance behave worse. And I have just known it can also make some compiler optimization doesn't work well. Is there some reason?





vendredi 25 septembre 2020

JsonProperty cannot be read after Custom annotation is used

I have a function which constructs a list of serializable fields per Model class at start up. It does so by searching for @APIField annotation for all the fields in a class and makes a Set<String> of field names. Then it is stored in Map<Class, Set<String >>, creating a static list of class along with it's white listed fields.

Later when I serialize using a custom @JsonFilter, I check if the writer.getName() is a contained in the set of field names and let the writer do the serialization. (it's in the code snippet below)

All this works fine until a @JsonProperty("sname") is used along with @APIField. The serialization happens with field name and not the json property name.

Here is the scenario:

    Class ShowClass {

        @APIField
        @Getter @Setter
        private String firstName;

        @APIField
        @Getter @Setter
        @JsonProperty("ln")
        private String lastname;
   }

Then, JsonFieldsListGenerator function generates Map<Class, Set<String>>, basically for each class, a set of field names that will be serialized. whiteListedFieldsMap in the code snippet is the global variable where I store the whiteListFields.

    Set<String> whiteListFields = new HashSet<>();
    Arrays.stream(clazz.getDeclaredFields()).forEach(field -> {
        if(field.isAnnotationPresent(APIField.class))
        {
            whiteListFields.add(field.getName());
        }
    });
    whiteListedFieldsMap.put(clazz, whiteListFields);

Then My serialization is happening in an overridden serializeAsField method

@Override
public void serializeAsField(Object pojo, JsonGenerator jgen,
        SerializerProvider provider, PropertyWriter writer)
        throws Exception
{
    Set<String> whiteListedFields = getWhiteListedFields(pojo.getClass());

    if(whiteListedFields.contains(writer.getName()))
    {
        writer.serializeAsField(pojo, jgen, provider);
    }

}

The problem is that writer.getName() gives me "ln" for lastName, whereas whiteListedFields contains "lastName".

Expected : {"firstName": "Mike", "ln" : "Gerard"}
Actual   : {"firstName": "Mike", "lastName": "Gerard"}

So, How do I make all the other annotations work properly with my @APIField while maintaining the program flow ?

Yes, one way is to actually save the whitelisted fields with their JsonProperty name. The problem is that if @JsonProperty isn't working, then there are other things that might not be working. So without any duct taping, how do I make sure that all the annotations other than @APIField continue to work (e.g. @JsonValue, @JsonProperty and anything else) ?





How can I find Annotated methods in Scala/Java on Runtime

I want to use Runtime Reflection with Scala annotations (could also be a Java annoations if necessary, but I would prefer to limit pure Java code)

I want to implement something like:

/**
  print all methods that implement a specific annotation
*/
 def getAllAnnotated(): Unit {...}

For example, if I have:

class Foo {
    @printme
    def foo(args: A): R
    
    def oof(args: A): R
}
class Bar {
    @printme
    def bar(): Unit
}

The result of running getAllAnnotated() would be something like:

Foo.foo
Bar.bar

Note that I don't want to look in a specific class, but instead any available method





Create a type trait that can be called both on types and on variables

There are two operators in C++ that can be called both on types and on variables: sizeof and typeid.

Suppose we want to implement our own operation with a similar behavior, something like*:

template<bool is_type>
struct type_traits_T;

template<>
struct type_traits_T<true> {
    template<typename T>
    struct type_traits {
        using mydecltype = T;
        // and other stuff...
    };
};

template<>
struct type_traits_T<false> {
    template<auto VAR>
    struct type_traits {
        using mydecltype = decltype(VAR);
        // and other stuff...
    };
};

This could have worked quite nicely, with a macro:

#define type_traits(V) type_traits_T<is_type(V)>::type_traits<V>

The missing part for the above is the is_type(V) part.

Is there a way to implement is_type(V) that would result with true in case V is a type, and false if V is a variable? If not, would there be a way to achieve that with the static reflection proposal?


* The use of a template to capture the variable has its own restrictions. It may be refactored by moving the call to decltype into the macro. However the question doesn't focus on the template part, which is here just for the purpose of having a simple and viable use case.





Dynamically reload JAR in tomcat

I have Jersey service runs in tomcat. I try to reload my JAR content when it has a new version. My service has instance manager type of IManager, its implementation is loaded through reflection.

private IManager manager; 

From different forums and questions here in stackoverflow, I understand that for reloading classes in JVM I have to implement my Classloader, due to default ClassLoaders assume that the class definition will not change through the life of the JVM and don't read its new version from disk.

So, I implemented my ClassLoader, but the problem in the next code:

private IManager manager;

public void loadManager() {
    MyWebAppLoader loader = new MyWebAppLoader(classesPathNorm, libPathNorm);
            
    Class<?> managerClass = loader.loadClass("mycompany.Manager");
    
    //EXCEPTION HERE: mycompany.Manager cannot be cast to mycompany.IManager
    manager = (IManager) managerClass.newInstance();

}
    

I know that the problem is IManager and Manager have different ClassLoaders (CatalinaClassLoader VS MyWebAppLoader). If I understand, I have 2 options:

  1. Use <Context reloadable="true">, BUT it isn't not recommended for use on deployed production applications + in this case I haven't a control on loaded JAR if it's corrupted, for example.

  2. Override classloader of Tomcat. I'm not sure that it's the safest way to solve my problem

So, my question, what is the best and the safest way to solve my problem? Am I right about two options that I have?





jeudi 24 septembre 2020

Assemblie.load.getType doesn't work for types with?

I have a huge like 110000+ line codefile that I'm reading out for some specific types to get information about them. I get those types from a .json file.

The reading out part is done via reflection (the assemblie is in a other solution):

First I load the files into the memory:

public static List<Assembly> LoadAssemblies(List<string> loadedPaths)
    {
        foreach (string loadPath in loadedPaths)
        {
            List<AssemblyName> referencedAssemblyNames = Assembly.LoadFrom(loadPath)
                                     .GetReferencedAssemblies()
                                     .Where(a => a.FullName.StartsWith(Constants.NameSpace))
                                     .ToList();
        }
        return AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.StartsWith(Constants.NameSpace)).ToList();
    }

After that I read out the specific Types and its customattributes that I want information about:

  public static Dictionary<string, string> GetCustomAttributes(List<Type> streamDesign, List<Type> enums)
    {
        List<PropertyInfo> propertyInfos = new List<PropertyInfo>();
        streamDesign.ForEach(sd => propertyInfos.AddRange(sd.GetProperties().ToList()));

        Dictionary<string, string> dbUsageMapping = new Dictionary<string, string>();

        foreach (Type t in enums)
        {

            var property = propertyInfos
                .Where(p => p.PropertyType.FullName != null ? p.PropertyType.FullName.Equals(t.ToString(),
                                        StringComparison.CurrentCultureIgnoreCase) : false)
                .ToList();

            foreach (PropertyInfo p in property)
            {
                var tmp = p.GetCustomAttributes()
                                .Where(a => a is ColumnAttribute)
                                .FirstOrDefault() as ColumnAttribute;
                if (tmp != null)
                {
                    dbUsageMapping.Add(t.ToString(), tmp.Name);
                    break;
                }
            }

        }
        return dbUsageMapping;
    }

The types I get with this one:

  public static List<Type> GetStreamDesignTypes(string loadedPath)
        {
            return AppDomain.CurrentDomain.GetAssemblies().Where(a => a.Location.Equals(loadedPath)).FirstOrDefault().GetTypes().ToList();
        }

It works fine for types without "?", but types like this -->

public global::JobTemplateType? TemplateType {}

aren't in there.

Do I have to do something specific to get those types? And if I search for types with "?", it returns null;

Any ideas?

Edit: As requested, original types -->

public enum JobTemplateType
    {
        /// <summary>
        /// Constant to represent None.
        /// </summary>
        None = 0,

        /// <summary>
        /// Constant to represent a normal job.
        /// </summary>
        Normal = 1,
...
    }

The original types are Enums and I want to match the Enums with the CustomAttributes "name" (if exists) to get the occurences in the database. (for documentation purposes)





Trying to change an item in a private List with reflection

I am wanting to edit an item in a private List from a different class (I can't change it to public). I am trying to use a dynamic to let me modify the 6th item in the list, but I just get errors about having the wrong type though "Failure has occurred while loading a type." I am new to Reflection but it is the only option I can use to try to access the private list.

Here is my code:

dynamic privateList = typeof(Class2).GetField("PrivateList", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(class2);
privateList[5] = new ListObj(2f, 2.5f, ListObj.ListObject6);

Thanks in advance!





Generic string to enum extension method with default value

I'm still at my early beginning in C# and I'm trying to implement Enum/converter converters.

All my enums has a NotDefined value equals to -1.

I would like to implement a generic extension method to get an enum from a string base on the the enum description (which mostly differ in spaces and cases).

public static T ToEnum<T>(this string value) where T : struct 
{
    foreach (T e in Enum.GetValues(typeof(T)))
    {
        if (e.GetDescription() ==value)
        {
            return e;
        }
    }
    
    // Doesn't work..
    // How can I return T.NotDefined? - I don't really want to throw something here
    return (T)-1; 
}

PS I initially found the GetDescription() implementation thanks to this thread : Enum ToString with user friendly strings which helps me a lot :-) .

Does anyone have an insight about my issue?

Many thanks!





Using reflection throws error in EF Core 3

We formerly used reflection to create linq queries, e.g. for the GetById method:

private IQueryable<T> GetQueryById(TKey id)
{
    var query = _dbset; //DbSet<T>

    var keyNames = _context.Model
            .FindRuntimeEntityType(typeof(T))
            .FindPrimaryKey()
            .Properties
            .Select(x => x.Name)
            .ToList();

    if (keyNames.Count() == 1)
    {
        query = query.Where(e => e.GetType().GetProperty(keyNames[0]).GetValue(e, null)
           .Equals(id)); //throws error
    }
        
    return query;
}

This does not seem to work any more in EF Core 3:

The LINQ expression 'DbSet .Where(c => c.GetType().GetProperty(__get_Item_0).GetValue( obj: c, index: null).Equals((object)__id_1))' could not be translated.

Is it possible to rewrite the query so that EF Core does not complain?





Load Dataset from Dynamically generated Case Class

What is Needed:

number of tables in source database are changing rapidly and thus I don't want to edit case classes so I dynamically generate them through SCALA code and put in package. But now not able to read it dynamically. If this works than I would parse "com.example.datasources.fileSystemSource.schema.{}" as object schema members in loop

What has already been Done:

I have some case classes dynamically generated from schema of database tables as below:

object schema{
case class Users(name: String,
                 favorite_color: String,
                 favorite_numbers: Array[Int])

case class UserData(registration_dttm: Timestamp,
                    id: Int,
                    first_name: String,
                    last_name: String,
                    email: String,
                    gender: String,
                    ip_address: String,
                    cc: String,
                    country: String,
                    birthdate: String,
                    salary: Double,
                    title: String,
                    comments: String)
}

Then i have used them as dynamic type to read in Load[T] function in my Loader.scala as below:

import org.apache.spark.sql.{Dataset, Encoder, SparkSession}

class Load[T <: Product: Encoder](val tableName: String,
                                       val inputPath: String,
                                       val spark: SparkSession,
                                       val saveMode: String,
                                       val outputPath: String,
                                       val metadata: Boolean)
    extends Loader[T] {

  val fileSystemSourceInstance: FileSystem[T] =
    new FileSystem[T](inputPath, spark, saveMode, tableName)

  override def Load: Dataset[T] =
    fileSystemSourceInstance.provideData(metadata, outputPath).as[T]

}

Now, by using reflect.api I am able to get TypeTag for my case classes.

def stringToTypeTag[A](name: String): TypeTag[A] = {
    val c = Class.forName(name)
    val mirror = runtimeMirror(c.getClassLoader)
    val sym = mirror.staticClass(name)
    val tpe = sym.selfType
    TypeTag(mirror, new api.TypeCreator {
      def apply[U <: api.Universe with Singleton](m: api.Mirror[U]) =

        if (m eq mirror) tpe.asInstanceOf[U # Type]
        else throw new IllegalArgumentException(s"Type tag defined in $mirror cannot be migrated to other mirrors.")
    })
  }

So if i print now my case class type tag I got:

val typetagDynamic = stringToTypeTag("com.example.datasources.fileSystemSource.schema.Users")
println(typetags)
TypeTag[com.example.datasources.fileSystemSource.schema.Users]

Problem:

Need to read these TypeTag or Dynamically generated case classes, to encode my datasets as below:

new Load[typetagDynamic](tableName,inputPath,spark,
saveMode,
outputPath + tableName,
metadata)(Encoders.product[typetagDynamic]).Load 

This is giving me error : Cannot resolve symbol typetagDynamic

if used like this:

new Load[typetagDynamic.type](tableName,inputPath,spark,
saveMode,
outputPath + tableName,
metadata)(Encoders.product[typetagDynamic.type]).Load 

This is giving me error : type arguments [T] do not conform to method product's type parameter bounds [T <: Product]





c#: How to get the value of 'this' with Reflection?

Is there a way to find out the value of the implicit this parameter which is passed into a function a few stack frames above the current code? I know this sounds weird, so let me give you the bigger picture.

I am working with a framework for test automation that lets me plug in my own code in a separate .NET assembly. My code is a public static method which eventually gets called by the framework. From the way the framework works I know that my code is indirectly called by a Run method. Run is a non-static method of a class that implements the ITestModule interface.

My code wants to access a non-static property in the instance whose Run method is executing, or in other words, a property member of the implicit this of the Run method.

The code I wrote so far uses the StackTrace class to traverse the stack and asks each stack frame whether its method has the signature which I expect. Once it find a match, the code asks the method's ReflectedType for the underlying class from which it gets a PropertyInfo for the requested property. If now I had this as well, I could go ahead and call MethodInfo.GetMethod.Invoke to retrieve the property value.

This is the code, omitting error checking etc.

StackTrace st = new StackTrace();
for (int j = 0; j < st.FrameCount; ++j)
{
  // examine each stack frame until we find what we are looking for
  StackFrame frame = st.GetFrame(j);
  MethodBase method = frame.GetMethod(); // executing method
  if (method.ToString() == "<method signature>")
  {
    // We have found the "Run" method
    Type rType = method.ReflectedType; // class of which "Run" is a member
    PropertyInfo pInfo = rType.GetProperty(property_name); // the property
    MethodInfo propGet = pInfo.GetMethod; // the property's "get" accessor

    Object instance = ...; // The "this" of the "Run" method
    Object result = propGet.Invoke(instance, null); // Retrieve the property value
    // do something with result

    break;
  }
}

It is the Object instance = ...; line that gives me headache.

Thanks a lot for any suggestions.

Hans





mercredi 23 septembre 2020

Akka Quickstart: An illegal reflective access operation has occurred

When running the official Akka Quickstart on my Mac terminal, I get this error:

Getting org.scala-sbt sbt 1.2.8 ...
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.ivy.util.url.IvyAuthenticator (file:/Users/helios/eclipse-workspace/akka-quickstart-java/sbt-dist/bin/sbt-launch.jar) to field java.net.Authenticator.theAuthenticator
WARNING: Please consider reporting this to the maintainers of org.apache.ivy.util.url.IvyAuthenticator
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
reStart
  

Is this the intended result? How can I go about fixing this?





How to verify that two classes with the same dependency call the same methods on that dependency

I have two classes that are both writing various records to BackendStore, and a ComplexObject that consists of various data records in the BackendStore. One class creates the object from scratch which involves computing and writing various records to the backend store. The other is cloning new object records from existing ones which involves reading various records, modifying them, and then writing the modified records to the backend store. In the future, if additional records are added to the definition of ComplexObject, I want to make sure that the ClonedObjectWriter is updated to clone the new record.

class NewObjectWriter {
    NewObjectWriter(BackendStore backendStore) {...}
    createComplexObject() {...}

class ClonedObjectWriter {
    ClonedObjectWriter(BackendStore backendStore) {...}
    cloneExistingObject(ComplexObject existingObject) {...}
}

I would like to enforce by adding a unit test that verifies that ClonedObjectWriter is calling all the methods on the BackendStore that NewObjectWriter is calling so that the two classes don't go out of sync. Is this possible?





Java How to access private static member of class

Hi may I know how to access private static member outside Java classes?

I want to check if a value is set correctly.





Specify certain properties of a type

I am trying to initialize objects for tests purposes. After initializing an object, I want to assert that all properties whose underlying type is a value type have a value that is not the default value of the property's type, with certain exceptions. I am not trying to recurse into sub-objects. For this purpose, I have the following:

    public static void NoValueTypedPropertyHasDefaultValue<T>(this T t, params string[] exceptions)
        where T: class
    {
        foreach (var property in typeof(T).GetProperties())
        {
            var propertyType = property.PropertyType;
            if (propertyType.IsValueType && !exceptions.Any(x => x == property.Name))
            {
                var defaultValue = Activator.CreateInstance(propertyType);
                object actualValue = property.GetValue(t);
                Assert.NotEqual(defaultValue, actualValue);
            }
        }
    }

Provided that everything has a parameterless constructor, it works. I'm not thrilled with the way I'm passing in strings for the exceptions. Is there a better way to do that?





Alternative to try-catch in a loop

I have a list of Method objects that I want to execute using user supplied parameters which I don't know the type or value until runtime.

I want to loop through the methods array and execute them using the invoke method until one of the methods executes successfully without an exception. Is this a good way to do it?

        Method[] methods = cls.getMethods();

        for (Method method : methods) {
            try {
                method.invoke(obj, param1, param2);
                break;
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }

I've been told that using try and catch for flow control is bad idea, but I'm not sure why. I'm also not sure what the alternative would be in a situation like this where I expect an exception to occur in the normal execution because the user supplies the parameters.

Any help is greatly appreciated.





How to distinguish parameteric types?

I am confused about subtypes in Scala. My major question is how to distinguish C[T1] from C[T2]. There are two scenarios:

  1. C[T1] "equals" C[T2] because they are all subtypes of C.
  2. C[T1] does not "equal" C[T2] because C[T1] and C[T2] are different types eventually.

I have tried some ways like .getClass, seems that this strategy won't work because we have primitive types.

println(List[Int](1).getClass == List[Double](1.0).getClass) // True
println(List[Int](1).getClass.getCanonicalName) // scala.collection.immutable.$colon$colon
println(Array[Int](1).getClass == Array[Double](1.0).getClass) // False
println(Array[Int](1).getClass.getCanonicalName) // int[]

I now wonder is there some way I can do this?





Instantiate an anonymous Java class using reflection

Is it possbile to instantiate an anonymous Java class using reflection. I have created an anonymous class that I would like to instantiate again later on, is there anyway of doing this? I can do it with an inner class, but I really need to do it with an anonymous one?





How do you figure out whether a CLASS is a spring proxy?

In a nutshell

In the AopUtils, we have

    /**
     * Check whether the given object is a JDK dynamic proxy or a CGLIB proxy.
     * <p>This method additionally checks if the given object is an instance
     * of {@link SpringProxy}.
     * @param object the object to check
     * @see #isJdkDynamicProxy
     * @see #isCglibProxy
     */
    public static boolean isAopProxy(@Nullable Object object) {
        return (object instanceof SpringProxy && (Proxy.isProxyClass(object.getClass()) ||
                object.getClass().getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)));
    }

In now want to check whether a bean class is proxied without instantiating the bean (i.e. just with its class) in a BeanFactoryPostProcessor.

I thought I could just "translate" above method:

    private fun <T> isAopProxyClass(candidate: Class<T>): Boolean {
        return SpringProxy::class.java.isAssignableFrom(candidate)
            && (
            Proxy.isProxyClass(candidate)
                || candidate.name.contains(CGLIB_CLASS_SEPARATOR)
            )
    }

But this does not detect proxies because SpringProxy::class.java.isAssignableFrom(candidate) is false even for obviously proxied classes.

How do I make this work?

Full picture

I'm in a BeanFactoryPostProcessor and I need the un-proxied bean classes to access certain annotated methods by reflection.

Access happens in a lambda function that will first use the ApplicationContext to retrieve the bean for the class. The bean must not be forcibly instantiated in this BeanFactoryPostProcessor (and in fact should throw an exception if it does because some beans are session-scoped).

screenshot of misbehaving code





Calling set on VarHandle in java 14 causes UnsatisfiedLinkError

I'm invoking the set method via reflection on the VarHandle instance

set.invoke(varHandle, arrayOf(field, field.modifiers and Modifier.FINAL.inv()))

However I'm getting UnsatisfiedLinkError everytime and I wasn't able to find anything related to my situation.

Caused by: java.lang.UnsatisfiedLinkError: 'void java.lang.invoke.VarHandle.set(java.lang.Object[])'

The field VarHandle points to is the modifiers field of Field class





mardi 22 septembre 2020

How to get all string values from action arguments in Web API C# method

 public override void OnActionExecuting(HttpActionContext actionContext)
 {

     Dictionary<string, object> list = actionContext.ActionArguments;

     for (int index = 0; index < list.Count; index++)
     {
       // need to all variables if the data type is string only 

       // input parameter might be list or model or int or string

       list.ElementAt(index).Value;

     }
 }




C# reflection get all subclasses of certain class and call generic method with their type

I have packets :

public class HelloPacket
{
    public string MyName { get; set; }
}

public class PingPacket
{
    public float PingTime { get; set; }
}

I have a generic abstract 'handler' class like this :

public abstract class PacketHandler<T>
{
    public abstract void Handle(T t);
}

And their implementations :

public class HelloPacketHandler : PacketHandler<HelloPacket>
{
    public override void Handle(HelloPacket helloPacket)
    {
        Console.WriteLine("Received Hello packet!");
    }
}

public class PingPacketHandler : PacketHandler<PingPacket>
{
    public override void Handle(PingPacket pingPacket)
    {
        Console.WriteLine("Pong!");
    }
}

I need to register them like this :

        NetPacketProcessor _netPacketProcessor = new NetPacketProcessor();

        HelloPacketHandler helloHandler = new HelloPacketHandler();
        PingPacketHandler pingHandler = new PingPacketHandler();

        _netPacketProcessor.SubscribeReusable<HelloPacket>((packet) => { helloHandler.Handle(packet); });
        _netPacketProcessor.SubscribeReusable<PingPacket>((packet) => { pingHandler.Handle(packet); });

Here is the SubscribeReusable method :

public void SubscribeReusable<T>(Action<T> onReceive) where T : class, new()
{
}

The problem is that, as the solution grows, I will have to keep adding these calls.

I'm wondering if I could use reflection to dynamically call 'SubscribeReusable'. The problem I'm facing is with the generics.

Here is the code I started with :

        foreach (Type i in typeof(PacketHandler).Assembly.GetTypes())
        {
            if (typeof(PacketHandler).IsAssignableFrom(i) && !i.IsAbstract && !i.IsInterface)
            {
                // Subscribe here
            }
        }

Where I'm stuck

I tried Type and dynamic, but it is still not working. I'm wondering if I even have the right approach.

 foreach (dynamic i in typeof(PacketHandler<dynamic>).Assembly.GetTypes())
            {
                if (typeof(PacketHandler<dynamic>).IsAssignableFrom(i) &&
                    !i.IsAbstract && !i.IsInterface)
                {
                    PacketHandler<dynamic> pkt = (PacketHandler<dynamic>) Activator.CreateInstance(i);

                    Type t = pkt.GetType();

                    MethodInfo method = typeof(NetPacketProcessor).GetMethod(nameof(NetPacketProcessor.SubscribeReusable));
                    MethodInfo generic = method.MakeGenericMethod(t);
                    generic.Invoke(this, new object[]
                    {
                        pkt.Handle()
                    });
                }
            }

Error





What is meant by Inspecting classes

Im going through Reflection in java and its main purpose is to inspect classes at RunTime.

May I know what does inspecting classes mean ?





Getting ReflectionFunction::__construct() expect string in PHP 7.2

When executing the following code in PHP v7.2,

<?php

class A { function a() {} }
$a = new A;
$rf = new \ReflectionFunction([ $a, 'a' ]);

I got an error

ReflectionFunction::__construct() expects parameter 1 to be string, array given in php shell code

Which is very strange. I passed a closure array which is valid parameter in PHP v5.3+ according to the doc.

# php -v
PHP 7.2.24-0ubuntu0.18.04.6 (cli) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.24-0ubuntu0.18.04.6, Copyright (c) 1999-2018, by Zend Technologies

I execute the code inside a Ubuntu 18.04 container that install PHP package from PPA ondrej/php. In other machine, this works. But in my case, it isn't.

Is there any PHP setting that control this behavior? Or is there any underlying PHP mechanism that may cause the error?





writing an (very) generic equality comparer

I have a data stucture that is straightforward serializable (e.g. to XML, to JSON): There is a main class C1 and several other classes C2, C3, ..., Cn. All classes Ci have public properties which are either

  • primitive types or string
  • IEnumerable<T> where T is either primitive type or string or any of the classes Cj (where j != i)
  • Cj (where j != i)

I want to define a generic equality comparer ValueEqualityComparer<T> which compares any of the classes Ci value-wise, i.e. in the following canonical way:

  • if type T is primitive, use Equals (or ==)
  • if type T is IEnumerable<S>, use Enumerable.SequenceEqual on the S objects with a ValueEqualityComparer<S> as third argument
  • else, for each public property P use ValueEqualityComparer<P>.Equals and connect these results via &&.

I already learned that pattern matching like above is not possible directly, so I need reflection. But I am struggling with how to do that.

Here is what I have written so far:

public class ValueEqualityComparer<T> : IEqualityComparer<T>
{
    public static readonly ValueEqualityComparer<T> Get = new ValueEqualityComparer<T>();
    private static readonly Type _type;
    private static readonly bool _isPrimitiveOrString;
    private static readonly Type _enumerableElementType;
    private static bool _isEnumerable => _enumerableElementType != null;

    static ValueEqualityComparer()
    {
        _type = typeof(T);
        _isPrimitiveOrString = IsPrimitiveOrString(_type);
        _enumerableElementType = GetEnumerableElementTypeOrNull(_type);
    }

    private ValueEqualityComparer() {}

    public bool Equals(T x, T y)
    {
        if (_isPrimitive)
            return Equals(x, y);

        if (_isEnumerable)
        {
            var comparerType = typeof(ValueEqualityComparer<>).MakeGenericType(new Type[] { _enumerableElementType });
            var elementComparer = comparerType.GetMethod("Get").Invoke(null, null);

            // not sure about this line:
            var result = Expression.Call(typeof(Enumerable), "SequenceEqual", new Type[] { _enumerableElementType },
                new Expression[] { Expression.Constant(x), Expression.Constant(y), Expression.Constant(elementComparer) });
        }

        // TODO: iterate public properties, use corresponding ValueEqualityComparers
    }


    private static bool IsPrimitiveOrString(Type t) => t.IsPrimitive || t == typeof(string);

    // if we have e.g. IEnumerable<string>, it will return string
    private static Type GetEnumerableElementTypeOrNull(Type t)
    {
        Type enumerableType = t.GetInterfaces().Where(i => i.IsGenericType
            && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)).FirstOrDefault();
        return enumerableType?.GetGenericArguments().Single();
    }
}

Questions regarding the // not sure about this line: line:

  • The goal is to call Enumerable.SequenceEqual<S>(x, y, ValueEqualityComparer<S>.Get()) where S is the element type of x and y (i.e. T is IEnumerable<S>). Is the line I wrote correct for that purpose?
  • How do I get the result (i.e. true or false) of that call?

Please don't fill in the // TODO section; I want to figure out as much as I can for myself.





Is there some way in scala that I can return a type?

I have a lot of classes such as DataFrameFlow, TextFlow, RDDFlow. They all derive from base class Flow.

Now I want to write a function judgeFlow which can read from a path: String and return something representing exact Flow type from which I can create corresponding instance. The whole code seems like the following

def judgeFlow(path:String) = /*1*/ {
  Flow.getStoreType(path) match {
    case StoreType.tdw =>
      DataFrameFlow
    case StoreType.hdfs =>
      TextFlow
  }
}

def createFlow(typeInfo:/*2*/) = /*3*/{
  new typeInfo()
}

However, I don't know how to write in place 1, 2 and 3.

EDIT

Knowing how to construct them is not enough here, because I also want the following:

  1. pattern matching through typeInfo
  2. some ways to do asInstanceOf

EDIT 2

Definition of Flow

abstract class Flow(var outputName: String) extends Serializable{
  def this() = this("")
...
}

Definition of DataFrameFlow

class DataFrameFlow(d: DataFrame, path: String) extends Flow {
  var data: DataFrame = d

  def this(data: DataFrame) = this(data, "")
  def this(path: String) = this(null, path)
  def this() = this(null, "")
...
}




lundi 21 septembre 2020

Why is Assembly.GetExecutingAssembly() returning different result inside a NuGet package?

I'm new to creating NuGet packages and I ran the following code snippet in various environments:

        /// <summary>
        /// Tries to find type by name in the executing assembly and after that
        /// in referenced assemblies.
        /// </summary>
        /// <param name="typeName">Name of the type to find (can be full or assembly qualified name as well).</param>
        /// <returns>Type found using the given name (or null if not found).</returns>
        public static Type FindType(string typeName)
        {
            if (typeName == null) throw new ArgumentNullException(nameof(typeName));

            // Helper method for finding the type in an assembly
            Type Finder(Assembly ass) => ass?.GetTypes().FirstOrDefault(type =>
                typeName.In(type.Name, type.FullName, type.AssemblyQualifiedName)
            );

            // Get the current assembly
            var executingAssembly = Assembly.GetExecutingAssembly();

            // Check if the type is inside the current assembly
            var targetType = Finder(executingAssembly);

            // Go through all of the referenced assemblies
            foreach (var assName in executingAssembly.GetReferencedAssemblies())
            {
                // If the type was found, return it
                if (targetType != null)
                    return targetType;

                // Check if the type is inside the assembly
                targetType = Finder(Assembly.Load(assName));
            }

            // Type wasn't found, return null
            return null;
        }

If I run it as local function or through a referenced project, it works fine, but when I create a NuGet package and call the method using the implementation of the method inside the NuGet package, it returns null.

The method Assembly.GetExecutingAssembly claims it returns The assembly that contains the code that is currently executing and yet I get different results when running it from NuGet package.

What can I do to get the correct output from the method if I pack it inside NuGet package?





Get array of list and keep reference?

For some performance reason , I want to get array of List directly in C#

https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,2765070d40f47b98

My code here:

private UIVertex[] GetArray(List<UIVertex> verts)
    {
        var aryF = typeof(List<UIVertex>).GetField("_items", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        return aryF.GetValue(verts) as UIVertex[];
    }

static List<UIVertex> verts
static UIVertex[] ary;
//...
ary = GetArray(verts);

In my case I can reuse 'verts' , But when 'verts' count change. my ary need to get again ( and it call reflection ) ,

reflection cost is too height , Can I just keep ary reference ? How to do it?





Find anonymous classes by annotation

Is there a way to find anonymous classes by some annotation with some java reflection library like (Reflections)?

I have this code: it use declare a inner class (extends Object) and annotated it with @DemoAnnotation

public class DemoUsageService {

    public void doSomething() {
        this.test(new @DemoAnnotation(value="Test") Object() {
            String content = "myContent";
        });
    }
}
@Retention(RUNTIME)
public @interface DemoAnnotation {
   String value();
}

Now I want to find all (anonymous) classes in my project that are annotated with @DemoAnnotation.


I tried the Reflections Library: but it seams not to find anonymous classes (inner static classes are found).

    @Test
    public void testFindAnnotatedClasses() throws Exception {
        
        Reflections reflections = new Reflections(
                new ConfigurationBuilder()
                        .setUrls(ClasspathHelper.forPackage(DemoUsageService.class.getPackageName()))
                        .setScanners(
                                new SubTypesScanner(false),
                                new TypeAnnotationsScanner()));
        
        Set<Class<?>> result = reflections.getTypesAnnotatedWith(DemoAnnotation.class);
        assertEquals(1, result.size()); //fails, because result.size == 0
        //...
    }
<dependency>
    <groupId>org.reflections</groupId>
    <artifactId>reflections</artifactId>
    <version>0.9.12</version>
</dependency>




Java record constructor invisible through reflection

I'm playing with Java 15's new records feature, and how it interacts with reflection. I've run into some strange behaviour, where I can sometimes access a record's constructor via reflection, and sometimes not. For example, given the following Java file:

Recording.java:

public class Recording {
    public static void main(String[] args) {
        System.out.println("Constructors: " + MainRecord.class.getConstructors().length);
        System.out.println("Methods: " + MainRecord.class.getDeclaredMethods().length);
    }

    record MainRecord(int i, String s) {}
}

This behaves as follows:

❯ javac --enable-preview --release 15 Recording.java
Note: Recording.java uses preview language features.
Note: Recompile with -Xlint:preview for details.
❯ java --enable-preview Recording
Constructors: 0
Methods: 5

In other words, the call to getConstructors() does not find any constructors (while the call to `getDeclaredMethods() does find methods). I don't understand why not, because the constructor does exist:

❯ javap Recording\$MainRecord
Compiled from "Recording.java"
final class Recording$MainRecord extends java.lang.Record {
  Recording$MainRecord(int, java.lang.String);
  public final java.lang.String toString();
  public final int hashCode();
  public final boolean equals(java.lang.Object);
  public int i();
  public java.lang.String s();
}

(Putting the record in a separate Java file gives the same results.)

However, if I do the same from JShell:

❯ jshell --enable-preview
|  Welcome to JShell -- Version 15
|  For an introduction type: /help intro

jshell> record JShellRecord(int i, String s) {}
|  created record JShellRecord

jshell> JShellRecord.class.getConstructors().length
$2 ==> 1

So, now it does find the constructor.

Here's the Java version I'm using:

❯ java -version
openjdk version "15" 2020-09-15
OpenJDK Runtime Environment AdoptOpenJDK (build 15+36)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 15+36, mixed mode, sharing)

Compiling and running the same program from Java 14 does work:

❯ java -version
openjdk version "14.0.2" 2020-07-14
OpenJDK Runtime Environment AdoptOpenJDK (build 14.0.2+12)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 14.0.2+12, mixed mode, sharing)
❯ javac --enable-preview --release 14 Recording.java
Note: Recording.java uses preview language features.
Note: Recompile with -Xlint:preview for details.
❯ java --enable-preview Recording
Constructors: 1
Methods: 5

I know that in Java 15, compared to Java 14, a number of restrictions have been put in place regarding reflection on records, but if I read the JEP correctly, those only apply to modification. Finding (and perhaps invoking) a constructor does not seem to apply.

Can anyone tell my what's going on here? What do I need to do to see a record's constructor in Java 15 through reflection?





java.lang.NoSuchFieldError when using ScalaTest

I'm getting a quite-hard-to-debug error when using ScalaTest. Oddly this seems to occur when my program has no Main object, but not when it does have a Main object. My code is really just using a typeclass with a polymorphic method to get a slice from a list, and looks like this (apologies for the slightly verbose example, I've reduced it down as much as I can):

package sportarray

object ArrayDefs {
  abstract class IsArr[A, I0, DT] {
    def getElem(self: A, i: Int): DT
    def getSlice[R](self: A, r: R)(implicit sliceTc: IsSlice[R]): sliceTc.Out = sliceTc.getSlice(self, r)

    trait IsSlice[R] {
      type Out
      def getSlice(self: A, ref: R): Out 
    }
    object IsSlice {
      implicit val iLocTCForInt = new IsSlice[Int] { 
        type Out = DT
        def getSlice(self: A, ref: Int): Out = getElem(self, ref)
      }
      implicit val iLocTCForList = new IsSlice[List[Int]] { 
        type Out = List[DT]
        def getSlice(self: A, ref: List[Int]): Out = ref.map(getElem(self, _))
      }
    }
  }

  object IsArrSyntax {
    implicit class IsArrOps[A, I0, T](self: A)(implicit 
      tc1d: IsArr[A, I0, T]
    ) {
      def getElem(i: Int) = tc1d.getElem(self, i)
      def getSlice[R](r: R)(implicit sliceTc: tc1d.IsSlice[R]) = tc1d.getSlice(self, r)
    }
  }
}

object ListOfListsObj {
  import ArrayDefs._
  case class List1d[I0, T] (
    indices: List[I0],
    data: List[T],
  )
  implicit def list1dIs1dSpArr[A, I0, T] = 
    new IsArr[List1d[I0, T], I0, T] {
      def getElem(self: List1d[I0, T], i: Int) = self.data(i)
    }
}

My test is simple and looks like this, in its own file in the test directory:

package sportarray

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers

class ArraySpec extends AnyFlatSpec with Matchers {
  "List" should "act as an array" in {
    import ArrayDefs._
    import ArrayDefs.IsArrSyntax._
    import ListOfListsObj._
    val list1d = List1d[Int, Double](List(1,2,3), List(1.0, 2.0, 3.0))
    assert(list1d.getSlice(1) == 2.0)
  }
}

If I sbt test this code as it is, I get the following error:

java.lang.NoSuchFieldError: sportarray$ArrayDefs$IsArrSyntax$IsArrOps$$tc1d
at sportarray.ArraySpec.$anonfun$new$1(HelloSpec.scala:12)
at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
at org.scalatest.OutcomeOf.outcomeOf$(OutcomeOf.scala:83)
at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
at org.scalatest.Transformer.apply(Transformer.scala:22)
at org.scalatest.Transformer.apply(Transformer.scala:20)
at org.scalatest.flatspec.AnyFlatSpecLike$$anon$5.apply(AnyFlatSpecLike.scala:1683)

I then tried adding a Main class to the program to see if this was a problem with the test, or a problem with the code itself:

object Main extends App {
  import ArrayDefs._
  import ArrayDefs.IsArrSyntax._
  import ListOfListsObj._
  val list1d = List1d[Int, Double](List(1,2,3), List(1.0, 2.0, 3.0))
  assert(list1d.getSlice(1) == 2.0)
}

This works fine if I sbt run, and, oddly enough, also allows me to run sbt test without any problems. If I then delete this main class, sbt test once again fails. Is anybody able to shed any light on what is going on here?

Thanks for any help!





dimanche 20 septembre 2020

How do I extract the Jackson property names from a java class when the serialization has been altered by annotation?

I have a somewhat odd problem. I have a system of data objects fo significant size, with a wide variety of properties. They're being serialized and deserialized with JSON, and in many cases, the field names have been altered by annotation. I have users who interact with that JSON and could not care less what the underlying code does, as long as they know what to put int eh JSON to make it work right. I'd like to provide them with an endpoint they can go to, where they can identify a class, and have it spit back the field name (as it would appear in the serialized JSON). I have the class object and have some ability in working with reflection.

I have considered a few options. My initial plan was that I was just going to handle everything with reflection, but I realized that that would require me to chase around all of the Jackson-affecting annotations myself to try to get the logic right. That sounds like a huge amount of unnecessary effort that would almost certainly generate a few ugly and well-hidden bugs as I wound up getting the logic not-quite-right. Jackson already has this logic, after all. It seems like I should be able to harness it in some way.

I have considered making a dummy version of the class, serializing it, and reading the field names off of the JSON that results, but there are a large number of classes here, many of them are complicated, and many of them have properties that point at one another. Under those conditions, making the sort of field auto-populate that would make that work right... well, that also sounds like a great deal of hopefully-unnecessary, bug-generating work.

There is the logic in Jackson somewhere that knows how to identify these field names (specifically the serialized field names for the fields that actually are being serialized). It seems like it should be possible to determine just with the ObjectMapper and the class that I want the information on. Is it possible? How should I do it? I haven't been able to find instructions online (fuzzed-out by all the articles on how to change the name in the first place) and just reading the class files in Jackson isn't doing the trick either. (The comments are relatively terse, and what I'm looking for is very specific. Even if I did find it, I don't know how I would make sure that it was actually giving me the thing I need, rather than some other, very similar thing.)

As a bonus, if there were some way to know which java class the field had as its value, that would be even better, but I have at least a few workarounds for that that I think I might be able to make workable. Getting a precise field names is more important.





How to get .net managed method pointer by "MethodName" that can be called on native code

Precondition

The .net method that I will get its pointer is:

  • public static method
  • have no overloads
  • arguments and return value just ValueType (unsafe pointer, primitive type, unmanaged struct)

Reason

Get the method pointer so I can call in C++ program.

This works for me but I need to declare delegate for every method.

I want to get rid of doing things over and over again.

In .net side:

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void UpdateDelegate(float delta);

public static void* GetUpdatePointer()
{
    var delegateInstance = = new UpdateDelegate(Update);
    var pfnUpdate = Marshal.GetFunctionPointerForDelegate(delegateInstance);
    return (void*)pfnUpdate;
}
public static Update(float delta)=>{...}

In C++ side:

typedef void (_stdcall *  FuncPtr)(float);
void foo()
{
    //just pseudo-code showing where is the pfnUpdate from.
    FuncPtr pfnUpdate = (FuncPtr)GetUpdatePointer();
    pfnUpdate(0.01f);
}

what I want

In c#, I export GetMethodPointer for my native code. It will return a function pointer to specified method, and this pointer can be invoked by native program via stdcall calling convention.

//avoid gc collect this object
static List<Delegate> KeepReference = new List<Delegate>();
public unsafe static void* GetMethodPointer(string name)
{
    System.Reflection.MethodInfo methodInfo = typeof(PhysicsMain).GetMethod(name);

    // also mark this delegate with [UnmanagedFunctionPointer(CallingConvention.StdCall)] attribute
    Type delegateType = ConstructDelegateTypeWithMethodInfo(methodInfo);

    var delegateInstance = Delegate.CreateDelegate(delegateType, methodInfo);

    KeepReference.Add(delegateInstance);
    return (void*)Marshal.GetFunctionPointerForDelegate(delegateInstance);
}

I need ConstructDelegateTypeWithMethodInfo to create a delegate with the same signature as the specified method. And mark [UnmanagedFunctionPointer(CallingConvention.StdCall)] attribute for it so that can be marshaled as a function pointer.

I think it may using IL, Reflection, even Asm to do this. Or using IL to write the whole GetMethodPointer method.





How would one use Kotlin's reflection?

I feel like I don't fully understand the depth of some deeps.

$ cat blya.kt 
inline fun<reified T> omg() {
    val x = T::class.supertypes  // such an innocent init
}

fun main() {
    omg<Int>()
}

$ kotlinc -d omg.jar -include-runtime blya.kt && java -jar omg.jar
OpenJDK 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
blya.kt:2:6: warning: variable 'x' is never used
    val x = T::class.supertypes
     ^
Exception in thread "main" kotlin.jvm.KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime. Make sure you have kotlin-reflect.jar in the classpath
    at kotlin.jvm.internal.ClassReference.error(ClassReference.kt:84)
    at kotlin.jvm.internal.ClassReference.getSupertypes(ClassReference.kt:42)
    at BlyaKt.main(blya.kt:9)
    at BlyaKt.main(blya.kt)

$ ls /snap/kotlin/current/lib/kotlin-reflect.jar  -l
-rw-r--r-- 1 root root 2893798 Sep 10 13:15 /snap/kotlin/current/lib/kotlin-reflect.jar

$ # hmm, strage it's not found on default, well, ok, let's add it

$ kotlinc -classpath /snap/kotlin/current/lib/ -d omg.jar -include-runtime blya.kt && java -jar omg.jar
OpenJDK 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
blya.kt:2:6: warning: variable 'x' is never used
    val x = T::class.supertypes
     ^
Exception in thread "main" kotlin.jvm.KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime. Make sure you have kotlin-reflect.jar in the classpath
    at kotlin.jvm.internal.ClassReference.error(ClassReference.kt:84)
    at kotlin.jvm.internal.ClassReference.getSupertypes(ClassReference.kt:42)
    at BlyaKt.main(blya.kt:9)
    at BlyaKt.main(blya.kt)

$ kotlinc -classpath /snap/kotlin/current/lib/kotlin-reflect.jar -d omg.jar -include-runtime blya.kt && java -jar omg.jar
OpenJDK 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
blya.kt:2:6: warning: variable 'x' is never used
    val x = T::class.supertypes
     ^
Exception in thread "main" kotlin.jvm.KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime. Make sure you have kotlin-reflect.jar in the classpath
    at kotlin.jvm.internal.ClassReference.error(ClassReference.kt:84)
    at kotlin.jvm.internal.ClassReference.getSupertypes(ClassReference.kt:42)
    at BlyaKt.main(blya.kt:9)
    at BlyaKt.main(blya.kt)

$ kotlinc -classpath /snap/kotlin/current/lib/kotlin-reflect.jar -d omg.jar -include-runtime blya.kt && java -classpath /snap/kotlin/current/lib -jar omg.jar
OpenJDK 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
blya.kt:2:6: warning: variable 'x' is never used
    val x = T::class.supertypes
     ^
Exception in thread "main" kotlin.jvm.KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime. Make sure you have kotlin-reflect.jar in the classpath
    at kotlin.jvm.internal.ClassReference.error(ClassReference.kt:84)
    at kotlin.jvm.internal.ClassReference.getSupertypes(ClassReference.kt:42)
    at BlyaKt.main(blya.kt:9)
    at BlyaKt.main(blya.kt)

As if I shouldn't want to use it at all.

Can anyone give some hint on what's happening?





Can someone explain this result?

There is a demo about go reflection:

func main() {
        test := []string{"hello"}
        V := reflect.ValueOf(test)
        if reflect.TypeOf(V).Kind() == reflect.Struct{
            fmt.Printf("it's a struct")
        } else {
            fmt.Printf("other")
        }
    }

and the output is "it's a struct"





samedi 19 septembre 2020

Assembly exes are getting cached

I'm trying to use reflection to load assemblies that are exes. The objective is to provide a harness that loads all the infrastructure, which is made up of various resources that are data, data access and utilities. The reason for this is the load time to is up to 90 seconds to 120 seconds for the entire infrastructure. So rather than have different instances of the infrastructure one is spinned up and shared for all. Each exe uses that infrastructure and through reflection in a service the infrastructure is injected into the exe. All fine when it's done the first time. The problem I'm having is that when I'm making changes in the exe's code and re-compile and then try to reload the new assembly using Assembly.LoadFrom method, it always loads the first assembly not the new one. So obviously the service caches the first assembly and everytime I try to reload with a new one it uses the older one. I'm on .net 4.8

Any Ideas?

 public static dynamic CreateObjectFromAssembly(string assemblyLocation, string type, object[] parameters)
    {
        Assembly sampleAssembly = null;
        AssemblyAccessor.LoadAssembly(assemblyLocation, ref sampleAssembly);
        return CreateObjectFromAssembly(sampleAssembly, type, parameters);
    }

    public static dynamic CreateObjectFromAssembly(Assembly sampleAssembly, string type, object[] parameters)
    {
        dynamic result = null;
        if (sampleAssembly != null)
        {
            Type foundOne = sampleAssembly.GetTypes().Where(x => x.FullName.Equals(type)).FirstOrDefault();
            if (parameters == null)
                result = Activator.CreateInstance(foundOne);
            else
                result = Activator.CreateInstance(foundOne, parameters);
        }

        return result;
    }

public static void LoadAssembly(String assemblyLocation, ref Assembly SampleAssembly)
    {
        try
        {
            SampleAssembly = Assembly.LoadFrom(assemblyLocation);
        }
        catch(Exception e)
        {

        }
    }




vendredi 18 septembre 2020

C# reflection get types from referenced project

I'm trying to get types declared in another my project referenced by my project with Unit Tests:

var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes())
                .Where(t => t.IsClass && t.Namespace != null && t.Namespace.StartsWith("MyProject"))
                .ToList();

It returns only types from the Unit Test project (the namespace is also starting with "MyProject"). What I'm doing wrong?





C# using PropertyInfo from reflection in a Lambda expression, error: not a valid property expression

I have a loop where I'd like to loop through only properties of my object with a specific decorator/attribute, and for those properties, if they're null, then remove them from being in a modified state by Entity Framework. I can get the loop to work, but not the removal of them being tracked.

This is my attempt:

                // Protect [NullUpdateIgnoreAttribute] attributes from nullification
                var properties = updateCustomer.GetType().GetProperties().Where(
                    prop => Attribute.IsDefined(prop, typeof(NullUpdateIgnoreAttribute)));

                foreach (var p in properties)
                {
                    Console.WriteLine($"Verifying {p.Name}...");
                    object value = p.GetValue(updateCustomer, null);
                    if (value == null)
                    {
                        Console.WriteLine($"{p.Name} is null. Shielding attribute.");
                        loyalty.Entry(customer).Property(x => p.Name).IsModified = false; 
                    }
                }

It's failing due to what I'm passing into loyalty.Entry().Property(x => here).IsModified = false. Clearly I can't use the propertyInfo directly. If I were doing this normally, I'd just pass x => x.propertyname. (e.g. x.firstname) but I can't hard code the property name here, it could be any one of several properties that have this attribute.

The error thrown is:

    "message": "The expression 'x => value(LCSApi.Customer+<>c__DisplayClass22_2).p.Name' is not a valid property expression. The expression should represent a simple property access: 't => t.MyProperty'. (Parameter 'propertyAccessExpression')",




C# Get Objects Attribute, create if null and set reference

I encountered the following problem: Imagine you have an object TypeA objA with objA.objBof TypeB. You want to create a variable TypeB objC = objA.objB, but if objB is null a new object of type TypeBshould be created. This is easy using ??. However the reference in objA will not get updated by that.

I'm unable to come up with a method, such that it takes any object (not only of TypeA), a string for the attribute name (not always of TypeB), and returns the correct type. Obviously one would need generics and reflection, but since the attribute type is derived within the method the generic type can not be inferred when calling the method. Therefore it throws an error.

I'm not allowed to touch the getter and want to avoid writing two lines where instead I want to call the function.





Store class declaring type in a variable [duplicate]

Is there any way to do something like this ?

class Program
{
    static void Main(string[] args)
    {
        var decType = Program;
    }
}

To be able to write a thing like that:

DataContext.Set<TheClass>() 




How to call method by name using Kotlin Reflection?

Is there any easy way to call method by name in Kotlin?

Something like:

val obj: Any
obj.invokeMethod("methodName", args...)




C++ Enum Template Functions: Compile Time Reflection

in principle the question is about the best way of getting reflexive iteration over an enum at compile time.

Let's assume I have an enum

enum Animal {
    DOG = 0,
    CAT = 12,
};

Now I have a function template

template <Animal A>
void animalVoice();

And I specialise the template:

template <>
void animalVoice<DOG>() {cout << "Bau" << endl;}
template <>
void animalVoice<CAT>() {cout << "Meow" << endl;}

Do I have the possibility of getting the same behaviour as in

int main() {
    animalVoice<DOG>;
    animalVoice<CAT>;
    return 0;
}

By iterating at compile time over the value of the enum?

Thanks

M.





jeudi 17 septembre 2020

Find all instances of Type in an object graph

Lets say i have the following object graph

Parent : BaseEntity
  string1 SimpleString
  Middle Middle
  List<Child> Children (3)

Middle : BaseEntity
  string NormalStr
  int NiceInt
  RandomClass Ignore

 Child : BaseEntity
   string ChildString
   Parent Parent
  

In this example i want a way to give my Parent as input and get back a flat list {Parent, Middle, Child1, Child2, Child3}. It should work for any type of object graph.

Im trying to get there with reflection and recursion. The problem i run into is the cyclic reference between Parent and Child and i end up in an infinite loop.

How do i prevent this? I cant seem to get any "already seen" mechanism to work.

This is what i got so far. It works without the collection part, but that part is pretty important...

    public void TraverseThroughProperties(object myObject)
    {
        foreach (var prop in myObject.GetType().GetProperties())
        {
            var instance = prop.GetValue(myObject);
            if (instance is BaseEntity myBase)
                TraverseThroughProperties(instance);


            if (instance is ICollection collection)
            {
                foreach (var item in collection.OfType<BaseEntity>())
                    TraverseThroughProperties(item);
            }

            // Do something with myObject + prop
        }
    }