mercredi 31 mai 2023

DynamicForm Component that takes Generic Model Class as Parameter to Generate EditForm

I have a component called DynamicForm which accepts couple of Parameters including Generic Model Class.

@typeparam TModel

<EditForm Model="@Model" OnValidSubmit="@HandleFormSubmit">
    @foreach (var property in typeof(TModel).GetProperties())
    {
        @if (property.PropertyType == typeof(string))
        {
            <input class="form-control" id="@property.Name" @bind="@property.GetValue(Model)" />
        }
        else if (property.PropertyType == typeof(DateTime))
        {
            <input type="date" class="form-control" id="@property.Name" @bind="@property.GetValue(Model)" />
        }
    }

    <button type="submit" class="btn btn-primary">Submit</button>
</EditForm>

@code {
    [Parameter]
    public TModel Model { get; set; }

    [Parameter]
    public EventCallback<TModel> OnValidSubmit { get; set; }

    private Task HandleFormSubmit()
    {
        return OnValidSubmit.InvokeAsync(Model);
    }
}

what I am trying to achive is to generate Dynamic EditForm (Controls) based on Provided Model Class using following code

<DynamicForm TModel="FormModel" Model="@person" OnValidSubmit="HandleFormSubmit" />

@code {
    private FormModel person = new FormModel();

    private void HandleFormSubmit(FormModel model)
    {
        //Todo
    }
}

But I am getting following compile time errors on @bind="@property.GetValue(Model)"

  • Error (active) CS0131 The left-hand side of an assignment must be a variable, property or indexer
  • Error (active) CS1503 Argument 1: cannot convert from 'object' to 'System.DateTime'




mardi 30 mai 2023

In .NET 6.0/7.0, how to load an assembly and then delete the assembly file?

In .NET 6.0, I loaded an assembly and invoked its methods and properties using reflection, then tried to delete the assembly file:

    var dllFilePath = @"C:\Users\frank\source\repos\.NET core\MyDll\bin\Debug\net6.0\MyDll.dll";
    var ctx = new AssemblyLoadContext(null, isCollectible: true);
    var assembly = ctx.LoadFromAssemblyPath(dllFilePath);
    var myType = assembly.GetType("MyDll.MyClass");
    var instance = Activator.CreateInstance(myType, new object[] { }, null);
    var myMethod = myType.GetMethod("GetGuidText");
    var res = myMethod.Invoke(instance, new object[] { Guid.NewGuid() });

    ctx.Unload();
    myType = null;
    instance = null;
    myMethod = null;
    ctx = null;
    assembly = null;

    GC.Collect();
    GC.WaitForPendingFinalizers();
    Thread.Sleep(2000);
    GC.Collect();
    GC.WaitForPendingFinalizers();

    File.Delete(dllFilePath);

The attempt to delete threw exception:

System.UnauthorizedAccessException: 'Access to the path 'C:\...\MyDll\bin\Debug\net6.0\MyDll.dll' is denied.'

How do I delete this file without having to restart the app?





lundi 29 mai 2023

Use of ReflectionTestUtils.setField() in Junit testing to set a List of objects

in my implementation , i have

List<recordEntity> entityList = service.mapper(parameter1,parameter2);

i need to set the value for this entityList with a static value for my unit testing, i know that using ReflectionsTestUtils we can set value, even i have used this for another scenaro,

ReflectionTestUtils.setField(classObject, "implementations", Collections.singletonMap("mapper", new DTOMapper()));

but am not sure how to set a list





how to edit method annotation attributes on runtime in springboot project?

how to edit method annotation attributes on runtime in springboot project? i've known there's a way to edit by using reflection like invocationHandler.getClass().getDeclaredField("memberValues"); but in the newer springboot environment it doesn't work, cause the invocationHandler that i got is not the instance of AnnotationInvocationHandler but the instance of SynthesizedMergedAnnotationInvocationHandler, in SynthesizedMergedAnnotationInvocationHandler i cant find the method that let me change the value of the annotation fields on the fly,thx in advance

i'm trying to reused the way that worked in old version just like:


InvocationHandler invocationHandler = Proxy.getInvocationHandler(rateLimit);
Field field = invocationHandler.getClass().getDeclaredField("memberValues");
field.setAccessible(true);
Map params = (Map)field.get(invocationHandler);
params.put("fields1",xxx);

but there's no fields called 'memberValues'





dimanche 28 mai 2023

C# Assembly Resolve Context problems

I'm loading an Assembly that references to TPL.DataFlow library and I was having problems because TPL.DataFlow dll was not loading. As I have read in Microsoft Documentation when using Assembly.LoadFrom() the folder of the assembly is taking in consideration in the Assembly Load Context.

I have solved the problem using the AssemblyResolve event but it's extrange that in debugging I have seen that the if (assembly == null) condition is not reached, so the assembly was loaded in context but not resolved.

Even that I have solved the problem I was surprised about that and that is why I'm asking about AssemblyResolve context

public static IService LoadService(CtorParameters parameters)
{
    AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
        CurrentDomain_AssemblyResolve(sender, args, parameters.DllLocation);
    try
    {
        var assembly = Assembly.LoadFrom(parameters.DllLocation);
        var serviceType = assembly.GetType(SERVICE_TYPE);
        var serialPortInstance = (IService)Activator.CreateInstance(serviceType, parameters);
        return serialPortInstance;
    }
    finally
    {
        AppDomain.CurrentDomain.AssemblyResolve -= (sender, args) =>
            CurrentDomain_AssemblyResolve(sender, args, parameters.DllLocation);
    }
}

private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args, string loadedAssemblyPath)
{
    var appDomain = (AppDomain)sender;
    if (args.RequestingAssembly == null)
    {
        try
        {
            var assemblyName = new AssemblyName(args.Name);
            var assembly = appDomain.GetAssemblies().FirstOrDefault(m => m.GetName().Name == assemblyName.Name);
            if (assembly == null)
            {
                var loadedDllDir = Path.GetDirectoryName(loadedAssemblyPath);
                var dllPath = Path.Combine(loadedDllDir, $"{assemblyName}.dll");
                assembly = Assembly.LoadFrom(dllPath);
            }
            return assembly;
        }
        catch { }        
    }
    return args.RequestingAssembly;
}




vendredi 26 mai 2023

Retrieving whole C# class implementation as a string in code [duplicate]

How to retrieve whole class in C# as a string.

What I mean by that is:

This is my class

public class MyClass
{
    public int MyProperty { get; set; }

    public void MyMethod()
    {
        Console.WriteLine("Inside MyMethod");
        Console.WriteLine("Hello, World!");
        Console.ReadLine();
    }
}

And I would like to output this implementation as a string.

Console.WriteLine(MyClassString)

Expected result:

"""public class MyClass
{
    public int MyProperty { get; set; }

    public void MyMethod()
    {
        Console.WriteLine("Inside MyMethod");
        Console.WriteLine("Hello, World!");
        Console.ReadLine();
    }
}"""




System.InvalidProgramException Common Language Runtime detected an invalid program for Reflection

System.InvalidProgramException : Common Language Runtime detected an invalid program. Seeing this error message whilst trying to check the expression's correctness and if it is the correct IL.

The expression is "DateTimeA.GetType().Name", where we expect the result to be a string i.e. "String;DateTimeA.GetType().Name;String".

This is an example from "ValidExpressions.txt" using mparlak's "Flee" (see https://github.com/mparlak/Flee/blob/master/src/Flee/).

For some reason, the code is failing on that specific expression. I've checked what the emitted ops are and it goes as follows...

ldarg.0
ldfld
callvirt
callvirt
ret

length 17

I've run the test on the Flee library (as the .txt file was in the tests but the test was previously removed), and it fails with this error. Not entirely sure how to resolve it... I expect this test to pass with no problems but it appears that the "GetType()" method specifically is causing problems and I'm not sure why...





jeudi 25 mai 2023

How to Fix Loading Issues in Unity Reflect and Correct Red/Blue Box Errors?

red boxes around objects and they wont load in correctly and some stay blue and never load.. i have tried exporting it again and to different projects locally and on the cloud.

I in in the eastern us area and have tried on mobile and on different computers and still get the same issues also tried clearing the cache.

trying to get it to load.





mercredi 24 mai 2023

Spring find custom annotations at startup and get method for posterior execution

using spring boot how could I:

  1. find all beans methods annoted with a custom annotation at application startup, then
  2. store this methods references into a map in a service, then
  3. call this service to execute the stored bens methods?




mardi 23 mai 2023

Get properties types of Class.Type in Swift

I want to retrieve all classes that confirm specific protocol

protocol Service: NSObject {}

and then build a dictionary

[ClassName: [String array of property types]].

I managed to retrieve all classes using obj c reflection:

    private static func allClasses<R>() -> [R] {
        var count: UInt32 = 0
        let classListPtr = objc_copyClassList(&count)
        defer {
            free(UnsafeMutableRawPointer(classListPtr))
        }
        let classListBuffer = UnsafeBufferPointer(start: classListPtr, count: Int(count))

        return classListBuffer.compactMap { $0 as? R }
    }

But I have problems with retrieving property types of services. From what I see Swift API requires object to get that info

Mirror(reflecting: obj).children

and even tho my protocol requires NSOject I don't want to create object just to retrieve properties. Is there any other way to achieve it? From what I saw there is obj-c method class_copyPropertyList but you can only retrieve name and attributes with that, and you still need the object to get property types.





lundi 22 mai 2023

How to get interface implementation type for currently executing method?

I have an interface with several implementations. The implementations and interface method call are in different packages if that matters. I'm trying to catch the exception that may occur during the method execution and log it with the implementation name after the method call. The implementation name is used in logs to differentiate in timeseries.a

try
{
    await _provider.Method();
    //_provider is declared as interface
}
catch (Exception e)
{
    //here I'm planning to log things including implementation that threw the error
    throw;
}

Is there a way to find interface implementation class that is executing the method in question without applying some regex to stack trace or modifying method in question for each implementation?

I tried using reflection and method info, but am only getting either all implementations or just interface information.





vendredi 19 mai 2023

How to fill current object (this) by another object

I need to copy all properties from another object to curren object (this) in Kotlin. object.copy() is not solution because i can't use it on curren instance of class. Maybe by reflection. In c# it looks like this:

public virtual void fillFromObject(object obj){
    foreach (var property in this.GetType().GetProperties().ToList())
    {
        if (property.GetSetMethod() != null)
            property.SetValue(this, obj.GetType().GetProperty(property.Name).GetValue(obj, null), null);
    }
}

using:

this.fillFromObject(anotherObject);




jeudi 18 mai 2023

How to access the values of a data class in Kotlin?

Here's the codes that is working:

data class Abc(
    val a: String,
    val b: String,
    val c: String,
    val d: D
) {
    data class D(
        val e: String,
        val f: String,
        val g: String
    )
}

fun main() {
    val xx = Abc("a1", "b2", "c3", Abc.D("e4", "f5", "g6"))
    xx::class.memberProperties.forEach {
        if (it.returnType.classifier == String::class) {
            println("${it.name} is a String -> ${it.returnType.classifier == String::class} ")
        }
    }
}

And the output is this:

a is a String -> true 
b is a String -> true 
c is a String -> true 

Now I would like to access the values of each String members and make the output look like this instead:

a is a String -> true -> and the value is a1 
b is a String -> true -> and the value is b2 
c is a String -> true -> and the value is c3 

How should I change the println line? Intuitively I have tried something like:

println("${it.name} is a String -> ${it.returnType.classifier == String::class} -> and the value is ${xx.get(it)}")

but it didn't work ...





mercredi 17 mai 2023

C# Entity member type as field of class (EF Core and DLinq)

apologies if I'm not making much sense, I don't know if the thing I am aiming to achieve exists or not.

I am using EF Core for my backend API and I have a bunch of entities, sample below:

public class EntityOne {
    public int Id { get; set; }
    public string Name { get; set; }
    public string Age { get; set; }
    ...
}

I also have a generic pagination and filtering function that takes in a custom configuration per field:

public class FilterConfiguration
        {
            public string FieldName { get; set; } // Name of the field from frontend
            public string PropertyName { get; set; } // The corresponding field on the entity/list
            public FilterType FilterType { get; set; } // Type of filter
            public OperationType OperationType { get; set; } // Type of operation

            public FilterConfiguration(string fieldName, string propertyName, FilterType filterType, OperationType operationType)
            {
                FieldName = fieldName;
                PropertyName = propertyName;
                FilterType = filterType;
                OperationType = operationType;
            }
        }

Making use of this configuration looks something like the following:

new FilterConfiguration("ID", nameof(EntityOne.Id), FilterType.Integer, OperationType.Equals)

The above configuration can be interpreted as the user has entered a Value for the ID field on the frontend to filter by, the field on the frontend is called ID, the corresponding entity field is EntityOne.Id, the value type is integer and the operationtype is equals (in a nutshell, filter all data in said table where the id is 5). Using the nameof keyword works fine as I am able to take that and place it into a DLinq query for the data. What I was wondering is if the "nameof(EntityOne.Id)" can be replaced with just "EntityOne.Id". If possible, what will the FilterConfiguration class look like?

Tried looking for multiple solutions on the internet but coming up empty. Not sure if what i am looking for is possible.





Dynamic computations in Rust

I want to develop a desktop app that allows user to describe a data-flow diagram with nodes and run it. Similar to node-based system in Blender, but more of general-purpose, data passing from node to node can be any type.

My main concern is how can I use Rust to declare new nodes so that node describes its inputs and outputs and when such node-graph is executed data can be passed from node to node in a type-safe manner.

In C# I can easily achieve this by simply inspecting any static function. Use reflection to get info about its arguments and dynamically pass out arguments from other functions to input arguments of the function.

For now it seems to me like Rust simply is a bad choice for such problems. Am I missing something? Can I solve this problem with Rust in an efficient manner?





mardi 16 mai 2023

Build getters and setters lambdas to avoid using reflection in c#

I am validating a lot of complex objects in my applications. For example:

public class School{
   public string Name {get;set;}
   public DateTime DateCreated {get;set;}
   public List<Person > Students {get;set;}
   public Dictionary<string, Teacher> Teachers {get;set;}
   ...
}
public abstract class Human
{...}
public class Person : Human
{...}
public class Student : Person 
{...}
public class Teacher: Person 
{...}

I validate that objects properties do not contain null values for example and also that string values are not to long using recursion and reflection like this:

foreach(var propInfo in myObj.GetType().getProperties())
{
    // if property info is of type string and null throw error
    
    // if dictionary analyze dictionar..
    // if list iterate over items on list..

    if(propInfo.PropertyType.IsClass)
       // recursive call..
}

I will like to speed things up on validation by analyzing all types when my program starts and storing all the information about each type. Also for each type I will like to build a getter and setter functions. In other words the getter will be of type Func<object, object>.

For example lets say I have an object of type School named school and I want to get the name. If I where to do:

var propertyInfo = typeof(School).GetProperty("Name");
var retrivedValue = propertyInfo.GetValue(school,null);

that will be 100 times slower than if I where to have this lambda:

Func<object, object> myGetter = (Object obj) => ((School)obj).Name;
var retrivedValue = myGetter(school); // 100 times faster!

I am able to build that getter lambda like this:

// Getter
private static Func<object, object> buildGetter(Type type, string propertyName)
{
    // Create a parameter for the lambda expression (the input to the function)
    ParameterExpression paramExpression = Expression.Parameter(typeof(object), "x");

    // Add a conversion to Person
    UnaryExpression convertExpression = Expression.Convert(paramExpression, type);

    // Get the property info for "FirstName"
    var propInfo = type.GetProperty(propertyName);
    if (propInfo is null)
    {
        if (Debugger.IsAttached)
            Debugger.Break();
        throw new Exception($"Property {propertyName} does not exist on type {type.Name}");
    }

    // Create an expression to get the property value
    MemberExpression propExpression = Expression.Property(convertExpression, propInfo);

    // Add another conversion to object for the return value
    UnaryExpression resultExpression = Expression.Convert(propExpression, typeof(object));

    // Create the lambda expression
    LambdaExpression lambdaExpression = Expression.Lambda(resultExpression, paramExpression);

    // Compile the lambda expression to get a delegate
    Func<object, object> func = (Func<object, object>)lambdaExpression.Compile();

    return func;
}

// And I can get the name of the school super fast like this

// this will be slow to build but if stored on memory it is suppert fast 
Func<object, object> myGetterBuilt = buildGetter(Typeof(School),"Name");
var retrivedValue = myGetterBuilt(school); // 100 times faster!

I am having trouble building the setter function. I need the setter function to work with value types such as int, doubles float, bool etc. Also with complex types. Can someone help me build the setter function that should be of type Action<object, object>. For examle if I want create the setter for DateCreated I will like to build this lambda Action<object,object> mySetter = (object obj, object val) => ((School)obj).DateCreated = (DateTime)val;

I know I do not need the setter for validation but it is so fast that It will be nice to know how to do it for the future.





lundi 15 mai 2023

How does magic_enum library can output enum value as string with msvc?

The magic_enum library provides way to retrieve an enum value as its name, in the form of a string. For instance:

#include <iostream>

#include "magic_enum.hpp"

enum class Dummy : uint16_t {
    first,
    second,
    third,
};

int main() {
    std::cout << magic_enum::enum_name<Dummy::first>()
              << std::endl;  // outputs "first"}

Does some can explain here how magic_enum actually implements enum_name with msvc?

I managed to reproduce this behavior with clang/gcc by passing the enum value to a template function and using __PRETTY_FUNCTION__ inside, for instance:

template<typename Enum_T, Enum_T Value_E> class EnumValueNameAsString
{
    static constexpr std::string_view Get()
    {
        auto constexpr end = std::string_view(__PRETTY_FUNCTION__).find_last_of(';');
        if constexpr (end == std::string_view::npos)
        {
            return std::string_view("Failure");
        }
        auto constexpr start
            = std::string_view(__PRETTY_FUNCTION__).find_last_of('=', end);
        if constexpr (start == std::string_view::npos)
        {
            return std::string_view(
                "Failure");
        }
        // 0 <= start < end
        if constexpr (end - start <= 2)
        {
            return std::string_view(
                "Failure");
        }
        return std::string_view(__PRETTY_FUNCTION__).substr(start + 2, end - start - 2);
    }

public:
    static constexpr std::string_view Name = Get();
};

But for C++, using __FUNCSIG__ instead of __PRETTY_FUNCTION__, I cannot achieve the expected result as __FUNCSIG__ actually is class std::basic_string_view<char,struct std::char_traits<char> > __cdecl EnumValueNameAsString<enum Dummy,0>::Get(void) The enum value name is nowhere in the string.





dimanche 14 mai 2023

Go: Check if pointer is nil or else null value

I have the following problem in Go, for which I am looking for an elegant solution.

I get a struct returned which has the following structure

type PointerStruct struct {
    fieldA *string
    fieldB *string
    ...
}

Now I need to convert it to a similar looking struct:

type ValueStruct struct {
    fieldA string
    fieldB string
    ...
}

So what I need to do is, to dereference every field if it is not nil or put a "" if it is nil. The signature of the function looks like this:

func map(pointerStruct PointerStruct) ValueStruct {}

There are too many fields, so it is not feasible to check every field for nil, the names of the fields are the same in both objects, which should make it easier. There has to be some elegant way to achieve this, any suggestions?





Kotlin no-arg compiler plugin doesn't generate constructors

Because I need some way to initialize all variables in the noArg constructor, I've tried to apply no-arg Kotlin Compiler Plugin.

Build.gradle:

plugins {
    id "org.jetbrains.kotlin.plugin.noarg" version "1.8.0"
}

noArg {
    annotation("com.neutrino.game.utility.NoArg")
    invokeInitializers = true
}

I've also tried

buildscript {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlinVersion"
    }
}

allprojects {
    apply plugin: "kotlin-noarg"
    noArg {
        annotation("com.neutrino.game.utility.NoArg")
        invokeInitializers = true
    }
}

NoArg.kt

package com.neutrino.game.utility

@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
@com.neutrino.game.utility.NoArg
annotation class NoArg

and finally

@NoArg
class Test(test0: String) {

    val test1 = 1
    val test2 = "test2"
}

However, this does not seem to work, regardless of @Target and @Retention.

Kotlin bytecode viewer does not generate the no-args constructor.

Test::class.java.constructors.forEach { 
    println("Parameters ${it.parameterCount}, Is synthetic? ${it.isSynthetic}") 
}

does not show any synthetic constructors generated either.

How to apply this compiler plugin and how to test if it works?

It is important for me that the no args constructor initializes all variables.





samedi 13 mai 2023

llegal reflective access at HtmlPipelineContext constructor of itext 5

context: jdk11, springboot, itextpdf 5.5.13.3, ubuntu, eclipse

during: new HtmlPipelineContext(null); throughout new CssAppliersImpl(new XMLWorkerFontProvider()); and last CssAppliersImpl(){// map builder inside } appears

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.itextpdf.text.io.ByteBufferRandomAccessSource$1 (file:/home/awieclawski/.m2/repository/com/itextpdf/itextpdf/5.5.13.3/itextpdf-5.5.13.3.jar) to method java.nio.DirectByteBuffer.cleaner()
WARNING: Please consider reporting this to the maintainers of com.itextpdf.text.io.ByteBufferRandomAccessSource$1

question: how to avoid it?

PS. Before HtmlPipelineContext instance is established:

        CSSResolver cssResolver = new StyleAttrCSSResolver();
        cssResolver.addCss(cssFile);
 //     cssFile is returned from XMLWorkerHelper.getCSS(getCssStream(path));
    }

and at the debug of new HtmlPipelineContext(null); is signalized: com.sun.jdi.ClassNotLoadedException: Type has not been loaded occurred invoking method.





vendredi 12 mai 2023

Why is reflection in c++ considered impossible? [duplicate]

I have seen a lot of misinformation about C++ not having out-of-the-box reflection and if you do want full reflection, you must use other languages, install libraries or give up.

But... It seems like c++ supports reflection just fine. I can relatively simply add a system that prints out even a private variables' name, value and type out in c++11. It can also be used to check if a variable of certain name and type exists on a class. Am I misunderstanding what reflections means in this context, or is stackoverflow consensus just incorrect?

Code example:

Factory.h, basic factory with object registry

#pragma once

#include <cstring> // strcmp
#include <functional>
#include <string>
#include <unordered_map>

#include "Object.h"

// Allows Object to be spawnable through SpawnObject.
// Registers the class with the factory's registry, and connects that to a templated SpawnObject function
#define SPAWNABLE(CLASSNAME) class CLASSNAME; static bool CLASSNAME##Registered = (ObjectFactory::GetInstance().GetObjectRegistry()[#CLASSNAME] = &ObjectFactory::SpawnObject<CLASSNAME>, true)

// Spawns a class of selected name
#define DoSpawn ObjectFactory::GetInstance().SpawnObjectByName

// Find a class of selected name
#define FindObject ObjectFactory::GetInstance().FindObjectByName

// Singleton  object factory
class ObjectFactory
{
public:
    std::unordered_multimap<std::string, Object*> Objects;

    // Gets instance of the simpleton
    static ObjectFactory& GetInstance()
    {
        static ObjectFactory Instance;
        return Instance;
    }

    // A templated function to spawn any registered Object
    template <typename TObject>
    static Object* SpawnObject()
    {
        return new TObject();
    }

    // A factory function that spawns an object of the specified class name
    Object* SpawnObjectByName(const std::string& ClassName, const char* EditorName = "")
    {
        auto it = GetObjectRegistry().find(ClassName);
        if (it != GetObjectRegistry().end())
        {
            Object* obj = it->second();
            Objects.insert(std::make_pair(EditorName, obj));
            
            obj->Name = EditorName;
            obj->RegisterVariables();

            return obj;
        }
        return nullptr;
    }
    
    std::unordered_map<std::string, std::function<Object* ()>>& GetObjectRegistry() // Returns the Registry of class names
    {
        static std::unordered_map<std::string, std::function<Object* ()>> Registry;
        return Registry;
    }

    Object* FindObjectByName(std::string Name)
    {
        auto it = Objects.find(Name);
        if (it == Objects.end())
        {
            return nullptr;
        }
        return it->second;
    }

private:
    std::unordered_map<std::string, std::function<Object* ()>> ObjectRegistry;                      // Registry that maps class names to factory functions
};

Object.h class, the base for reflection

#pragma once

#include <map>
#include <string>
#include <typeinfo>
#include <vector>

// Holds variable type, value and name so it can be accessed
struct RegistryEntry
{
    const std::type_info* type;
    void* value;
    const char* name;
};

#define EditorVariableRegistry ObjectVariableRegistry::GetInstance().VariableRegistry 

class ObjectVariableRegistry
{
public:
    static ObjectVariableRegistry& GetInstance()
    {
        static ObjectVariableRegistry Instance;
        return Instance;
    }

    std::multimap<void*, RegistryEntry> VariableRegistry;

private:
    ObjectVariableRegistry() {}
    ObjectVariableRegistry(const ObjectVariableRegistry&) = delete;
};

class Object
{
protected:
    std::vector<RegistryEntry> EditorVariables;         // Container of all variables changable in Editor
    
public:
    #define SERIALIZE(var) EditorVariables.push_back(RegistryEntry{&typeid(var), &(var), #var}), true;

    void RegisterVariables()                            // Registers all editor variables into a global list. Does not work properly if placed in .cpp file
    {
        SERIALIZE(Name);
        
        for (auto& entry : EditorVariables)             // Loops through the EditorVariables and add them to the global VariableRegistry
        {
            EditorVariableRegistry.emplace(this, entry);
        }
    }
    
    std::string Name = "";
};

Foo.h. A simple class which inherits from Object, meaning it now has out-of-the box support for reflection.

#pragma once

#include "Factory.h"

SPAWNABLE(Foo);
class Foo : public Object
{
public: 
    Foo()
    {
        SERIALIZE(Bar);
    }
    
private:
    std::string Bar = "private variable";
};

Finally: Main.cpp. Note how we don't #include Foo.h anywhere in the program, and we can still inspect (and modify) Foo variables as long as we #include "Factory.h".

#include <iostream>

#include "Factory.h"
#include "Foo.h"

void PrintAllVariables()
{
    printf("Registry contents: (%zi) \n", EditorVariableRegistry.size()) ;
    for (const auto& var : EditorVariableRegistry)
    {
        if (Object* obj = static_cast<Object*>(var.first))
        {
            std::cout << "  Owning class name: " << obj->Name << "  Owning class instance address: " << var.first << std::endl;
        }

        std::cout << "  Variable name: " << var.second.name << "  Variable address: " << var.second.value << std::endl;
        std::cout << " Type: " << var.second.type->name() << std::endl;
        std::cout << "  Value: ";
        // Check the type of the variable
        if (*var.second.type == typeid(std::string))
        {
            std::cout << *static_cast<std::string*>(var.second.value);
        }
    }
}

int main()
{
    DoSpawn("Foo", "Dude");

    PrintAllVariables();

    return 0;
}

Output:

Registry contents: (2) 
  Owning class name: Dude  Owning class instance address: 0x561afd16cf80
  Variable name: Bar  Variable address: 0x561afd16cfb8
 Type: NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
  Value: private variable  Owning class name: Dude  Owning class instance address: 0x561afd16cf80
  Variable name: Name  Variable address: 0x561afd16cf98
 Type: NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE
  Value: Dude




xml.Unmarshal unsupported type struct

I'm getting an error where I cannot xml.Marshal a struct made at runtime with reflect.

It is giving me the following error:

xml: unsupported type: struct { ... }

Here is my go-playground link.

Anyone have any idea why this isn't working?
What am I missing about the implementation?
It works fine for JSON and YAML.





jeudi 11 mai 2023

Named fields for another class

I need to access some private fields via reflection. While this is considered bad, it is an external library and I have no other way to access it. The field names (and types) are known in advance (during compile time) and as a precaution for future library updates I want the compiler to throw an error when this field doesn't exist anymore.

Lombok has the annotation @FieldNameConstants which generates all field names as static Strings. When the field doesn't exist anymore, the static variable won't generate and the compiler will throw an error. This would be a great solution, but as this is an external library class I cannot annotate it with lombok.





mercredi 10 mai 2023

Calling java.lang.reflect.Field::getValue(this) from abstract superclass defined method returns IllegalAccessException

I'm trying to print the whole hierarchy of a class using reflection.

To do this I defined an abstract superclass A that defines the toString(int offset) method:

abstract class A {
    public String toString(int offset) {
        StringBuilder builder = new StringBuilder();
        try {
            for (Field field : this.getClass().getDeclaredFields()) {
                builder.append(String.join("", Collections.nCopies(offset, "\t")));
                builder.append(field.getName()).append(": ");
                field.setAccessible(true); // workaround
                if (field.getType().isPrimitive()) {
                    // (int, float, ...)
                    builder.append(field.get(this));
                } else if (field.getType().getName().contains("java.lang")) {
                    // (Integer, String, ...)
                    builder.append(field.get(this).toString());
                } else {
                    // Other classes
                    builder.append("\n").append(A.class.cast(field.get(this)).toString(offset + 1));
                }
                builder.append("\n");
                field.setAccessible(false); // workaround
            }
        } catch (Exception e) {
            System.out.print(e);
        }
        return builder.toString();
    }
}

then I have some classes that extend the A class:

public class X extends A {
    private String field1;
    private Y field2;
}

public class Y extends A {
    private String field3;
    private String field4;
}

which instances contains some values.

The expected output of the call x.toString(0) should be:

field1: value1
field2:
    field3: value3
    field4: value4

Without the use of field.setAccessible(true) when I call x.toString(0) I get

IllegalAccessException: Class A can not access a member of class X with modifiers "private"

but I cannot undestand why.

When I check the reference while debugging this refers to X.class, so why the field.getValue(this) doesn't work?

Shouldn't this refer to the instance of the class calling the method? Am I missing something?





How to convert lambda expression from a type to another type in Java?

I'm using mybatis-plus's lambda chained query and it looks like this

Long uid = new LambdaQueryChainWrapper(baseMapeer)
            .select(User::getUid)
            .eq(User::getUsername, username)
            .get();

I think it's so tedious that I have to write every class, and sometimes I needed to add caching operations, so I write an abstract class to simplify the operation, like this

// abstract service
public <R> T getEntityByUniqueColumn(SFunction<T, R> lambda, R value) {
    // use mybatis-plus util
    final String keyColumn = keyName();
    // USE THIRD-PARTY LIBRARY REFLECTION UTIL
    final String propertyName = reflectProperty(lambda);
    // use mybatis-plus util
    final String columnName = reflectColumn(propertyName);

    return new QueryChainWrapper(baseMapper)
             .select(keyColumn)
             .eq(columnName, value)
             .get();
}

// actual service
public Long getUid(String username) {
    return getEntityByUniqueColumn(User::getUsername, username);
}

I'm using the 'de.cronn.reflection.util.PropertyUtils' method to get propertyName through get lambda function

private String reflectPropertyName(SFunction<T, ?> getXxxSFunc) {
    if (getXxxSFunc == null) return null;
    try {
        return PropertyUtils.getPropertyName(entityClass, getXxxSFunc::apply);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Now the problem arises. PropertyUtils requires a lambda expression with a TypedPropertyGetter parameter, while my abstract method provides a lambda expression with an SFunction parameter.

The method signature of the former is V get(T t), and the method signature of the latter is V apply(T t). I tried to convert from SFunction to TypedPropertyGetter by using lambda::apply.

But I encountered an exception when I executed it. The reason is: PropertyUtils will eventually check whether the lambda method passed is call site specific. If it is, it throws an exception. This means that we cannot express lambda expressions by delegation (there are attributes inside), and we must pass this parameter by user-defined, such as User::getUsername.

// source-code
private static void assertHasNoDeclaredFields(Object lambda) {
    if (hasDeclaredFields(lambda)) {
        throw new IllegalArgumentException(lambda + " is call site specific");
    }
}

private static boolean hasDeclaredFields(Object lambda) {
    return lambda.getClass().getDeclaredFields().length > 0;
}

There are many methods of abstract classes in my project. I want to know how to convert this lambda expression into a zero-one type without delegation.





How to remove all registered event handlers of a specific event from a UWP Control

I would like to know, how can I remove all the event handler registered in a particular event in a UWP Control (e.g., button or toggle switch). Consider the fact that I don't have any access to the event handle, so I can't use the deregister method like "some_event -= my_event_handler".

I found some solution [https://ift.tt/7gvMJfo] in stack overflow for the similar problem using reflection; however the solutions didn't work when I tried to implement the for UWP controls.





How to pass parameter to invoke method as a vararg of a relfected class in case of Java reflection?

I have a project in which I am using a third party library. However, I need to call methods from the third party only if the user has copied those jars in the project, or else use the existing jars. For this purpose I am using reflection for creating the classes and calling the methods from this third party library.

One of the methods from the library expects varargs of another class from the same library as argument. Since both the classes have been created in my main class using reflection and also their corresponding methods have been created using reflection, how do we pass argument as vararg of a class to the methodname.invoke() method?

Refer the code snippet ahead.

//-------Class A-----------------

package com.demoA;

Class A {
   public void methodA(B... b) {
      // Contents of methodA...
   }
}

//-------Class B-----------------

package com.demoB;

Class B {
    // contents of class B here...
}

//-------Class MainClass-------------

package com.mainclass;

Class MainClass {
    public static void main(String[] args) {
        Class<?> azz = Class.forName("com.demoA.A");
        Object aObject = azz.getDeclaredConstructor().newInstance();
        Method methodAReflected = null;
    
        for (Method m : azz.getMethods) {
            if (m.getName.equals("methodA")) {
                methodAReflected = m;
            }
        }
        
          Class bzz = Class.forName("com.demoB.B");
          Object bObject = bzz.getDeclaredConstructor().newInstance();
        
          methodAReflected.invoke(aObject, <how to pass varargs here>);
          // Passing only bObject or new Object[] { bObject } result in an IllegalArgumentException : type mismatch
    
    }
}

Also, is there is any better way (rather than iterating through the method names) to use Java reflection's getMethod() method to create the reflected method when the expected parameter is a vararg?





lundi 8 mai 2023

Blazor - Reflection issue

I'm trying to get the data values out of an object. I can get the properties from the Class just fine. But when I ask for the values, it fails. Any thoughts on why the GetValues line isn't working?

@inject HttpClient Http
@using System.Reflection

<p>@str</>

@code {
    public string? str;

    protected override async Task OnInitializedAsync()
    {
        stats = await Http.GetFromJsonAsync<Statistics[]>("sample-data/CoreDataCompany2023E.json");

        Type type = typeof(Statistics);

        var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);

        foreach (var prop in properties)
        {
            str += prop.GetValue(stats);
        }    
    }
}

@code{
    public class Statistics
    {
        public string Year { get; set; }  
        public int Volume { get; set; }
    };

Statistics[] stats = new Statistics[]
    {
        new Statistics
        {
            Year = "2023",
            Volume = 1225000
        }
    };
}




How to use MethodByName between different packages [closed]

i am using MethodByName in my go code to take the name of the function from config file, here i have declared the interface struct in other package but i want to call the function in other function,

                            log.Infof("\n name of metric is : " + metric.Name + "\n")
                            results := utils.Invoke(c, metric.Name, m, serviceLog, metric.TimeOut)
                            if !results[0].IsNil() {
                                log.Errorf("Failed to get " + metric.Name)
                            }

location of this file is /src/file1

func Invoke(any interface{}, name string, args ...interface{}) []reflect.Value {
    inputs := make([]reflect.Value, len(args))
    for i, _ := range args {
        inputs[i] = reflect.ValueOf(args[i])
    }
    result := reflect.ValueOf(any).MethodByName(name).Call(inputs)
    return result
}

this is in src/utils/file2

package diagnosticDumps

type ThresholdFunc struct{}

this is in src/diagnosticDumps

but it is giving panic: reflect: call of reflect.Value.Call on zero Value

the function written is exported

func (t *ThresholdFunc) HotThreadMetric(some parameters) {




How to get values from the array, that put into the object?

I am making json parser so I need the iniversal method, thats why I can not int[] arr = obj as int[];

 int[] array = new int[] { 0, 1, 2 };
 object obj = array;
//I need to get value from the 'obj'

I tried to use reflection, but my knowledge is not enough to solve the problem. Also I tried to use solutions from here How to extract elements of an array in object type in c#? but it did not help me.

UPD

I am getting random object, and I must convert it into json format ecma-404. But I got problems with converting arrays, because I can not get values.

   private static string ReadObject(object obj) {
            string json = "{";
            TypedReference reference = __makeref(obj);
            foreach(var fromField in obj.GetType().GetFields()) {
                var toField = obj.GetType().GetField(
                    fromField.Name, BindingFlags.Public | BindingFlags.Instance);

                object value = fromField.GetValueDirect(reference);
                if(value == null)  json += toField.Name + ':' + "null" + ',';
                else json += toField.Name + ':' + WriteValue(value, value.GetType()) + ',';

            }
            json = json.Remove(json.Length - 1);
            json += '}';
            return json;
        }


 public static string SerializeArray(object obj) {
            string json = "[";
//here must be code
            return json;
        }





samedi 6 mai 2023

How to invoke a constructor what has a ReadOnlySpan

This is the second time I ask this question because it has been marked as duplicate, but my problem still not been solved and I can't figure it out.

Link 1
Link 2

From Link 1: This code below is from the accepted answer, but doesn't work.

CS0306 The type 'ReadOnlySpan' may not be used as a type argument

var delegateCtor = Expression.Lambda<Func<ReadOnlySpan<byte>,object>>
(ctorCall, new ParameterExpression[] { param }).Compile();

So my question again:

In .Net Framework BigInteger has a constructor what I can invoke as this:

ConstructorInfo _ctor = typeof(BigInteger).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null,
            new Type[] { typeof(UInt32[]), typeof(Boolean) }, null);

BigInteger result = (BigInteger)_ctor.Invoke(new Object[] { new UInt32[] { 42, 69, 314 }, false });

Recently swapped to .Net Core and the constructor changed to:

ConstructorInfo _ctor = typeof(BigInteger).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,
            new Type[] {typeof(ReadOnlySpan<UInt32>), typeof(Boolean) });

So the logical step was:

BigInteger result = (BigInteger)_ctor.Invoke(new Object[] { new ReadOnlySpan<UInt32>(new UInt32[] { 42, 69, 314 } ), false } );

But I'm getting an error.

Error CS0029 Cannot implicitly convert type 'System.ReadOnlySpan' to 'object'.

How can I invoke a constructor what takes 2 arguments and one of them is a ReadOnlySpan?

Thank you





vendredi 5 mai 2023

Index specific TypeORM entity fields

I'm building an indexing service to index various entity fields. I'd like to be able to add a decorator like @Searchable or similar to the fields I want to decorate and then using some kind of indexing service (and probably reflection) find all the entity classes (those with the @Entity decorator), then in each one of those, gather up all of the fields with @Searchable decorators applied to them.

The issue is - I'm running into issues trying to use reflection to find the entities an it's starting to feel like I'm approaching the issue wrong.

I've tried putting the smarts in the decorator and having it register with some kind of external service every time it's called, but this feels very fragile and requires a singleton of that service to be available to "hold" the data.





mercredi 3 mai 2023

Invoke a method which returns an object from a specific class

I have a Java method that I am going to call using reflection, but it throws an UnsupportedOperationException: invalid class reference provided:

package example;

public class TestContract extends Contract {
     
    // .. other functions they are not intended

     public RemoteFunctionCall<User> ret1Object() {
          final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_RET1OBJECT, 
                  Arrays.<Type>asList(), 
                  Arrays.<TypeReference<?>>asList(new TypeReference<User>() {}));
          return executeRemoteCallSingleValueReturn(function, User.class);
     }

     public static class Person extends StaticStruct {
        public BigInteger size;

        public Person(BigInteger size) {
            super(new org.web3j.abi.datatypes.generated.Uint256(size));
            this.size = size;
        }
    }

    public static class User extends DynamicStruct {
        public String name;

        public String fr2;

        public BigInteger age;

        public Person person;

        public User(String name, String fr2, BigInteger age, Person person) {
            super(new org.web3j.abi.datatypes.Utf8String(name), 
                    new org.web3j.abi.datatypes.Address(160, fr2), 
                    new org.web3j.abi.datatypes.generated.Uint8(age), 
                    person);
            this.name = name;
            this.fr2 = fr2;
            this.age = age;
            this.person = person;
        }
    }

}

Note that the above function (ret1Object) is returning a User object. (No problem when a method returns String, BigInteger, etc.)

I'm using the following code to call functions at runtime:

ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("example.TestContract");
Method loadMethod = cls.getMethod("load", String.class, Web3j.class, Credentials.class, ContractGasProvider.class);
Object instance = 
                    loadMethod.invoke(cls, contractAddress, AIOBlock.web3Instance, AIOBlock.currentCredential, (ContractGasProvider) new DefaultGasProvider());

Method[] methods = cls.getMethods();
Method method = null;
for (Method mth : methods) {
    if (mth.getName().equalsIgnoreCase("ret1Object")) {
        method = mth;
        break;
    }
}
Object retObject = method.invoke(instance);
RemoteFunctionCall rfc = (RemoteFunctionCall) retObject;
retObject = rfc.send(); // <<----------- Exception is thrown at this line

When calling ret1Object I'm getting the exception invalid class reference provided, but my code works for all other functions that return java built-in types such as String, BigInteger, etc.





How to invoke a private static method with parametrized parameter in Java?

I have a method with the following signature private static <T> String getId(T element) and I need to test it.

I have tried to do a stuff like that Method method = MyClass.class.getDeclaredMethod("getId", (Class<?>) any(Object.class));, but it does not work. I got a java.lang.NoSuchMethodException with MyClass.getId(null).

If I well understand, that means that the declared args for the reflection is not well defined.

There is a way to do it?

By advance, no, I can't change the signature of the tested method.





mardi 2 mai 2023

How to access the embedded struct inside the SliceOfPointers field of a Struct

I want to add functionality to take the first element when the data is []*struct.

func getEncFields(t reflect.Type, list map[string]int) {
    for t.Kind() == reflect.Ptr {
        t = t.Elem()
    }
    if t.Kind() == reflect.Struct {
        for i := 0; i < t.NumField(); i++ {
            field := t.Field(i)
            tag := field.Tag.Get("bson")
            if containsTag(tag, "encr") {
                list[getFieldName(field, tag)]++
            }
            getEncFields(field.Type, list)
        }
    }

In this code I need to add functionality when the data is []*Struct. Here is the struct type to be passed in this function.

type Customer struct {
    Name     string    `json:"name" bson:"name"`
    Acnumber int64     `json:"acnumber" bson:"acnumber,encr"`
    Number   int64     `json:"number" bson:"number,encr"`
    Address  []Address `json:"address" bson:"address"`
}
type Address struct {
    Mail string `json:"mail" bson:"mail,encr"`
}

Thank you for your support





nextjs css changes does not reflecting on client side?

next.js project everything work properly but style changes does not reflected although I clear my browser cache ,hard reloading , restart development server but still not working mean changes are not reflecting.

import export is also proper every style is apply but changes not reflecting, need some other solution





lundi 1 mai 2023

Using C# Reflection to parse a hierarchy of data classes

I have written a data parser for my script engine that uses reflection to get the value of actual program data classes. I have a hierarchy of classes where some of my sub-classes hide other sub-classes.

C#'s runtime binder logic knows how to handle this and won't recognize members of the hidden class, but my logic can't tell the difference between a hidden member and a valid member.

The code below is a super-truncated version that illustrates my issue. As you can see from the output, both the timestamp member of the original PSR class, and the timeStamp (different case) member of the updated PSR class are found.

I'm looking for an attribute or method that can help me decide if the member I'm looking at is hidden or accessible.


using System;
using System.Reflection;`

namespace test
{
    static class PRD
    {
        public static dynamic prdData { get; private set; } = new PRD_P20();
    }

    public abstract class PRD_DATA
    {
        public BLE ble = new BLE();
        public class BLE : PRD_BLE_BASE { }
    }

    public abstract class PRD_BLE_BASE
    {
        public PSR psr = new PSR();
    }
    public class PSR
    {
        public string timestamp = "original";
    }

    public class PRD_P20 : PRD_DATA
    {
        /* Instantiate new version BLE and hide the parent class  */
        public new BLE ble = new BLE();

        public new class BLE
        {
            public PSR psr = new PSR();
        }

        public class PSR
        {
            public string timeStamp = "updated";
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            var o = PRD.prdData;
            foreach (FieldInfo f in o.GetType().GetFields())
            {
                Console.WriteLine(f.Name + " " + f.DeclaringType);

                object o1 = f.GetValue(o);
                foreach (FieldInfo f1 in o1.GetType().GetFields())
                {
                    Console.WriteLine("----" + f1.Name);

                    object o2 = f1.GetValue(o1);
                    foreach (FieldInfo f2 in o2.GetType().GetFields())
                    {
                        Console.WriteLine("--------" + f2.Name + ": " + f2.GetValue(o2));
                    }
                }
            }

            Console.WriteLine(PRD.prdData.ble.psr.timestamp);   // Fails RuntimeBinderException
            Console.WriteLine(PRD.prdData.ble.psr.timeStamp);

            Console.ReadKey();
        }
    }}

Output:

ble test.PRD_P20
----psr
--------timeStamp: updated
ble test.PRD_DATA
----psr
--------timestamp: original