vendredi 30 avril 2021

Is possible in typescript get access to other decorator names used by a method in a NestJS application?

I need to get a list of decorators used by a method inside one custom defined decorator.

I have reviewed the typescript decorators and Reflect Metadata documentation but I could not find anything about that.

My application is a NestJS app and I need to detect what properties are using the GraphQL @Query() decorator.





Dynamically Access Nested struct values

I am trying to access a property based on the path i get from the database:

for example in struct Vehicle,


type Vehicle struct {
    core.Model
    Manufacturer Manufacturer
    VehicleNumber string
.....
}

type Manufacturer struct {
    ManufacturerName string
....
}

i want to fetch

value := exportValueFromField(vehicle,"Manufacturer.ManufacturerName")
    func exportValueFromField(data interface{}, index string) string {
       indexArray := strings.Split(index, ".")
       r := reflect.ValueOf(data)
       for _, i := range indexArray {
          if r.FieldByName(i).Kind() == reflect.Struct {
            r = reflect.ValueOf(r.FieldByName(i).Interface())
          }else {
            r = r.FieldByName(i)
          }
       }
       return fmt.Sprintf("%v", r)
   }

But it doesn't seem to work





Not able to use mirrors in flutter package

I created a new flutter package project.

Trying to use dart:mirrors in tests, but it is not visible...

Any guess why that happen?

Here is my pubspec:

name: testName
description: A new Flutter package.
version: 0.0.1
author:
homepage:

environment:
  sdk: ">=2.12.0 <3.0.0"
  flutter: ">=1.17.0"

dependencies:
  flutter:
    sdk: flutter
  equatable: 2.0.0

dev_dependencies:
  flutter_test:
    sdk: flutter

enter image description here





jeudi 29 avril 2021

Parametrize record creation for an Xunit Theory

I would like to change each property on a record in turn and verify the equality function works properly. Instead of writing a test for each property I was hoping to use reflection and xunit theories and the record 'with' syntax to do something like this, like in this post:

    [Theory]
    [InlineData("Tag", "fake tag")]
    [InlineData("Name", "fake name")]
    [InlineData("Age", "fake age")]
    public void Equality_PropertyChanged(string propertyName, string value)
    {
        Type myType = typeof(MyRecordType);
        PropertyInfo myPropInfo = myType.GetProperty(propertyName);
        
        var different = myRecord with { myPropInfo.SetValue(this, "a different tag", null) };
        Assert.NotEqual(m_fake_params, different);
    }

I something like this possible?





PropertyInfo parameter with requirements

Is it possible to take PropertyInfo (or something similar) as an argument and also require that the PropertyInfo be of type decimal? Or better yet require that it be a property of a specific class or interface? I'm thinking similar to how typescript has keyof

This is what I was hoping would work

public decimal SumProperty(Item item, PropertyInfo propertyOfItem){
    // has to be casted to decimal?
    return propertyOfItem.GetValue(item);
}




mercredi 28 avril 2021

Automatically populate view with heterogeneous values from a model

Let's pretend I have a model like the following:

struct Coupon: Identifiable {
    let id: Int
    let code: String
    let totalAmount: Double
    let spentAmount: Double
    let rate: Double
    let validFrom: Date
    let validTo: Date
    let supplier: Supplier
}

My intent is to build a SwiftUI card-like view displaying all the formatted information using a helper function like the following:

private func entry(for label: LocalizedStringKey, value: LocalizedStringKey) -> some View {
    HStack { Text(label); Spacer(); Text(value) }
}

I know I can use reflection to loop through the properties, and start doing some type checking to format dates, for example, but for doubles things are more complicated because some represent amounts but others don't. Another problem would be how to render the label for each property. Is there some even complex way to achieve this idea?





How do you get specific generic method overload from static class using reflection?

so I have a static class:

class static EnumHelper {
   public string GetCode<E>(E value) where E: struct {}

   public string GetCode<E>(E? value) where E: struct {}
}

however using:

typeof(EnumHelper).GetMethod("GetCode")

always returns this error:

System.Reflection.AmbiguousMatchException: Ambiguous match found.

However, i can't directly use the overload of GetMethod providing the "parameter types" because the parameter type are based upon the generic type argument defined in the method itself.

The goal is to:

//given parameter: T item
MethodInfo mi = typeof(EnumHelper).GetMehod("GetCode");
mi.MakeGenericMethod(typeof(T));
mi.Invoke(null, new object[] {item});

but I'm having trouble at the "GetMethod" part of this equation.

Thanks.





Is there a way to unit test a function with static variables?

Ιs there a way to test a function containing static variables using PHPUnit?

For example,

class MyClass {
  public function my_method() {
    static $already_invoked = false;
    
    if ($already_invoked) {
      return;
    }

    echo 'Hello world';

    $already_invoked = true;
  }
}

my_method() will print Hello world exactly one time, no matter how many times it's called.

$instance = new MyClass();
$instance->my_method();
$instance->my_method();

outputs:

Hello world

Having just one test

<?php
class MyMethodTest extends \PHPUnit\Framework\TestCase {
    public function test_should_print_hello_world_exactly_one_time() {
        $instance = new MyClass();
        $instance->my_method();
        $instance->my_method();

        $this->expectOutputString('Hello world');
    }
}

passes:

MyMethod
 ✔ Should print hello world exactly one time

However, adding another test

<?php
class MyMethodTest extends \PHPUnit\Framework\TestCase {
    public function test_should_print_hello_world() {
        (new MyClass())->my_method();

        $this->expectOutputString('Hello world');
    }

    public function test_should_print_hello_world_exactly_one_time() {
        $instance = new MyClass();
        $instance->my_method();
        $instance->my_method();

        $this->expectOutputString('Hello world');
    }
}

causes the previously passing test to fail, because of the static variable:

MyMethod
 ✔ Should print hello world
 ✘ Should print hello world exactly one time
   │
   │ Failed asserting that two strings are equal.
   │ --- Expected
   │ +++ Actual
   │ @@ @@
   │ -'Hello world'
   │ +''
   │

Now, I know I could use a static property instead:

class MyClass {
    private static bool $already_invoked = false;

    public function my_method() {
        if (self::$already_invoked) {
            return;
        }

        echo 'Hello world';

        self::$already_invoked = true;
    }
}

That way, I could use a reflection property to reset its value immediately after each test, like this:

class MyMethodTest extends \PHPUnit\Framework\TestCase {
    // ...

    public function tearDown() {
        $ref = new ReflectionProperty('MyClass', 'already_invoked');
        $ref->setAccessible(true);
        $ref->setValue(null, false);
    }
}

And then, both tests pass:

MyMethod
 ✔ Should print hello world
 ✔ Should print hello world exactly one time

In my case, though, I'm dealing with legacy code and I'd like to write some unit tests before refactoring it.

I've also tried to run each test in isolation (although that's not ideal since it'd probably end up being considerably slower) using the @runInSeparateProcess method annotation, but that seems to be failing because the process isolation feature requires serialization:

PHP Fatal error:  Uncaught Exception: Serialization of 'ReflectionClass' is not allowed in phar:///usr/local/bin/phpunit/phpunit/Util/GlobalState.php:151

Is there a way to test a function containing static variables?





JAVA - Reflection onto Generic Type [duplicate]

i want do do a POST Request using Spring REST Template and a Generic Type for the ResponseEntity. For this i need to do a reflection onto the class i want to use for the ResponseEntity. How can i achieve this?

This is my code so far:

public <T> T post(String url, Map<String, Object> body) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

    //build Request
    HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);
    //Send request
    ResponseEntity<T> response = this.restTemplate.postForEntity(url, entity, T.class);
}




mardi 27 avril 2021

How to implement interface with reflection and pass it to a method called with reflection in Java?

I need to implement a listener and pass it to a service. I do not have a direct access to both interface and service classes.

I am stuck at passing Proxy interface to a method via reflection.

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Main {
    public static void main(String[] args) {

        try {
            Class<?> c = Class.forName("android.view.WindowManagerGlobal");
            Method m = c.getMethod("getWindowManagerService");
            Object windowManager = m.invoke(c.newInstance(), new Object[] {});

            Class<?> someInterface = Class.forName("android.view.WindowManagerService$WindowChangeListener");

            Object instance = createListenerInstance(someInterface);
            instance.getClass().getDeclaredMethod("windowsChanged", (Class<?>[]) null).invoke(instance, new Object[] {});
            System.out.println(instance.getClass().getName());

            // Fails with:
            // java.lang.NoSuchMethodException: android.view.WindowManagerService.addWindowChangeListener(com.sun.proxy.$Proxy0)
            windowManager.getClass().getMethod("addWindowChangeListener", instance.getClass()).invoke(windowManager, new Object[] { instance });

            System.out.println(windowManager.getClass().getName());
        } catch (Exception e) {
            System.out.println(e.getCause());
        }
    }

    private static Object createListenerInstance(Class<?> someInterface) {
        return Proxy.newProxyInstance(someInterface.getClassLoader(), new Class<?>[] { someInterface }, new InvocationHandler() {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                // Handle the invocations
                if (method.getName().equals("windowsChanged")) {
                    System.out.println("windowsChanged");
                } else if (method.getName().equals("focusChanged")) {
                    System.out.println("focusChanged");
                }
                return args;
            }
        });
    }
}

The following is the piece of code I have no access to by either new operator or ClassName.class:

package android.view;

public class WindowManagerService {

    public interface WindowChangeListener {
        public void windowsChanged();
        public void focusChanged();
    }
    public void addWindowChangeListener(WindowChangeListener listener) {
        System.out.println("Listener added: " + listener);
    }
    public void removeWindowChangeListener(WindowChangeListener listener) {
        System.out.println("Listener removed: " + listener);
    }
}

/////////
package android.view;

public class WindowManagerGlobal {
    private WindowManagerService windowManagerService = new WindowManagerService();

    public WindowManagerService getWindowManagerService() {
        return windowManagerService;
    }

    public void setWindowManagerService(WindowManagerService windowManagerService) {
        this.windowManagerService = windowManagerService;
    }
}

I do not know how to pass the proxy object to a method that requires WindowChangeListener.





lundi 26 avril 2021

Java reflexation get all classes within constrains

Im trying to make a generic instance mapper from an SQLite DB to my project logic layer. Each entry in the mapper is an instance of some class "DAL< name >" for example "DALProduct" all in the same package that extends class "DALObject" with the following structure:

public abstract class DALObject{
  static String getCreate();
  ... //other logic
}

Using reflexation I can easily call the getCreate method on each class and get what I need from it. The issue is that I dont know how many child classes DALObject will have and i want a mapper that won't need to be touched when a new one is added.

I know that you can get all child classes of DALObjects that have been loaded but I run this code at the very start of my program before I load any of the classes.

Any ideas? I have a pretty big constraint case so maybe I can somehow hack it together.





Dynamic DI in Asp.net Core

I'm using asp.net core and I need to add DI dynamically like bellow:

services.AddTransient<SampleConfig>();

Assembly assembly = myAssembly;

if (assembly == null)
{
     return services;
}

foreach (var type in assembly.ExportedTypes)
{
     var interfaceType = type
        .GetInterfaces().FirstOrDefault(i => i.GetInterfaces().Any(x => x.Name.Contains("IService")));

     if (interfaceType == null)
           continue;

     services.AddTransient(interfaceType, type);
}

My service is like this:

public PriceProvider(
        IHttpClientFactory httpClientFactory,
        ILoggerFactory loggerFactory,
        SampleConfig config)
        : base(httpClientFactory, loggerFactory)
    {
        _httpClient = httpClientFactory.CreateClient();
        _c = config;
    }

My issue is everything works except SampleConfig. It always is null.

Did I miss something?





dimanche 25 avril 2021

Modifying struct value using reflection and loop

I wanted to loop through a struct and modify fields value using reflection. How can I Set it?

func main() {
    x := struct {
        Foo string
        Bar int
    }{"foo", 2}
    StructCheck(Checker, x)
}

func Checker(s interface{}) interface{} {
    log.Println(s)
    return s
}

func StructCheck(check func(interface{}) interface{}, x interface{}) interface{} {
    v := reflect.ValueOf(x)
    for i := 0; i < v.NumField(); i++ {
        r := check(v.Field(i))
        w := reflect.ValueOf(&r).Elem()

        log.Println(w.Type(), w.CanSet())

        // v.Field(i).Set(reflect.ValueOf(w))

    }
    return v
}

Running Set() causes panic and shows :reflect.Value.Set using unaddressable value





How to scan for annotations in methods only in specific classes using reflection library java?

I have an annotation @API which I assign to all the routes i.e RequestMapping in a controller in java spring.What I want to do is,First scan all the classes in a package that are annotated with @Controller and after scanning all the controller classes,I want only to scan for Methods with annotation @API in only these controller annotated classes.

How can I implement this in using reflection in java?

  Reflections reflections = new Reflections("my.project.prefix");

  Set<Class<? extends SomeType>> subTypes = reflections.getSubTypesOf(SomeType.class);




Reflections is not working when using Jenkins

I've created a console app which gets dlls from folder and uses reflection in order to extract the methods out of each dll, it works fine on my local machine, but when I use this app from Jenkins server, I get error for each

file (could not be loaded: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.)

is that a known issue? what could be the problem?





samedi 24 avril 2021

No field signature in class Ljava/lang/reflect/Method

I've below code

println("Result: '${Method::class.java.getDeclaredField("signature")}'")

When I execute this code on JVM, I get valid result

import java.lang.reflect.Method

fun main(args: Array<String>) {
    println("Result: '${Method::class.java.getDeclaredField("signature")}'")
}

// OUTPUT: Result: 'private transient java.lang.String java.lang.reflect.Method.signature'

but when I execute the same line in Android, I get No field signature in class Ljava/lang/reflect/Method.

Here's the complete stacktrace

2021-04-24 15:16:49.564 13890-13890/com.theapache64.notes E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.theapache64.notes, PID: 13890
    java.lang.RuntimeException: Unable to create application com.theapache64.notes.NotesApp: java.lang.NoSuchFieldException: No field signature in class Ljava/lang/reflect/Method; (declaration of 'java.lang.reflect.Method' appears in /apex/com.android.runtime/javalib/core-oj.jar)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6652)
        at android.app.ActivityThread.access$1600(ActivityThread.java:231)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1952)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: java.lang.NoSuchFieldException: No field signature in class Ljava/lang/reflect/Method; (declaration of 'java.lang.reflect.Method' appears in /apex/com.android.runtime/javalib/core-oj.jar)
        at java.lang.Class.getDeclaredField(Native Method)
        at com.theapache64.notes.NotesApp.onCreate(NotesApp.kt:20)
        at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1197)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6647)
        at android.app.ActivityThread.access$1600(ActivityThread.java:231) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1952) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7682) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 
2021-04-24 15:16:49.597 13890-13890/? I/Process: Sending signal. PID: 13890 SIG: 9

- Why is this happening?





Annotation Processing Tool To Scan A Java Project In A Different Directory

We want to write an annotation processor to generate a json file based on the data of certain custom annotations. Let's call this annotation processor project jsongenerator. We want jsongenerator to be in a separate repo (lets say as a standalone CLI tool) which we run on the java project which we want to generate a json for (based on the annotation it uses).

So the question is, provided a "directory path" as an argument (which would link to the path of a different java project). E.g.

jsongenerator --dirPath=/path/to/java/project/source

How would one read the third party java project source to run annotation processing on it?





Activator.CreateInstance(assemblyType) return null using c#

We have a requirement to load the dll dynamically. so i have used the Activator.CreateInstance(assemblyType) c# code but it returning null.can you please help me





vendredi 23 avril 2021

Using reflection how can we tell if a class property is a nullable collection and get its data type?

I have no problems with properties that are non-nullable collections but everything changes when the property is a nullable collection...

Given a class with nullable collection properties (int?[], long?[], List<Nullable>, ...)

public class SomeClass
{
    public int?[] PropertyX { get; set; }
    public long?[] PropertyY { get; set; }
    public float?[] PropertyZ { get; set; }
    public List<decimal?> PropertyList { get; set; }
    public string Name { get; set; }
} 

How can I tell if the property is a nullable collection?
Does the nullable collection have any actual values?
Lastly what is the nullable collections data type?

public class SomeOtherClass
{
    public string Discover(SomeClass someClass)
    {
        var sb = new StringBuilder();
        foreach (var propertyInfo in someClass.GetType().GetProperties())
        {
            var propValue = propertyInfo.GetValue(someClass, new object[] { });
            if (propValue.IsNullableCollection() && propValue.HasValue())
            {
                sb.AppendFormat("{0} data type is {1}", propValue.GetDataType());
            }
        }
        return sb.ToString();
    }
}

Example:

void Main
{
  var sc = new SomeClass() 
  {
    PropertyX = new int?[2]{50,10}
  };
  var output = new SomeOtherClass().Discover(sc); 
  
  //Display Output ...
}

"PropertyX has values and data type is int."





Why does Kotlin (community) encourage reflection in pattern matching

Almost every Kotlin Android tutorial or project intensively uses when-is constructions like the following

val response : Response = //...
when(response){
   is Success   -> useResponseData(response.data)
   is Cancelled -> handleCancellation()
   is Error     -> handleError(response.errorCode) 
}

As far as I understand, the usage of reflection is not justified in most cases and should be avoided. I suppose that my example is that particular case when the use of reflection is justified, provided that the Response is sealed and most likely the set of its subclasses will never change. Am I correct?

Is such construction in my example absolutely "clean", or rather the compromise for the sake of code simplicity?





How to access Class.typeName on Android api 21+

Class.typeName or Class.getTypeName() was added in Api 26 according to the Android docs. Is there a way to get the type name in some other fashion?

enter image description here





jeudi 22 avril 2021

Using A VSIX is it possible to create a Object from the Project That has a Extension

What I need was to Create an Instance of a C# class in the Main Project using a VSIX extension. Is this Possible?

Example:- A project this has my extension installed. When extension Invoke it Should create an Instance of that Open File. Inside the Vsix project in order to use those methods for another purpose.

Here What I was tried;

     public Void ExecuteCommand(SaveCommandArgs args, CommandExecutionContext executionContext)
    {
        ThreadHelper.ThrowIfNotOnUIThread();

      
        if (args.SubjectBuffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument textDoc))
        {
            var filePath = textDoc.FilePath;
             // Here I get the Open File Locatiob
            var dte = Package.GetGlobalService(typeof(DTE)) as DTE;
            ProjectItem item = dte.Solution?.FindProjectItem(filePath);


            var name = Path.GetFileNameWithoutExtension(filePath);
            
             // test is the project I used for Extension. namespace Test in the project that used the Extension.
          // Here When I tried to create a object from that class In give me assembly error. Activator point to the Current VSIX assembly not the Project  assembly we want
            object obj = ((ObjectHandle)Activator.CreateInstance(null, "Test."+name)).Unwrap();
            Type type = obj.GetType();

           

            
        }}

So what I really want to know What I am trying is possible or Not? if is it possible how to get that assembly here or is there any other better way to do this?





C# Loading Assemblies With Names Containing a Dot

In my c# application (asp.net mvc), I want to use Autofac to handle my dependency injection, but I got an error when atttempting to use the RegisterAssemblyTypes function (error message below).

I did some experiments with a new solution and found that the error seems to be related to a dot in the project name. The test solution looks like this:

AssemblyTest.sln

- Main.csproj
--> Program.cs

- TestLoadAssembly.csproj
--> Test.cs

- TestWith.Dots.csproj
--> Test.cs

The test classes both have one method that prints "Hello" to the screen. Program.cs looks like this:

using System.Reflection;

namespace Main
{
    class Program
    {
        static void Main(string[] args)
        {
            var x = Assembly.Load(nameof(TestLoadAssembly)); //This works
            var y = Assembly.LoadFrom("TestWith.Dots.dll"); // This seems to work
            var z = Assembly.Load(nameof(TestWith.Dots)); // Error here
        }
    }
}

Main is the active project, and there are project references from Main to the other two. All projects are .net 5 projects.

The error I get from line 3:

System.IO.FileNotFoundException: 'Could not load file or assembly 'Dots, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'

My question is, how do I make the third line (z) work? Since the first line works, but the third line does not, it seems the error is related to the dot in the name, or is there something that I'm missing here? However, as line two shows, it seems to work when loading the dll by referencing it directly by name.

I have been staring myself blind at this, so I would appreciate your help!





Iis it possible to codify a collection (or enumeration) of class properties?

I am using reflection to compare objects of a given class. I only want to compare certain properties. Right now I have a simple collection of strings with the names of the properties that I want to compare.

Something like:

public static readonly ICollection<string> PROPERTIES_TO_COMPARE = new List<string>()
{
     "Name",
     "Phone"
};

Then I use it doing something like:

PropertyInfo[] properties = typeof(MyClass).GetProperties();
foreach (PropertyInfo property in properties)
{
     if (PROPERTIES_TO_COMPARE.Contains(property.Name))
     {
         //compare
     }
 }

But if next month I change the property name from "Phone" to "PhoneNumber" I will need to remember to edit the collection of properties. I do not find myself to be that trustworthy.

Is there a better way? Perhaps something similar to nameof(varible), so the compiler can help me? Or perhaps my entire approach is wrong?

Update: This is what I need to do (ideally with less code):

 if (oldVersion.Name != newVersion.Name)
 {
        changes.Add(new Change()
        {
              FieldName = nameof(oldVersion.Name),
              OldValue = oldVersion.Name,
              NewValue = newVersion.Name
        });
  }

  if (oldVersion.Phone != newVersion.Phone)
  {
        changes.Add(new Change()
        {
             FieldName = nameof(oldVersion.Phone),
             OldValue = oldVersion.Phone,
             NewValue = newVersion.Phone
        });
  }
  // and 15 properties more




mercredi 21 avril 2021

Java Reflection: Why getConstructors() for class A returns an empty array? [duplicate]

D.java

   package com.model; 
   public class D {
     public int z;
    }

B.java

package com;
import com.model.D;

class A {
 public int x;
}

class C {
 public int y;
 public C() {}
}
        
public class B {
    public static void main(String args[] ) throws Exception {
        
        Class clssA = A.class;
        Constructor[] constructorA = clssA.getConstructors();   // []
        
        Class clssC = C.class;
        Constructor[] constructorB = clssC.getConstructors();  // [public com.C()]

        Class clssD = D.class;
        Constructor[] constructorD = clssD.getConstructors();  // [public com.model.D()]
        }
}

As per my understanding, the Java compiler provides a default (public no-arg) constructor for classes without any constructor, then why the output of getConstrucors() call for class A and class C are different?

Also, class A and class D have the same class structure with the only difference of package name but the getConstructors() for class D returns a non-empty array?





C# - Create an instance of a class with generic type parameters without specifying these types

I have the following code:

public static class Typing
{
    public static void Run()
    {
        var type = typeof(GenericSuperType<,>);

        type = type.MakeGenericType(typeof(int), typeof(int));
        dynamic instance = Activator.CreateInstance(type);
        var types = instance.Register();
        
        foreach(var i in types)
            Console.WriteLine(i);
    }
}

public class GenericSuperType<C, R>
{
    public IEnumerable<Type> Register()
    {
        yield return typeof(MiddlewareOne<C, R>);
        yield return typeof(MiddlewareTwo<C, R>);
    }
}

public interface IGenericMiddleware<C, R>
{
    R Execute(C command);
}

public class MiddlewareOne<C, R> : IGenericMiddleware<C, R>
{
    public R Execute(C command)
    {
        return default;
    }
}

public class MiddlewareTwo<C, R> : IGenericMiddleware<C, R>
{
    public R Execute(C command)
    {
        return default;
    }
}

What I want to achieve is to create an instance of GenericSuperType<,> class in order to call the Register() method that will basically return some other generic types. The sole purpose for this is to get the types the Register() method returns (those types could be different than the ones in the example and would be provided by a user in a method overload). However, in order to do that, I need to provide some types to GenericSuperrType<,> (as I do with int) here, but then the problem rises - these types can have generic constraints on them, let's say:

public class GenericSuperType<C, R> where C : ISomeType
{
    public IEnumerable<Type> Register()
    {
        yield return typeof(MiddlewareOne<C, R>);
        yield return typeof(MiddlewareTwo<C, R>);
    }
}

In that case, creating the instance with whatever type will fail.
What I have tried so far is to check the generic constraints on C and R and act accordingly, something alog those lines (a simple example):

    public static void Run()
    {
        var type = typeof(GenericSuperType<,>);

        var defparams = type.GetGenericArguments();
        IList<Type> typeConstraints = new List<Type>();
        foreach (var i in defparams)
        {
            typeConstraints.Add(i.GetGenericParameterConstraints().FirstOrDefault());
        }

        for (int i = 0; i < typeConstraints.Count; i++)
        {
            if (typeConstraints[i] == null)
                typeConstraints[i] = typeof(String);
        }

        type = type.MakeGenericType(typeof(int), typeof(int));
        dynamic instance = Activator.CreateInstance(type);
        var types = instance.Register();
        
        foreach(var i in types)
            Console.WriteLine(i);
    }

And that would work OK but I'd have to cover all possible generic constraints.
The other thing I thought about is: to actually remove the GenericSuperType<,> generic type constraints with reflection (if it's actually possible, I think that should be but I'm not great at c# reflection), and then provide some dummy type just to get the types from the Register() method. Or maybe just copy the content of the type/class/file into another one without the generic type constraints and call them? I'm looking for solution to this (I know this sounds complicated but I also know that reflection is a powerful tool that would make that possible).

Thank you in advance for all your help!





mardi 20 avril 2021

Lua - C++ object metatable returns nil

I have just started delving into Lua, and I learnt that C++ object properties could be accessible through metatables.

I am trying to access such an object's functions in a game's script: "GameLib". It is available in Lua as a global variable, but getmetatable() returns nil:

-- example usage elsewhere in the scripts:
local pPlayer = GameLib.GetLocalPlayer();

-- my tried code:
local mt = getmetatable(GameLib);
print("Metatable type:" .. type(mt)); -- "Metatable type: nil"

What could be the problem? Are there cases, when a C++ object has no metatable? If so, is there another way to access its properties?





Serialize objects to JSON using custom reflection

I'm writing a custom runtime reflection system to serialize the objects of my application (a game, so game entities).

My reflection framework is really simple, it allows me to reflect data types and attach data members, constructors and member functions to these meta types:

// reflect built-in types
    Reflect::Reflect<int>("int");
    Reflect::Reflect<float>("float");
    Reflect::Reflect<std::string>("string");

// reflect TransformComponent
    Reflect::Reflect<TransformComponent>("TransformComponent")
    .AddConstructor<>()
    .AddDataMember<&TransformComponent::SetPosition, &TransformComponent::GetPosition>("position")
    .AddDataMember<&TransformComponent::SetId, &TransformComponent::GetId>("id")               
    .AddDataMember(&TransformComponent::mName, "name")
    .AddDataMember(&TransformComponent::f, "f");

I can use reflected members to set and get data members (which can have attached setters and getters) or to construct instances of reflected types:

Reflect::any transformComponentAny = Reflect::Resolve("TransformComponent")->GetConstructor<>()->NewInstance();

// using reflection to set and get object fields
    Reflect::any positionAny = Reflect::Resolve("Vector3D")->GetConstructor<>()->NewInstance();
    Reflect::Resolve("Vector3D")->GetDataMember("x")->Set(positionAny, 22.22f);
    Reflect::Resolve("Vector3D")->GetDataMember("y")->Set(positionAny, 130.12f);
    Reflect::Resolve("Vector3D")->GetDataMember("z")->Set(positionAny, 545.12f);

    Reflect::Resolve("TransformComponent")->GetDataMember("f")->Set(transformComponentAny, 0.009f);
    Reflect::Resolve("TransformComponent")->GetDataMember("position")->Set(transformComponentAny, positionAny);
    Reflect::Resolve("TransformComponent")->GetDataMember("id")->Set(transformComponentAny,32325);
    Reflect::Resolve("TransformComponent")->GetDataMember("name")->Set(transformComponentAny, std::string("hey a transform, again..."));  

all objects are wrapped inside a class like std::any, which abstract the real object, and mantains a type descriptor of the object type (to perform casts, conversions etc..)

Now, this is all ordinary reflection stuff I guess, what I'm stuck on is how to serialize my objects (which is the whole point of all this stuff).

When I want to serialize a member of an object to a JSON, I can easily retrieve the value, given the type descriptor of the object, the meta data member and the instance of the object:

auto typeDesc = object.GetType();  // get the type descriptor for the object (this is a any object)
for (auto dataMember : typeDesc->GetDataMembers())  
{
     auto fieldName = dataMember->GetName();
     auto fieldType = dataMember->GetType()->GetName();

     any field = dataMember->Get(object);

    if (fieldType == "int")                       
        json[fieldName] = field.Get<int>();
    else if (fieldType == "string")
        ....
}

what I want is to avoid the explicit check for the runtime type and the cast to the type. I'd like something like this:

json[fieldName] = field  // field is a any, it has no info about type at compile time

and let the meta type perform the necessary cast. I'm able to do it when deserializing from a JSON, since the meta types preserve the compile time type of the data member they represent, while any just keeps a type descriptor of the object it contains (I need to call any.Get<> at compile time with the appropriate type).

Any ideas about how to do it?





Java reflection : Object has a field Set

So I have an object that contains a set of an object, how can I use reflection to tell what type of set it is?

I can do obj.getClass().getDeclaredField(propertyName).getType(); to find out its a set, but how do I find out its a Set of MyObject, is that possible?





lundi 19 avril 2021

In Kotlin, how does GSON.fromJson(...) manage to mutate a read-only field of an existing object?

In Kotlin, how can an instance's read-only val field be mutated?

In the following Kotlin code, gson.fromJson(...) gets a Thing(0) from the InstanceCreator and somehow manages to mutate value from 0 to 1, then return that object. How?

import com.google.gson.GsonBuilder
import com.google.gson.InstanceCreator

class Thing(val value: Int)

fun main() {
    val creator = InstanceCreator { Thing(0) }
    val gson = GsonBuilder().registerTypeAdapter(Thing::class.java, creator).create()
    val thing = gson.fromJson("""{"value":1}""", Thing::class.java)
    println(thing.value) // 1
}

I verified that the object returned by gson.fromJson(...) is the same object provided by the InstanceCreator, so it's not creating a new instance based on the one provided by the InstanceCreator.

I also tried setting value using reflection, but didn't find a way. There was no setter available on the val field.





dimanche 18 avril 2021

using variadic arguments to function in golang causes type error compared to passing non-variadically

I'm using the gui package for Go ImGui bindings, and I'm having trouble adding a variable number of variadic arguments to one of it's functions by passing in an array postpended with ... due to some type errors

My Code:

package main

import (
    "fmt"

    g "github.com/AllenDang/giu"
)

func handle(err error) {
    if err != nil {
        panic(err)
    }
}

var lines []g.Widget
func loop() {
    g.SingleWindow("hello world").Flags(g.WindowFlagsAlwaysAutoResize).Layout(
        lines...,
    )
}

func main() {
    imageSize := float32(150)
    lines = append(lines, *g.Line(
        g.ImageWithFile("/path/to/png").Size(imageSize, imageSize),
    ))

    wnd := g.NewMasterWindow("Hello world", 400, 200, g.MasterWindowFlagsTransparent, nil)
    wnd.Run(loop)
}

Compiling gets the following error

./main.go:105:16: cannot use *giu.Line(giu.ImageWithFile("/path/to/png").Size(imageSize, imageSize)) (type giu.LineWidget) as type giu.Widget in append:
        giu.LineWidget does not implement giu.Widget (Build method has pointer receiver)

OK, makes sense because g.Line() returns type *g.LineWidget and lines is of type []g.Widget. I change the global declaration of lines to...

var lines []g.LineWidget

It still won't compile...

./main.go:89:173: cannot use lines (type []giu.LineWidget) as type []giu.Widget in argument to giu.SingleWindow("hello world").Flags(giu.WindowFlagsNoTitleBar | giu.WindowFlagsNoResize | giu.WindowFlagsNoMove | giu.WindowFlagsNoCollapse | giu.WindowFlagsAlwaysAutoResize).Layout

Not sure why I am getting an error in this case, because if I pass in the parameter myself without using variadic expansion like so, it still works

g.SingleWindow("hello world").Flags(g.WindowFlagsNoTitleBar | g.WindowFlagsNoResize | g.WindowFlagsNoMove | g.WindowFlagsNoCollapse | g.WindowFlagsAlwaysAutoResize).Layout(
        g.Line(
            g.ImageWithFile("/path/to/png").Size(111, 111),
        ),
)

How do I remedy this? I tried using a function that took in ...interface{} and returned the proper type, and tweaked some other stuff, but none of that worked. Do I need to use reflection? I just want to pass in a variable number of parameters to that function at runtime, based on the images in a directory. Any help would be appreciated

Edit: Just a silly error, declaring lines like

var lines []g.Widget

and appending like

lines = append(lines, g.Line(
        // g.Button("Click Me").OnClick(onClickMe),
        g.ImageWithFile("/image").Size(imageSize, imageSize),
    ))

fixes the issue





How to use java reflection to implement methods

This task is about a basic decompiler and how could i fill in the following several methods marked as comment? thanks

getMethodInfo() returns a string object which contains the method header(visibility, modifiers, return type, name, parameter list)

getClassInfo() returns a string object representing the head of the class definition without the { opening for the body

getFieldInfo() returns a string object containing the definition of a given field without a potential initialization value.

getConstructorInfo() returns a string object containing the definition of a given constructor, including parameters.


    public String decompile(Class<?> clazz) {
        StringBuilder stringBuilder = new StringBuilder(getClassInfo(clazz))
                .append("{");

        /* iterate over all constructors and add them to the output string */  

     

        /* iterate over all fields and add them to the output string */
       

        /* iterate over all methods and add them to the output string */



        stringBuilder.append("\n}");

     
        return stringBuilder.toString();
    }

    public String getClassInfo(Class<?> clazz) {
        StringBuilder stringBuilder = new StringBuilder();

        /* implement getClassInfo() */


        return stringBuilder.toString();
    }

    public String getFieldInfo(Field field) {
        StringBuilder stringBuilder = new StringBuilder();

        /* implement getFieldInfo() */



        return stringBuilder.toString();
    }

    public String getConstructorInfo(Constructor<?> constructor) {
        StringBuilder stringBuilder = new StringBuilder();

        /* implement getConstructorInfo() */


        /* return final string */
        return stringBuilder.toString();
    }

    public String getMethodInfo(Method method) {
        StringBuilder stringBuilder = new StringBuilder();

        /* implement getMethodInfo() */


        return stringBuilder.toString();
    }

}





Is it possible to access types from assemblies specified by CSharpCompilation.ExternalReferences?

I'm trying to write a source generator to remove boilerplate code in a project. The purpose of the project is to transpile existing unit tests of "solution" code to unit tests of "exercise" code. I'll give a short example below:

// The "solution" code
public void Name_InitializesAsNull() {
  Solutions.Person person = new Solutions.Person();
  Assert.IsNull(person.Name);
}

// The "exercise" code
public void Name_InitializesAsNull() {
  Exercises.Person person = new Exercise.Person();
  Assert.IsNull(person.Name);
}

In order to make this transpilation, I want to validate that the class Exercises.Person has a readable field or a property Name. I have previously done this through reflection, and would like to continue to do so.

So my question is: Is it possible to access type information, like MemberInfo, during source generation of types in the assemblies specified by CSharpCompilation.ExternalReferences?





How to define a global function inside a specific context via contextmanager and decorators

I am trying to create global functions that would only be accessible inside a specific context using both context managers and decorators. So far i have been able to implement something that looks like This (i have removed bits of code that are irelevant to the question):

Mod.py

def canUseFooBar(func):
    def wrapper():

       global Foo
       if "Foo" in globals():
          raise ValueError("Error: The user already defined the function Foo")
       else:
          def Foo():
             print("Global function Foo has been called")
       # The rest of the functions would be protected in the same way in order to protect accidental  overrides
       global Section
       @contextmanager
       def Section():

          global Bar
          def Bar():
             print("Global function Bar has been called")
          
          yield None
          del Bar

       func()
       del Foo
       del Section

    return wrapper

UserCode.py

import ModPackage.Mod as MOD

@canUseFooBar
def userFunction_01():
    # The function can use Foo
    # And Bar only inside a "Section"
    MOD.Foo()
    with MOD.Section():
       MOD.Bar()


def userFunction_02():
    # This function cannot use neither, Foo, Section() nor Bar()
    # It would raise a ValueError
    MOD.Foo()
    with MOD.Section():
       MOD.Bar()

This kinda looks like what i am trying to achive, however, what i would really like to do is something that would looke like this to the user:

UserCode.py

#Some import 

@canUseFooBar
def userFunction_01():
    Foo()
    with Section():
       Bar()

I am ok with having some functions in the global namespace because this feature is not designed to be used in a huge project but rather a very small scripting api where the user would only write one function.

Also, ultimately, the user would not even have to bother with decorators and imports as it will be requested from him to give the path to their scripts and the api will automaticaly decorate the functions and create the imports.





Robust way to check via reflection if extension method could be invoked on specific type

Is there any ready to use solution to check (via reflection) if this arg of extension method is compatible with a specific arbitrary type?

In cases where extension methods has simple types on this parameter, it is a trivial task, you could just invoke Type.IsAssignableTo(), and you done.

But, if this arg is something like this:

public static void ExtMethod<T, V, X>(this Dictionary<V, List<string>> arg)
    where V : IDictionary<List<X>, T>, new()
    where T : class, IDisposable

Such checking could become pretty hard to resolve. Of course my example doesn't look practical, but anything possible in this world, and tool which i am trying to make should be able to handle any ridiculous but valid (from C# point of view) constructions.

Task context

I am currently developing smart auto completion in .net oriented IDE-like tool. Something like intelli-sense in VS. And i need to provide user with extension methods which could be used on type which is in current context of completion popup. But, how to find all extension methods for this type, make me a good trouble, because i couldn't even see the way to build such matching algorithm.

I wonder if there any alternative ways to do this (with Cecil for example)?





vendredi 16 avril 2021

C# - How to set a value of a child of a field acquired by Refelctions

So, I have some objects (various types), that have another objects as fields (also various types). And that objects have let's say a float field. How can I set the last one, since I don't have that 'middle' object which reflection requires?

I'm getting it in that way:

FieldInfo field = foo.GetType().GetField(name1).FieldType.GetField(name2);

And here comes my problem:

field.SetValue(object_that_i_dont_have, float_value);





Using custom attributes to map values to a fully qualified type name

I am working on a .NET project that needs to take a plaintext value, and, given that value, instantiate a specific object type designed to store and work with it.

For example:

Say I am given a file containing the following three lines of text:

Role|Manager
Company|ComputerCompany
Age|27

Furthermore, I have defined the following class structure:

public abstract class Field()
{
    public string FieldDataType;
    public abstract void CustomBehavior();
}

public class StringField : Field
{
    public string value;
    
    public StringField ()
    {
        FieldDataType = "String";
    }
    // implement CustomBehavior() here
}

public class IntField : Field
{
    public int value;
    
    public IntField ()
    {
        FieldDataType = "Int";
    }
    // implement CustomBehavior() here
}
...

When my file parser reads in the line "Role|Manager" I want to use the text "Role" to create an instance of the StringField type using reflection and store the value "Manager" in it.

Similarly when I read in the line "Company|ComputerCompany" I want to use the text "Company" to create an instance of the StringField type, and when I read in the line "Age|27" I want to use the text "Age" create an instance of the IntField type.

Is there a way, perhaps using attributes, to map a known list of field names such as "Age" "Company" and "Role" to a set of custom qualified type names?





C# - How to reach grand child of class using reflection

public class A
{
   public B b { get; set;}
}
public class B
{
   public C c { get; set;}
}
public class C
{
   public string Name { get; set; }
}

I need to reach the value of C.Name dynamically using reflection. With my limited imagination I can only reach the second layer with the code below

 Type type = a.GetType();
 PropertyInfo[] properties = type.GetProperties();
 foreach (PropertyInfo property in properties)
 {
     var subObject = type.GetProperty(property.Name).GetValue(a); // this is b
     foreach (var subProperty in subObject.GetType().GetProperties())
     {
          var propertyValue = subProperty.GetValue(subObject);
     }
 }

What should be my next step?





How to create a function which accepts any template as a template parameter? [duplicate]

I need to find out whether a type is a template or not. To do this, I thought I would use two function overloads, like so:

template <typename T> // If T is a simple type this overload will be selected
consteval bool isTemplate(int) {
   return false;
}
template <template <class...> class T> // This overload will be selected if T is a template and fits in as a template template parameter
consteval bool isTemplate(char) { // Dummy char parameter to avoid redefinition
   return true;
}

However this doesn't work when T is a template with non-type template parameters, eg:

template <int N>
struct T {};
auto x = isTemplate<T>(0); // Error, second overload does not work

How do I make the second overload accept any template ? ( Or any alternative solution to detect whether a type is a template is welcome :)





Is there a way to recognise a Java 16 record's "main" constructor via reflection?

Assuming I have a record like this (or any other record):

record X(int i, int j) {
    X(int i) {
        this(i, 0);
    }
    X() {
        this(0, 0);
    }
    X(String i, String j) {
        this(Integer.parseInt(i), Integer.parseInt(j));
    }
}

Is there a way to find this record's "main" constructor, i.e. the one that is implicitly declared in the RecordHeader?





Java 9: 'opens' module for access by reflection not required?

The 'opens' keyword in the logic of Java modules allows reflective access (here). I've recently ported a complex JavaFX app. to Java 15 with success, but it was a nightmare because JavaFX is rightly based on reflective access. My question is about a more simple Java 15 application THAT PERFECTLY WORKS, but I expected a runtime error that DID NOT OCCUR! Why? Any highlight welcome... So, I have a very common client/server relationship between 2 modules as follows:

module PauWare2 {
exports com.pauware.pauware_engine.Core;
}
module My_device_module {
requires PauWare2;
}

One may observe that 'opens' IS NOT used in 'My_device_module'. In practice, PauWare2 accesses public methods by reflection:

    package My_device_package;
    public class My_device { // In 'My_device_module'
    public void a() {}
    com.pauware.pauware_engine.Core.AbstractStateMachine _My_device_state_machine; // PauWare2 reuse
    // Reflective access of 'a' method by '_My_device_state_machine'
    }

I expected a runtime error, which involves 'opens My_device_package to PauWare2;' in 'My_device_module'? However, as said, no problem at all... Any idea on that? THANKS in advance..





casting object to list of interface from a propertyinfo getvalue [duplicate]

interface blah 
{ 
  int status;
}
class B : blah
{
  public int status;
}
class A : blah 
{
  public int status;
  public List<B> items;
}

var the_a = new A() { items = new List<B>() { new B() { status = 5; } } };

// this gets passed around and eventually gets to a generic function
// that is trying to update status on the item and any children that might also have the interface blah

PropertyInfo pinfo = null; /* the PropertyInfo of items on class A */

// this function

private function update<T>(T data) where T : blah
{

 if (pinfo.PropertyType.IsGenericType && pinfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
 {
     // i now know my generic has a list, and that the list is of type List<blah>
     // however .net standard 2.0 doesn't allow casting as IList;
     // you have to pass a type
     // however it also wont allow cast to IList<blah>
     // how do a get either IList<blah> or even a list of objects
     // something i can loop through?
     var temp_object = pinfo.GetValue(data);
     // how does one iterate or cast this to a iterable list of interface blah?
 }
}



I need to edit the data of an interface on a property of a generic. The above code should show what im after, not exactly how i got to that point though. This question doesnt seem to answer it. C# casting the result of GetValue from PropertyInfo to a generic list





jeudi 15 avril 2021

In .NET 5.0 for bundled assemblies, the value returned is an empty string

Since .net 5, my method FileInfo _dataRoot = new FileInfo(typeof(Program).Assembly.Location); returns an empty string.

What alternative can I use to get the path to my file?

using System.IO;

namespace BlazorClient
{
public class PathUtilities
{
  public static string GetPathFromBinFolder(string relativePath)
  {
      FileInfo _dataRoot = new FileInfo(typeof(Program).Assembly.Location);
      string assemblyFolderPath = _dataRoot.Directory.FullName;
 
      string fullPath = Path.Combine(assemblyFolderPath, relativePath);
      return fullPath;
  }
}
}




mercredi 14 avril 2021

How to extract field from protobuf message without schema

According to this issue, the protoreflect package provides APIs for accessing the "unknown fields" of protobuf messages, but I don't see any way to use it if there isn't any existing schema. Basically, I want to perform a "weak decode", similar to what the JSON unmarshaller does if the output is of type map[string]interface{}.

The example from the documentation looks like this:

err := UnmarshalOptions{DiscardUnknown: true}.Unmarshal(b, m)

where b is the input byte slice and m is the output message, which needs to be initialised somehow, as you can see here. I was thinking that dynamicpb can be used for this purpose, but it doesn't look possible without having an existing MessageDescriptor and that's where I got stuck...





How to traverse an unknown object of type T hierarchy with reflection, get all the class types, then add them an EF core DbContext with C#?

I am developing a generic function to use with EF core, The important one is setAddedState, I am not really interested in an EF Core work arounds but in how to send a generic tree recursively to this statement:

 context.Entry(entity).State = EntityState.Added; 

where entity is recursively obtained from an unknown object, that may contains lists of other objects and direct object descendants:

        public async Task<T> CreateGraph(T entity) {
            using (AppDbContext context = _contextFactory.CreateDbContext()) {
            setAddedState(context, entity);
            }
           return entity;
        }
        // this method does not work:
        private void setAddedState(AppDbContext context, object entity) {
           // entity object is the root of the tree, contains many sub objects and List<OtherObjects>
            context.Entry(entity).State = EntityState.Added;
            Console.WriteLine("entry added");
           foreach (FieldInfo fieldInfo in entity.GetType().GetFields())
           {
               Console.WriteLine($"prop name: {fieldInfo.Name}, prop type: {fieldInfo.FieldType.ToString()}");
               if (fieldInfo.FieldType == typeof(List<>)){
                   foreach(var item in fieldInfo.getValue())
                   {  
                      setAddedState(context, entity);
                   }

               }
               setAddedState(context, fieldInfo.GetValue(entity));
           }
        }

The idea is to traverse the object graph tree from the root and add it to EF core context object manually, the pre assumption is that all sub objects are already added with DbSet to dbContext is OK. Graph of objects looks like:

Class1 c = new Class1(){ //root object is added
     Prop1 = new Class2() { ...}, //Class2 should be added to dbContext.
     Prop2 = new List<Class3>{ ...}, // each item in class3 list should be added to dbContext
     Prop3 = "string" // value type is not to be added ofcourse
}

The point is not just for EF Core, but how to make a totally generic function and extract types for use in similar examples like the addition for EF core.





Getting MethodInfo from a generated IEnumerator type

I'm trying to gather the attributes applied to an IEnumerator method based off an instance of the enumerator. For example:

static class Program {
    [SomeAttribute("Hello")]
    static IEnumerator Test() {
        yield return 1;
        yield return "x";
    }

    static void Main() {
        var foo = Test();
        // ... How to get the attribute from the 'foo' instance?
    }
}

foo.GetType() returns the generated type Program.<Test>d__4, so it seems to be somewhat aware of the method that generated it. How can I work backwards to find the MethodInfo of Test? From there I can get the attribute.

I also tried searching through the Program type, at each of it's methods' MethodInfo.ReturnType property to find one which returns Program.<Test>d__4. To my surprise, the MethodInfo I want just indicates a System.Collections.IEnumerator return type.

Maybe someone who understands the internals a little better can explain how I could get the MethodInfo from the generated type or vice versa.

Thanks.





.NET instantiate dynamically loaded type

Here is my current project structure and the problem it gives:

I have 2 different projects, project A (class library) and project B. Project A contains a class C that has a single constructor with a single parameter of type Microsoft.Extensions.Configuration.IConfiguration. In project B I dynamically load the assembly produced by project A. If I now want to instantiate the class C with a custom built Microsoft.Extensions.Configuration.IConfiguration object, it gives an ArgumentError, because the IConfiguration types are not the same and hence can not be converted to each other. This happens because the IConfigurations types come from the same assembly, but at a different location. (One is in A\bin\release\Microsoft.Extensions.Configuration.dll and the other in B\bin\release\Microsoft.Extensions.Configuration.dll)

Is there a way that I could set up the projects such that I can instantiate class C in project B, without a project reference to project A? (This dynamic assembly loading is a requirement that cannot be changed).

Edit: This is my first every StackOverflow post, so suggestions for posing the question better are welcome!





Java 16 Annotation ElementType.RECORD_COMPONENT cannot be reflected

Using JDK 16, I declared two annotations:

    @Target({ ElementType.RECORD_COMPONENT})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface A {}

    @Target({ ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface B {}

And I declared a record class like this:

public record User(@A @B long id, String name, int age) {}

Then I use reflection to fetch the annotations of id, which is:

Annotation[] annotations = fields[0].getAnnotations();

But the size of annotations is one and I only got @B, why is that? Thanks





Flutter: Convert String to class name during runtime

Is it possible to "convert" a String which is dynamically generated in my code, into a class name, e.g. to use the class name as a key in a Map that has variables for each of keys?

My code:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  // Suppose this is a dynamic list returned from a database query -
  // which for simplicity purposes is now "hard coded"
  final List<String> listFromDB = ['one', 'three', 'two'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
          itemCount: listFromDB.length,
          itemBuilder: (context, index) =>
              _listItemBuilder(context, index, listFromDB)),
    );
  }
}

Widget _listItemBuilder(BuildContext context, int index, List<String> list) {
  // suppose this is some map with translations of different languages. 
  final labels = Labels.translations['key'];

  final String key = list[index];
  // QUESTION: How can I use the above String key to "search" through the
  // AnyClass Map in order to return the corresponding value, e.g. "1" for the 
  // key "one"? How is it possible to "convert" a String into a key that can 
  // be used like so:  
  // print(labels.key) to return "1" if list[index] was "one"
  
  print(labels.key) // ERROR: Not compiling because key is a String


  return null;
}

// GENERATED: The below code can not be changed as it is generated

class Labels {
  static final Map<String, AnyClass> translations = {
    'key' : AnyClass(one: '1', two: '2', three: '3')
  };
}

class AnyClass {
  AnyClass({this.one, this.two, this.three});

  final String one;
  final String two;
  final String three;
}

I have read this old thread on GitHub on the same issue. But it seems there was no solution at that time. I also came across reflections in Dart but I am not sure whether they provide a solution in the above described case.

Thanks for any help and advice!





mardi 13 avril 2021

Using Reflection to access private unsafe pointer fields

Let there be the following class:

public class SomeClass
{
    private unsafe void* mPtr;
}

What is the proper way to access the value of mPtr using Reflection?

Here is how I'm trying to do it:

using System;

public class SomeClass
{
    private unsafe void* mPtr = (void*)42;
}

public class Program
{
    public static unsafe void Main()
    {
        System.Reflection.FieldInfo ptrFieldInfo = typeof(SomeClass).GetField("mPtr", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
        
        SomeClass obj = new SomeClass();
        
        void* ptr = System.Reflection.Pointer.Unbox(ptrFieldInfo.GetValue(obj));
        
        Console.WriteLine("ptr = " + (int)ptr);
    }
}

The expected output is: ptr = 42

But, running this I get System.NullReferenceException originating from System.Reflection.MonoField.GetValueInternal.

Am I encountering this Mono bug? If yes, is there a workaround? Or am I doing it wrong?





Get all classes that implement an interface and call a function in .NET Core

How can I get all classes that implements a specific interface then call a function of that class if a string member of the specific class matches a given one?

Basically what I have is a ICommandHandler interface:

interface ICommandHandler
{
    string Command { get; }
    Task ExecuteAsync();
}

and a class that implements it:

public class StartCommand : ICommandHandler
{

    public string Command { get => "start"; }
    public async Task ExecuteAsync()
    {
      // do something
    }
}

What I want to do is to get all the classes that implements the ICommandHandler interface, then verify if the class.Command equals a specific string and if it does then call the ExecuteAsync method.

I've tried using this answer here: https://stackoverflow.com/a/45382386/15306888 but the class.Command is always null





JavaFX-How to get the value of property?

Below is my tableview,including 3 columns. And each column is binded with one property of Classroom contained by ObservableList 'data'.

List<Classroom> classroomList = DayCare.getClassroomList();
ObservableList<Classroom> data= FXCollections.observableList(classroomList);
classroomIdCol.setCellValueFactory(new PropertyValueFactory<>("id"));
groupIdCol.setCellValueFactory(new PropertyValueFactory<>("groupId"));//This coulum shows the id of groups in each classroom
numberCol.setCellValueFactory(new PropertyValueFactory<>("curPerson"));
tableView.setItems(data);

Now I want to add tooltip only on column groupIdCol and when user put mouse on any cell in this column, the tooltip could show the specfic data of group(s) contained by that cell.I've found one method to add tooltip to certain column:

private void addTooltipToColumnCells(TableColumn<ObservableList<String>, String> column) {
        Callback<TableColumn<ObservableList<String>, String>, TableCell<ObservableList<String>, String>> existingCellFactory
                = column.getCellFactory();

        column.setCellFactory(c -> {
            TableCell<ObservableList<String>, String> cell = existingCellFactory.call(c);
            Tooltip tooltip = new Tooltip();
            tooltip.textProperty().bind(cell.itemProperty());//bind tooltip with property of cell
            cell.setTooltip(tooltip);
            return cell ;
        });
    }

However, I have trouble in getting the value of cell.itemProperty(). I need to get the value of each cell in groupId column(which is a String contains groupId) and I'll use the value to search the data of certain groups and then let tooltip to show the data. Is there any method to realize this function? Any help would be appreciated!

Below is my UI,however I could only let tooltip to show data of all groups instead of showing data of certain groups contained by each cell.

enter image description here





Print fields/methods annotated only with @Printable annotation

I have this assignment and I have no idea how to do it. The assignment is:

Create a Person class with properties – age, name, country. Create new Annotation @Printable. Implement a method that takes a list of Persons and print only the properties for each person annotated with @Printable annotation.





Java Record confusion with Annotations with fields vs parameters?

I spotted an oddity today testing out record support for my Persism ORM Library.

I have an annotation used for methods or fields defined like this:

@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.FIELD})
public @interface NotColumn {
}

I wanted to prevent users from using this on a record since it wouldn't make sense for this annotation to be used in that context. It seems doing this should not compile since I don't specify ElementType.PARAMETER as valid Target.

The following compiles fine though:

public record MyRecord(String customerId,
                       String companyName,
                       @NotColumn String description
}

But this form with a compact constructor

public record MyRecord(String customerId,
                       String companyName,
                       @NotColumn String description

   public MyRecord {
   }

}

Fails to compile with "java: annotation type not applicable to this kind of declaration" - which is actually what I would expect.





C#, assign internal delegate

I have this code in an external assembly:

internal class StylePropertyReader
{
    internal delegate int GetCursorIdFunction(StyleSheet sheet, StyleValueHandle handle);
    internal static GetCursorIdFunction getCursorIdFunc = null;
}

Where StyleSheet is a public type, StyleValueHandle is internal.

I would like to change the value of the getCursorIdFunc variable, something like this:

StylePropertyReader.getCursorIdFunc = myCustomMethod;

I think I can easly change its value through Reflection but I don't know how to declare my method in order to satisfy the internal delegate, since the second parameter type is inaccessible.

How do I deal with the second parameter? The ideal solution for me would be to simply use object as type:

static int myCustomMethod(StyleSheet sheet, object handle)




lundi 12 avril 2021

C# Reflection Type.GetField array

Im trying to read variable array from string and show it in console but each time I run the program Im getting error: "Object reference not set to an instance of an object." Can anyone suggest how to do this?

my code:

public class Positions
{
   public static string[] test = { "test", "test2" };
}

private void test()
{
   Positions pos = new Positions();

   Type type = typeof(Positions);
   FieldInfo fi = type.GetField("test[0]");

   Console.WriteLine(fi.GetValue(pos));
}




Mocking java.lang.Class getDeclaredMethod(String name, ...Class args) with Mockito not working

I am trying to mock the getDeclaredMethod on a java .class object of a certain defined java type:

AccessRulesMethods accessRulesMock = mock(AccessRulesMethods.class);
Method mockMethod = mock(Method.class);
when(accessRulesMock.getClass().getDeclaredMethod(param.getValue(), String.class, BigInteger.class)).thenReturn(mockMethod); 

but I get the following exception:

java.lang.NoSuchMethodException: myOwnPackage.AccessRulesMethods.methodName(java.lang.String, java.math.BigInteger)
at java.lang.Class.getDeclaredMethod(Class.java:2130)

Lokking into java.lang.Class at line 2130 it seems that the method is not mocked at all. I found in another discussion here that this is the correct way but with no examples... Anyone knows how can I manage to get what I need?

Thanks a lot, Saverio





How to reference a method parameter from lambda in C#

Given this lambda

public static Expression<Func<int, int>> Add(int add)
{
    return x => x + add;
}

it creates the following debug output:

.Lambda #Lambda1<System.Func`2[System.Int32,System.Int32]>(System.Int32 $x) {
    $x + .Constant<ConsoleAppExpressionTest.Program+<>c__DisplayClass1_0>(ConsoleAppExpressionTest.Program+<>c__DisplayClass1_0).add
}

The debug view shows that the field add is addressed within a constant.

How to create the same lambda dynamically?

What i've tried:

public static Expression<Func<int, int>> Add(int add)
{
    var x = Expression.Parameter(typeof(int), "x");
    var expr = Expression.Add(x, Expression.Field(Expression.Constant(null), "add"));

    return Expression.Lambda<Func<int, int>>(expr, x);
}

leads into a System.ArgumentException: 'Instance field 'add' is not defined for type 'System.Object''.

While using the parameter directly as constant would just create a copy of the value: Expression.Constant(add)





Java: How to read a private field value from another class without a getter

Can Someone help me with below code, I want to access/get the values of myConstraint from another Class?

public class myLegacyClass{

    private void methodOfInterest(){
        ValueConstraint myConstraint = new EnumerationConstraint( new int[] {1, 2, 3, 4, 5, 7, 9});
    }
}


public class myNewCode{

    public static void main(String[] args)
    {
      // read the value of myConstraint here ...
    }
}

how can I do it?

Note: I can not change my myLegacyClass and there are no getters and setters available for myConstraint





C# Reflection: Typedefinition.IsNested & Typedefinition.IsNestedFamily

Whats the difference between IsNested and IsNestedFamily ? In the Documentation of Typedefinition I only see IsNested. But according to InteliSense actually there are both Propertys on it.

enter image description here

I can only find IsNestedFamily in the Documentation for the class Type.

So my question:

Can anyone explain to me, the difference between these two Propertys on the Typedefinition class?





dimanche 11 avril 2021

How to get list of custom annotations declared in class

I have created custom annotations to get the list of classes which are having these markers on runtime (Working as expected).

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Marker {
  @interface Only{}
  @interface Marker1{}
  @interface Marker2{}
}

I need a mechanism to get the list of the markers declared in these test classes. Below is the code which I am trying to run to get these, but no luck!!

@Marker.Only
public class Sample {

    @Test
    public void main() {
        Assert.assertTrue(true);
    }

    @AfterMethod
    public void m2(ITestResult result) {
        Annotation[] acc = result.getMethod().getRealClass().getAnnotations();
        // Getting blank array as acc
        System.out.println(acc);
    }
}




Call variable length Java method using JNI

I am passing a callback java object to my JNI code, I need to call a method on it.

This can be achieved by using g_log_params.env->CallIntMethod(...).

The thing is, my Java function accepts variable length parameters.

void foo(String message, Object... args);

How do I call this method from my JNI code?





What are some techniques for making a surface reflective in OpenGL

I want to make a surface reflect stuff, like water does

I saw a neat technique that involved using a framebuffer object to get a texture of what's above the surface and then put that texture on the surface. This is overly simplified, but that's the gist of it.

My problem is that I'm using an fps-style camera. That technique seems to only work if the camera rotates around the centre of the surface. But, if I go and look at an object at the edge of the surface, that's going to be in the middle of the texture and the effect will be completely wrong.

So... yeah... Are there any techniques that would allow me to make a surface reflect stuff, given my choice of camera controls?





TypeTest to overcome erasure with generic types in scala3

I am having problems understanding how TypeTests in scala3 can replace the use of TypeTag in scala 2. The usecase being able to match on a generic parameter like x: List[Int].

Concrete example I am trying to solve:

enum Foo :
  case Bar()
  case Baz()

case class Mod[T <: Foo](modFn: T => T)

def modifyBarsOrBaz(mod: Mod[_]) = mod match
  case barMod: Mod[Foo.Bar] => ???
  case bazMod: Mod[Foo.Baz] => ???

the compilation results (as expected) in the comiler warning(s)

the type test for Mod[Foo.Bar] cannot be checked at runtime and an unreachable case.

Now my question is: is this possible to do at all in scala3?

I was under the impression that I would somehow have to provide a TypeTest[Any, Mod[Foo.X]] for all X which are subclasses of the Foo enum.

But I am struggling to even implement those tests, as well as understanding what using parameter the modifyBarsOrBaz is required for this to work.

Thus I came up with the following (not working) solution:

def modifyBarsOrBaz[T <: Foo](mod: Mod[T])(using TypeTest[Any, Mod[T]]) = mod match
  case barMod: Mod[Foo.Bar] => ???
  case bazMod: Mod[Foo.Baz] => ???

and a naive tt implementation as such

val tt: TypeTest[Any, Mod[Foo.Bar]] =
  new TypeTest[Any, Mod[Foo.Bar]] :
    def unapply(x: Any): Option[x.type & Mod[Foo.Bar]] = x match
      case m: Mod[_] => ??? // what to do here? use a classtag on Mod?

I tried to search the web for answers, but since this is pretty new I was not lucky. Any hints?





samedi 10 avril 2021

Get method with an 'in' parameter through reflection

Imagine the following scenario, in which you would want to get the MethodInfo of the first method:

public class Foo
{
    public void Bar(in int value)
    {
    }

    public void Bar(string value)
    {
    }
}

If we would now look at the output of typeof(Foo).GetMethods(BindingFlags.Public | BindingFlags.Instance):

MethodInfo[6] { [Void Bar(Int32 ByRef)], [Void Bar(System.String)], [Boolean Equals(System.Object)], [Int32 GetHashCode()], [System.Type GetType()], [System.String ToString()] }

You can see that the first method, the one which we want to get the MethodInfo of, it says Int32 ByRef which is not the same as the Int32 type. I obvisously tried the following, but without any success:

typeof(Foo).GetMethod("Bar", BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(int) }, null)

I took at a closer look at the actual parameter with the following code:

typeof(Foo).GetMethods(BindingFlags.Public | BindingFlags.Instance)[0].GetParameters()[0]

Which outputs [Int32& value], which seems like a pointer of the the value type. So is there any way to get the Int32& type at runtime? Something along the lines of typeof(Int32&)?





get access from static class by general name

I have a static class StaticDataValues. In this class I instantiate my value classes:

public static class StaticDataValues
{
    public static Floor Floor = new Floor ();
    public static Kitchen Kitchen = new Kitchen ();
}

In other classes (e.g. in a WPF UserControl) I want to use (e.g.) Kitchen.

private void InitializeEventNotifications()
{
    StaticDataValues.Kitchen.Raffstore.ElementAt(this.ID).Status.ValueChanged += (s, e) =>
    {
        var value = s as Home.Automation.Beckhoff.VarModel.VarItemBool;

        if (value != null)
        {
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background,
                new Action(() => this.ButtonAuto.Button.IsCheckedvalue.Value));
        }
    };
}

How can I change this Kitchen to Floor dynamically (over a property)? Is this possible?





Access an Object's field values in Java - cannot access a member of class java.lang.IllegalAccessException

I'm trying to use generics to access the field of an object.

For example, if I have an object called myObject and I know that most of its fields are of the data type float. So when I call this function getFieldValuesFloat(myObject, new String[]{"id"});

Then I got this error:

java.lang.IllegalAccessException: class se.danielmartensson.tools.GetClassInformation cannot access a member of class se.danielmartensson.entities.LX_Current with modifiers "private"

Here is the code I have problems with:

public static <T> Float[] getFieldValuesFloat(T object, String[] avoidTheseFields) {
    String[] fieldNames = getFieldNames(object, avoidTheseFields);
    Float[] fieldValues = new Float[fieldNames.length];
    int i = 0;
    for(String fieldName : fieldNames) {
        try {
            Field field = object.getClass().getDeclaredField(fieldName);
            fieldValues[i] = field.getFloat(object);
            i++;
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return fieldValues;
}

And the error focusing on this code row:

fieldValues[i] = field.getFloat(object);

This is weird, because I'm using this method to get the field names. And that method works. It also using generics, but instead, I'm reading the field names only from an object.

public static <T> String[] getFieldNames(T object, String[] avoidTheseFields) {
    Field[] fields = object.getClass().getDeclaredFields();
    String[] fieldNames = new String[fields.length - avoidTheseFields.length];
    List<String> avoidTheseNamesList = Arrays.asList(avoidTheseFields);
    int i = 0;
    for(Field field : fields) {
        String fieldName = field.getName();
        if(avoidTheseNamesList.contains(fieldName))
            continue;
        fieldNames[i] = fieldName;
        i++;
    }
    return fieldNames;
}

Question:

How can I get all values from an arbitary class using generics?





Java: Abstract generic data context class

I would like to store all application data in a data context class.

Having application data classes A and B implementing IApplicationData, the non-abstract, non-generic version could look like this:

NonGenericDataContext

private List<A> aList;
private List<B> bList;

public List<A>getAs() {
    return aList;
}

public List<B>getBs() {
    return bList;
}

Now I would like to abstract from the concrete application classes and use a generic data context to use common functionality in multiple applications. The data context class could then look like this:

AbstractGenericDataContext

protected Map<Class<? extends IApplicationData>, List<? extends IApplicationData>> listsByType;

public List<? extends IApplicationData> getListByType(Class<? extends IApplicationData> clazz) {
    return objectListsByType.get(clazz);
}

I would love to use proper generics, but Java erases the type during compilation, hence the construct with Class. Unfortunately, the construct above makes the code cumbersome and return values of getListByType() need to be casted.

Question How could the code be improved to achieve an abstract, generic (not necessarily in a JLS sense, but with similar usability) data context class?

I would like stick with a pure Java solution (so no code generators if possible). Reflection would be ok if it does not slow down data access in a critical way.





How does MethodHandles.Lookup.findSpecial(Class?> refc, String name, MethodType type, Class?> specialCaller) work? like invokespecial

Please see the code

public class TestMethodHandle {

    class G {
        void thinking(){
            System.out.println("im G");
        }
    }

    class F extends G {
        @Override
        void thinking(){
            System.out.println("im F");
        }
    }

    class S extends F {
        @Override
        void thinking(){

            MethodType methodType = MethodType.methodType(void.class);
            try {
                Field impl_lookup = MethodHandles.Lookup.class.getDeclaredField("IMPL_LOOKUP");
                impl_lookup.setAccessible(true);
                MethodHandles.Lookup IMPL_LOOKUP = (MethodHandles.Lookup)impl_lookup.get(null);
                MethodHandle mh = IMPL_LOOKUP.findSpecial(G.class , "thinking", methodType, G.class);//Please note here
                mh.invoke(this);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }

        }
    }

    public static void main(String[] args) {
        new TestMethodHandle().new S().thinking();
    }

} 

Run it

im G

If I change the code:

MethodHandle mh = IMPL_LOOKUP.findSpecial(G.class , "thinking", methodType, F.class);
// im G

or

MethodHandle mh = IMPL_LOOKUP.findSpecial(G.class , "thinking", methodType, S.class);
// im F

or

MethodHandle mh = IMPL_LOOKUP.findSpecial(F.class , "thinking", methodType, S.class);
// im F

I know it has the same effect as invokespecial, How does it implemented?





vendredi 9 avril 2021

how to use linq dynamic select based on type

I have below class mechanicalData like

public class MechanicalData
{
    public List<LibraryLighting> InternalLoadsLighting { get; set; }
    public List<LibraryEquipment> InternalLoadsEquipment { get; set; }
}

and then i am mapping the fields and forming a list object like as below

private static MechanicalData TransformMechanicalData(MechanicalData sourceMechanicalData, Dictionary<string, MasterSection> masterSectionMappedLibrary)
{
    return new MechanicalData()
    {
        InternalLoadsLighting = sourceMechanicalData.InternalLoadsLighting
                               .Where(a => a != null)
                               .Select(libraryLighting => new LibraryLighting
        {
            Id = libraryLighting.Id,
            IsApproved = true,
            Revision = libraryLighting.Revision,
            MasterSection = masterSectionMappedLibrary["Library Lighting"],
            SourceOfDataId = libraryLighting.SourceOfData.Id,
            LightingDensity = libraryLighting.LightingDensity
            .....
        }).ToList() ?? new(),

        InternalLoadsEquipment = sourceMechanicalData.InternalLoadsEquipment
                                 .Where(a => a != null)
                                 .Select(libraryEquipment => new LibraryEquipment
        {
            MasterSection = masterSectionMappedLibrary["Library Equipment"],
            SourceOfData = libraryEquipment.SourceOfData,
            EquipmentDensity = libraryEquipment.EquipmentDensity,
            Id = libraryEquipment.Id,
            IsApproved = true,
            Revision = libraryEquipment.Revision,
            ......
            ....
        }).ToList() ?? new(),
     }
 }

Is there any way i can apply dynamic type to simplify the above values assign or any suggestion with linq dynamic select query using reflection method that would be very grateful to me, TIA.





Class

In the past, you were able to use

Class<?> type = (Class<?>) ((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];

to get the type arguments of your class.

But now, in Java 15, it throws ClassCastException because getGenericSuperclass is not of type ParemeterizedType.





Cast to Type with reflection without generic argument

I have an issue which involves casting to different Types

I have a class which is a wrapper, which contains an inner wrapper which contains T here is the structure:

public class Wrapper
{
    public readonly Guid Foo;

    public Wrapper(Guid foo)
    {
        Foo = foo;
    }
}

public class Wrapper<T> : Wrapper
{
    public readonly InnerWrapper<T> InnerWrapper;

    public Wrapper(Guid foo, InnerWrapper<T> innerWrapper) 
        : base(foo)
    {
        InnerWrapper = innerWrapper;
    }
}

public class InnerWrapper<T> 
{
    public readonly Guid Bar;
    public readonly T Content;
    public InnerWrapper(T content, Guid bar)
    {
        Content = content;
        Bar = bar;
    }
}

In another part of the code I have a List<Wrapper>. notice that is a list of wrapper not a list of wrapper<T> which means that T can be any class. when this translates is expected to have something like

{
    wrapper<Class1>,
    wrapper<Class2>
}

and so on.

At some point in the code there is a "helper class" which contains the object as object type and the Type

public class Helper
{
    public readonly object Obj;
    public readonly Type Type;

    public Helper(object obj, Type type)
    {
        Obj = obj;
        Type = type;
    }
}

And here is where my problem begins, I created a helper method to convert from List<Helper> to List<Wrapper> and it does it, but the inner object is type object instead of being the actual type.

And i have no clue of how to convert from object to the actual type without using generics, and as T can be multiples types I cannot use them.

This is the helper classs

public static class HelperExtensions
{
    public static T CastTo<T>(this object o) => (T)o;

    public static List<Wrapper> ToWrapper(this IEnumerable<Helper> helperList)
    {
        List<Wrapper> wrapperResponseList = new List<Wrapper>();
        foreach (var help in helperList)
        {
            // doesn't work either var typedValue = Convert.ChangeType(help.Obj, help.Type);

            var methodInfo = typeof(HelperExtensions).GetMethod(nameof(CastTo), BindingFlags.Static | BindingFlags.Public);
            var genericArguments = new[] { help.Type };
            var genericMethodInfo = methodInfo?.MakeGenericMethod(genericArguments);
            var typedValue = genericMethodInfo?.Invoke(null, new[] { help.Obj });

            var wrapper = typedValue.BuildWrapper(Guid.NewGuid(), Guid.NewGuid());

            wrapperResponseList.Add(wrapper);
        }

        return wrapperResponseList;
    }


    //This one called individually does the work properly
    public static Wrapper<T> BuildWrapper<T>(this T obj, Guid foo, Guid bar)
    {
        InnerWrapper<T> inner = new InnerWrapper<T>(obj, bar);
        return new Wrapper<T>(foo, inner);
    }

}

to show the code here I also Created a test class

public class Placeholder
{
    public Guid Value { get; }

    public Placeholder(Guid value)
    {
        Value = value;
    }
}

so when I call

Placeholder placeholder = new Placeholder(Guid.NewGuid());
Helper helper1 = new Helper(placeholder, placeholder.GetType());
var result = new List<Helper> { helper1 }.ToWrapper();

It generates a List<Wrapper> but instead of wrapper<T> it is generating Wrapper<Object>

Any idea how can I cast it properly?

I also created a fiddle https://dotnetfiddle.net/pz3JDz which contains all the needed code to test.

Thanks In advance for your help.





Action method in c#

I just want him to give me what has changed at the entrance. When I want to get the same value to the input of the select method, I want to get the same values in the action output, not the whole properties class WeatherForecast.

 public class WeatherForecast
{
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    public string Summary { get; set; }
}


 public void method(){
        Select(d=>
        {
            d.Summary = "dasd";
            d.TemperatureC = 25;
        });}

 private void Select(Action<WeatherForecast> func)
    {
        var result = new WeatherForecast();
     
        func(result);
        foreach (var item in result.GetType().GetProperties())
        {
            RaisePropertyChanged(item.Name);
        }
        var ss = func;
        
    }

'''





Can I set multiple List Item property values with Reflection?

In continuation to: Can I set a property value with Reflection?, I have a challenge-

class Student
{
    public string Name { get; set; }
    public List<ListItem> Courses { get; set; }
}

List Selections has 2 Items 1.

{
Text = 'Business Management', Value = 'Course 1', Selected = 'true'
}
    {
    Text = 'Network Management', Value = 'Course 2', Selected = 'false'
    }
    

    How do I assign the Selections to Courses property of the Student class?





    Check if .NET assembly was compiled with overflow/underflow checking

    Is there a way to determine whether a .NET assembly was compiled with or without overflow/underflow checking (i.e. the CheckForOverflowUnderflow build property or /checked+ or /checked- flag) by examining that assembly through Reflection or running some command-line tool or similar?





    jeudi 8 avril 2021

    how to update a map value by reflection

    I encountered a problem, I expect to make a general method to update the value in the map, as in the below example:

    Code In Answers1

    The expected output result is:

    inner: map[0:map[name:test]]
    outer: map[0:map[name:test]]
    inner: map[0:map[age:1]]
    outer: map[0:map[age:1]]
    

    But the actual output is:

    outer: map[]
    outer: map[]
    

    How can I achieve the expected output?





    Reflect Value.Interface() panic: bad indir on CGo type after v1.15.4

    I'm using a C Library called GEOS which provides a C-backed implementation for handling Geometric operations. A struct containing this C type was used during some reflection operations, but upon upgrading to Go v1.15.4 (Or any version after) this results in a panic.

    I've isolated the problem, and it appears that when using a reflect Type to create a new reflect Value, a subsequent call of Interface() results in the panic: bad indir:

    var test *C.GEOSGeometry
    
    reflectType := reflect.ValueOf(test).Type().Elem()
    value := reflect.New(reflectType)
    
    // Panics in 1.15.4+
    value.Interface()
    

    The actual panic comes from within func packEface inside reflect/value.go where the following occurs:

    switch {
        case ifaceIndir(t):
            if v.flag&flagIndir == 0 {   // here v.flag = 22 and flagIndir = 128
                panic("bad indir")
            }
            ...
    

    Does it appear that something I'm doing is incorrect here, or is it more likely that this was a bug introduced in 1.15.4?





    How to convert user entered text into C# code

    I have a HTML input in my web app, where the user can enter some sort of filter criteria:

    Type='Person' && Name='Bob' && Hobby='Reading'

    Say I have a C# classes:

    public abstract class Something {
     public string Type { get; set; }
    }
    
    public class Person:Something  {
     public string Name { get; set; }
     public string Hobby { get; set; }
    }
    
    public class Animal:Something  {
     public string Breed { get; set; }
     public string Color { get; set; }
    }
    

    Then I have some sort of Processor method:

    Process(Something obj) {
      // use the user text to decide what to do
    }
    

    How would I:

    1. Go about parsing the user entered text, to indicate if it is valid or invalid?
    2. Map the entered text into my incoming object in Process?

    Thanks.