lundi 30 octobre 2023

How to inject a method into a class at runtime without ASM?

In past versions of the bytecode manipulation framework Mixin, there was a method called prepareConfigs(MixinEnvironment). A nonstandard, but very commonly-used, way to bootstrap Mixins at a certain phase of the lifecycle was to access and call that method using Reflection.

In later versions of the framework, that method's signature has been changed to prepareConfigs(MixinEnvironment, Extensions), causing the Reflection-based usages to break.

The owner of the library has made it clear that breaking this was intentional and will not allow a fix. However, even though it was bad practice to use that strategy, the usage was common enough that end-users are unable to use many apps that relied on the framework.

I would like to make a compatibility patch that adds the old method back to the class to stop the crashes. Problem is, this requires injecting a method into a class that is restricted from being transformed by ASM.

The only requirement is that the method does not throw a NoSuchMethodException when accessed via reflection, since I'm easily able to implement their intended behavior somewhere else. It doesn't actually need to do anything, it just needs to stop the exception from being thrown.

I've heard people offhand-mention a way to declare class members that can only be accessed by Reflection, but I couldn't find any details on it.

Is there a way to do what I need without ASM?





dimanche 29 octobre 2023

Type Load Exception On Method Load

I have a Visual Studio 2023 solution containing 32 projects. The projects extensively reference each other. 31 of the projects are class libraries, while the last one is a console application used whenever I want to test one of the functions in my library, so I don't have to create a new temporary one each time. Visual Studio's Immediate Window has never worked for me, even before this issue. All the projects are written in C# 11, and use .NET 7.0. Many of the projects reference the NuGet package System.Collections.Immutable.

I was attempting to write a Crawler, like a Web Crawler, but for types. It would iterate though all static/nonstatic members of a type, add their parameter types and return types (if present) to a HashSet<Type>. It would then recursively do the same for each type that was added. It was designed so that it would only ever iterate though each time once.

It did this by creating a List<Type>, and every time a type was added to the HashSet<Type> that did not already exist, it would add it to the list. After the list was complete, it would recursively do the same for each type in the list. If a type was, or contained in its generic parameters (if present), a generic parameter, it would be substituted with its definition. There were also some functions to cover pointers, references, and arrays.

I ran the function on an object, and it worked fine. I got the type for the object using C#'s typeof(?) method. However, then I ran the function on a static class in one of my projects, and it threw an exception.

At this point, it is worth mentioning the projects that are involved with this. I have one console application project (Test) in which I am executing the crawler in a second project (Brendan.IC.Typed.Execution), which was supposed to crawl through a static class in a third project (Brendan.IC.Typed). The latter project references System.Collections.Immutable. System.Collections.Immutable most likely has nothing to do with this, but I think its worth mentioning everything, since I have absolutely no idea what the problem is.

The exception was a System.TypeLoadException.

System.TypeLoadException: 'Could not load type 'Brendan.IC.Typed.TypedEvolutionLookup`1' from assembly 'Brendan.IC.Typed, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.'

The static class I had called the crawler on was Brendan.IC.Typed.TypedEvolution. One of its static methods contained a parameter of type Brendan.IC.Typed.TypedEvolutionLookup<>. This is how the crawler found it. It then was unable to load it. The exception was thrown in the MethodInfo.GetParameters() function.

Initially, I assumed this was some problem with my crawler function. I cleaned and rebuilt the solution, my normal first step in handling errors, but to no effect. I recompiled the solution multiple times in both Debug and Release mode, to no effect. I checked my code for anything that might effect type loading. I found nothing. Finally, I decided to load the offending type in my top-level statements. It threw an exception, the same exception it had previously.

System.TypeLoadException: 'Could not load type 'CodeInterpretation.Typed.TypedEvolutionLookup`1' from assembly 'Brendan.IC.Typed, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.'

Here was my top-level statement:

using Brendan.IC.Typed;
using Brendan.IC.Typed.Execution;
using static System.Console;
Type bigType = typeof(TypedEvolutionLookup<int>);
Crawler.Crawl(bigType);
ReadKey(true);

I simplified it to this:

using Brendan.IC.Typed;
using static System.Console;
Type bigType = typeof(TypedEvolutionLookup<int>);
ReadKey(true);

This is when things started to get weird... real weird.

First of all, I noticed that there was no line number or call stack associated with the exception.

A picture of the exception.

Upon selecting Show Call Stack:

A picture of the call stack.

Here's my full screen:

A fullscreen screenshot of the exception.

Usually, when I get an exception, I can add a WriteLine() right before the line I suspect, and it will print to the console before the program terminates due to the exception. I did so, and added a breakpoint on the same line, intending to step through the program. Finally, I added a generic parameter to the generic type definition. But the program didn't even hit the breakpoint! Nor did it print to the console!

New code:

using Brendan.IC.Typed;
using static System.Console;
WriteLine("hi");
Type bigType = typeof(TypedEvolutionLookup<int>);
ReadKey(true);

Screenshot:

Screenshot of exception.

I put it in release mode, too. As expected, it did not throw an error, since it optimized out the unnecessary assignment. Nor did it hit the breakpoint, obviously.

I removed the 4th line, and it then work fine. I added it back in, it broke. I tried getting a different type from the Brendan.IC.Typed assembly. It worked fine. I replaced the WriteLine() statement with another ReadKey(true) statement. It broke.

using Brendan.IC.Typed;
using static System.Console;
ReadKey(true);
Type bigType = typeof(TypedEvolutionLookup<int>);
ReadKey(true);

A screenshot of the error for the latter case.

I got rid of the generic parameter. There was no change:

A screenshot of the error.

What worries me is that I think the error is happening, not with the execution of the typeof statement, but in the compiler for the IL! The error is being thrown between when I compile it, and when the top-level statements are executed! There is only one thing I can think of that would fit those constraints, and depend on the existence of a typeof line, and that it the IL runtime compiler itself!!! Yet the type is being found easily by the C#-to-IL compiler!

And the error is not happening with any of the other types in the assembly! Unfortunately, the TypedEvolutionLookup<> struct is the only generic type in the Brendan.IC.Typed assembly. However, it is not the only readonly struct. I have, though, tested some of the other readonly structs, and they do not have the same problem. The IL compiler seems to, for some reason, single out this one specific type, and, dependent or not on generics, this should not be happening.

I have, multiple times, restarted my computer, in case there is some secret RAM type-cache that I am not aware of. I have, multiple times, cleaned and rebuilt the solution, in case there is something weird with that. I have, multiple times, deleted the output directories of all my projects, in case some past versions are interfering with the present ones.

(All my class libraries compile to the same output directory; however, the console application compiles to its own, so as to avoid confusion.)

There has been no change. I do not understand this. I want to get the System.Type for this struct. Why has the IL compiler singled out this specific one? It has no funky attributes, except for the occasional [MaybeNullWhen(false)] in the parameters of its methods.

Why could this be happening, and how might I avoid it?





vendredi 27 octobre 2023

MethodHandle Lookup Issues

I've recently needed to make a relatively simple events system. (Id -> Consumer) This would be able to subscribe a Method based off annotation. Then I remembered that Java isn't C# and attempted to look for a way to accomplish this. After many similar threads, I came across this GitHub Gist, and attempted to implement it. I did so successfully, however did not realize early enough that the MethodHandles.lookup() method is location specific and only applies to the class that calls it.

ConsumerFactory

public class ConsumerFactory {
    private final Method consumerMethod;
    private final MethodType consumerMethodType;

    private final Map<Method, Consumer<?>> methodCache = new HashMap<>();

    public ConsumerFactory() {
        consumerMethod = findLambdaMethod(Consumer.class);
        consumerMethodType = MethodType.methodType(consumerMethod.getReturnType(), consumerMethod.getParameterTypes());
    }

    public <T, L> Consumer<T> createConsumer(L instance, Method implMethod) throws Throwable {
        Consumer<T> cached = (Consumer<T>) methodCache.get(implMethod);
        if(cached==null) {
            Class<?> implType = implMethod.getDeclaringClass();

            MethodHandles.Lookup lookup = MethodHandles.lookup().in(implType);
            MethodType implMethodType = MethodType.methodType(implMethod.getReturnType(), implMethod.getParameterTypes());
            MethodHandle implMethodHandle = lookup.findVirtual(implType, implMethod.getName(), implMethodType);

            MethodType invokedMethodType = MethodType.methodType(Consumer.class, implType);

            CallSite metaFactory = LambdaMetafactory.metafactory(
                    lookup,
                    consumerMethod.getName(), invokedMethodType, consumerMethodType,
                    implMethodHandle, implMethodType);

            MethodHandle factory = metaFactory.getTarget();
            Consumer<T> consumer = (Consumer<T>) factory.invoke(instance);
            methodCache.put(implMethod, consumer);
            return consumer;
        }
        return cached;
    }

    private Method findLambdaMethod(Class<?> type) {
        if (!type.isInterface()) {
            throw new IllegalArgumentException("This must be interface: " + type);
        }
        Method[] methods = getAllMethods(type);
        if (methods.length == 0) {
            throw new IllegalArgumentException("No methods in: " + type.getName());
        }
        Method targetMethod = null;
        for (Method method : methods) {
            if (isInterfaceMethod(method)) {
                if (targetMethod != null) {
                    throw new IllegalArgumentException("This isn't functional interface: " + type.getName());
                }
                targetMethod = method;
            }
        }
        if (targetMethod == null) {
            throw new IllegalArgumentException("No method in: " + type.getName());
        }
        return targetMethod;
    }
    private Method[] getAllMethods(Class<?> type) {
        LinkedList<Method> result = new LinkedList<>();
        Class<?> current = type;
        do {
            result.addAll(Arrays.asList(current.getMethods()));
        } while ((current = current.getSuperclass()) != null);
        return result.toArray(new Method[0]);
    }
    private boolean isInterfaceMethod(Method method) {
        return !method.isDefault() && Modifier.isAbstract(method.getModifiers());
    }
}

Is their anything I could do to still have this sort of idea function? Ideally end up as something like Map<String, Consumer<Event>>. I was considering forcefully creating a Lookup class, but I'm not sure if that would be the best idea.

Thank you all for the help!





Get the type name of a Dictionary with generics in C#

Is there an easy or elegant way to get the type name of a Dictionary with the generic types in C#?

Currently I have this code works:

if (property.PropertyType.Name == "Dictionary`2")
{
    Type[] arguments = property.PropertyType.GetGenericArguments();
    Type keyType = arguments[0];
    Type valueType = arguments[1];
    properties[property.Name] = $"Dictionary<{keyType.Name},{valueType.Name}>";
}

I was wondering whether there is more easy way of achieving this formatted string that I'm looking for, like: "Dictionary<type, type>"





mercredi 25 octobre 2023

Blazor validate custom editor control bound to property by name

In my Blazor server app, I created a CustomEdit control to edit DateTime properties of an object by name:

NOTE this is an illustration - using an existing DateTime editor is not the point here, the point is I am binding to a property by its name!

@typeparam TItem;
@inherits ComponentBase;  
@if (Context != null) {
  <InputText @bind-Value="@DateStr" />
  <ValidationMessage For="@(() => DateStr)" />
}
@code {
  [Parameter]
  public TItem Context { get; set; }

  [Parameter]
  public string BoundPropertyName { get; set; }

  [Parameter]
  public string DateFormat { get; set; } = "dd.MM.yyyy";

  protected override void OnParametersSet() {
    if (_pInfo == null) {
      _pInfo = typeof(TItem).GetProperty(BoundPropertyName);
    }
    base.OnParametersSet();
  }
  PropertyInfo _pInfo;

  bool isValid(DateTime result) {
    if (_pInfo == null || Context == null) {
      return false;
    }
    // --- validation
    var valContext = new ValidationContext(Context) { MemberName = BoundPropertyName };
    var validationResults = new List<ValidationResult>();
    return Validator.TryValidateProperty(result, valContext, validationResults);
  }
  string DateStr {
    get => _pInfo != null && Context != null ? ((DateTime)_pInfo.GetValue(Context)).ToString(DateFormat) : string.Empty;
    set {
      DateTime result;
      if (DateTime.TryParseExact(value, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out result) && isValid(result)) {
        _pInfo.SetValue(Context, result);
      }
    }
  }
}

I created an edit form bound to a PersonData model with a birthday as follows within the edit form:

<CustomEdit TItem="PersonData" BoundPropertyName="@nameof(PersonData.BirthDate)" Context="@model" />

Now, I see the validation triggers as expected, returns false for an empty string for example, but my validation message is not showing and the editor box appears as valid (green) as it shouldn't (PersonDate.BirthDate is flagged as [Required] and also with a custom ValidDateAttribute that has some internal logic). Why is the message not showing?

As a side-note: if I use an existing DateTime editor and directly @bind-Value="@context.Birthday", validation works perfectly and shows the validation errors I want to see...





dimanche 22 octobre 2023

C++ how to get the first and the last element in an std::vector by its base memory address

To me, a vector layout looks something like this:

struct MyViewOnHowVectorLooksLike
{
public:
   int* _first, * _last, * _end;
};

Known Parameters:

  1. Address of the std::vector<Type> object
  2. size of the <Type>

Questions:

  1. Find the address of the first element and the last element in the vector

Is there any way to access the first and last elements in a std::vector by its base memory address, which is &Test in the above test case, not by calling any build-in method of the std::vector function eg [0], .front(), etc; (The reason why I'm doing this is to have a static reflection system which could output the content of any given written vector type)

struct FTestData {
    int data;
};

class TestClass {
public:
    // test array
    std::vector<FTestData> testArray;

    TestClass(){}
};

// TEST CASE
FTestData testCon1 = FTestData();
testCon1.data = 111;
FTestData testCon2 = FTestData();
testCon2.data = 222;

TestClass Test = TestClass();
Test.testArray.push_back(testCon1);
Test.testArray.push_back(testCon2);

std::vector<FTestData>* TestData = (std::vector<FTestData>*)((size_t)&Test);
size_t ptr = (size_t)TestData;
FTestData& TestElement1 = (*TestData)[0];
size_t realFirstElementAddress = (size_t)&TestElement1;

// try to get the address of the first element in the vector but it  gives me the wrong address
size_t CustomFirstElementAddress = (*(size_t*)(ptr));

// expecting those two to be the same but it wasnt
assert(realFirstElementAddress == CustomFirstElementAddress);

I thought the _First and _Last are right next to the base address, but it keeps outputting the wrong results.

AddOn: The real problem I am trying to solve is to have a detail panel with my own reflection system, which could allow me do something like this. It works for most common types, and nested class.

{
    if (field.Type == "int") {
        int location[1];
        auto& value = *(int*)((size_t)&Component + Offset + field.Offset);
        memcpy(location, &value, sizeof(location));
        if (ImGui::DragInt(fieldName.c_str(), location, 0.1f, 0.0f, 0.0f, "%.1f"))
        {
            memcpy(&value, location, sizeof(location));
        }
    }
    else if (field.Type == "std::string") {
        char buffer[256];
        memset(buffer, 0, sizeof(buffer));
        auto& value = *(std::string*)((size_t)&Component+ Offset + field.Offset);
        strcpy(buffer, value.c_str());
        if (ImGui::InputText(fieldName.c_str(), buffer, sizeof(buffer))) {
            value = std::string(buffer);
        }
    }
    else if (field.Type == "bool") {
        bool location[1];
        auto& value = *(bool*)((size_t)&Component + Offset + field.Offset);
        memcpy(location, &value, sizeof(location));
        if (ImGui::Checkbox(fieldName.c_str(), location)) {
            memcpy(&value, location, sizeof(location));
        }
    }
    else if (field.Type == "float") {
        float location[1];
        auto& value = *(float*)((size_t)&Component + Offset + field.Offset);
        memcpy(location, &value, sizeof(location));
        if (ImGui::DragFloat(fieldName.c_str(), location, 0.1f, 0.0f, 0.0f, "%.1f"))
        {
            memcpy(&value, location, sizeof(location));
        }
    }
}




wierd class cast using dynamic proxy and java17 - java modules exception

I have trying to make a simple dynamic proxy example work without success. I assume I am doing something wrong but reading some java modules tuts and proxy tuts did not help me understand... the code is super basic with an interface, its implementation, an invocatgion handler and the class with the main method that runs the example:

package com.example.proxy;

public interface Foo {
    public String foo(String s);
}

package com.example.proxy;

    public class FooImpl implements Foo{
    
        @Override
        public String foo(String str) {
            return str;
        }
        
    }

package com.example.proxy;

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

public class FooProxy implements InvocationHandler{
    Foo foo;
    public FooProxy(Foo s){
        this.foo = s;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("%#$%#5^$@5^$@5^   PROXY");
        return ("[proxied] "+method.invoke(this.foo, args));
    }
    
}

package com.example.proxy;


import java.lang.reflect.Proxy;


public class MainTest {

    public static void main(String [] args){
        Foo o = (Foo)Proxy.newProxyInstance(Foo.class.getClassLoader(), Foo.class.getInterfaces(), new FooProxy(new FooImpl() ));

    }
}

running maintest yeilds:

Exception in thread "main" java.lang.ClassCastException: class jdk.proxy1.$Proxy0 cannot be cast to class com.example.proxy.Foo (jdk.proxy1.$Proxy0 is in module jdk.proxy1 of loader 'app'; com.example.proxy.Foo is in unnamed module of loader 'app')
    at com.example.proxy.MainTest.main(MainTest.java:10)

I tried exposing com.example.proxy in module-info.java explicitly, trying some opens etc but nothing helped so I assume I do not get something. can anyone help point me in the right direction thanks!





Get field of struct pointer if not nil, otherwise default value

I'm looking for a function that would reduce the redundancy in accessing a member of a struct pointer in Go. It should perform the member access if the pointer is not nil, or return a default value otherwise. It should be functionally equivalent to:

var ptr *MyStruct
var result any
if ptr != nil {
    result = ptr.MyField
} else {
    result = sql.NullFloat64{}
}

In principle, this pattern comes from the orElse of optionals in many other languages. The use case is to extract a field from a nested protobuf message and stuff it into a SQL query. The resulting function looks like the following:

func GetFieldOrElse(v any, fn string, or any) any {
    segments := strings.Split(fn, ".")
    r := reflect.ValueOf(v)
    for _, field := range segments {
        if r.IsNil() {
            return or
        }
        r = reflect.Indirect(r).FieldByName(field)
    }
    return r.Interface()
}

// pi is a protobuf message and ExtraParams is a nested message inside `pi`
GetFieldOrElse(pi.ExtraParams, "Make", sql.NullString{})
GetFieldOrElse(pi.ExtraParams, "Model", sql.NullString{})
GetFieldOrElse(pi.ExtraParams, "LensModel", sql.NullString{})
GetFieldOrElse(pi.ExtraParams, "Aperture.Numerator", sql.NullInt64{})
GetFieldOrElse(pi.ExtraParams, "Aperture.Denominator", sql.NullInt64{})

I tried to look for a compile-time solution (i.e. without reflection) but failed. Is this the idiomatic way of achieving this goal?





vendredi 20 octobre 2023

Title: Why does Spring Data JDBC use reflection in PersistentPropertyAccessor, and could code generation improve performance?

Question: I'm currently working with Spring Data JDBC, and I've noticed that PersistentPropertyAccessor relies on reflection to access and manipulate properties. I understand that reflection can be slow, and I'm wondering why this choice was made.

  1. What are the reasons behind using reflection in PersistentPropertyAccessor in Spring Data JDBC?

  2. Have there been any performance considerations taken into account when choosing reflection as the method for property access?

  3. Could using code generation tools like MapStruct provide a performance improvement in this context, and are there any trade-offs to consider?

    I'm interested in understanding the design decisions and potential performance enhancements related to this specific aspect of Spring Data JDBC. Any insights or best practices in this area would be greatly appreciated.





mercredi 18 octobre 2023

Can a closed generic type be activated via reflection?

My question here is related to this question, which has received sufficient attention but no answers/comments so far.

In response to my discovery that t remains an empty List(Of Type) after running RegisterAssemblyTypes() (further down, in my edit), I dug into the Autofac source code a bit. What I found is interesting, especially for this case.

It seems that Autofac considers a closed generic type to be non-registerable, at least when specified at runtime. We find this in the comments of the internal function FilterAndRegisterConcreteTypes():

Filters a list of types down to only those that are concrete, not open generic, and allowed by the provided activator data.

Since t emerges clean and unscathed, it seems that Autofac considers the ZipCodeRepository (Of ZipCode) type (and its cousins) unregisterable when loaded at runtime via reflection. Note that we can register that specific type at design time all day long, like so:

Builder.RegisterType(Of ZipCodeRepository(Of ZipCode))

...but for some unknown reason (to me, at least) it gets dropped when registering via reflection. Curiously, however, it doesn't seem to satisfy the requirements for exclusion.

So why is Autofac's RegisterAssemblyTypes() function filtering out my repositories?





How to cast object to Func

public static class PropertyAccessor
{
    public static Expression Create<T>(string propertyName)
    {
        var property = typeof(T).GetProperty(propertyName);
        if (property is null)
        {
            return null;
        }

        var result = typeof(PropertyAccessor).GetMethod(nameof(CreateExpression))!
            .MakeGenericMethod(typeof(T, property.PropertyType)
            .Invoke(null, new object[] { propertyName });
    }

    private static Expression<Func<TIn, TOut>> CreateExpression<TIn, TOut>(string propertyName)
    {
        var parameter = Expression.Parameter(typeof(TIn));
        var body = Expression.Property(parameter, propertyName);
        return Expression.Lambda<Func<TIn, TOut>>(body, parameter);
    }
}

I'm tried to cast using Convert and other things, but without knowing TIn and TOut in compile time it's unable to cast





mardi 17 octobre 2023

Can Google Audit Reflection Pass

May I ask if reflection can be used for Bluetooth pairing in Google's app? Will Google Play review pass

Can Google's review reflection pass? I used the reflection method during the development of the app to adapt to the successful Bluetooth pairing of Huawei Hongmeng phones





lundi 16 octobre 2023

How to ensure Java has access to on-the-fly compilated classes?

Basically, I am generating files with Java Reflection. When using INtelliJ, everything works fine, everything is generated as it should. During the generation, I build some files I generated so I can use more Reflection on them. This is the code I use to do so :

private Class<?> compile(File sourceFile, String pack) throws ClassNotFoundException, IOException {
        File output = new File(Constants.BASE_TARGET_PATH);
        output.mkdirs();

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

        StandardJavaFileManager standardJavaFileManager = compiler.getStandardFileManager(null, null, null);
        standardJavaFileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(output));
        Iterable<? extends JavaFileObject> compilationUnits = standardJavaFileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile));
        compiler.getTask(null, standardJavaFileManager, null, null, null, compilationUnits).call();
        standardJavaFileManager.close();


        URLClassLoader urlClassLoader = URLClassLoader.newInstance(new URL[] {output.toURI().toURL()});
        Class<?> dynamicClass = urlClassLoader.loadClass(pack + "." + sourceFile.getName().replaceFirst("[.][^.]+$", ""));

        return dynamicClass;
    }

When I try to package my generator in a .jar, this does not work because, even though some of my custom annotations have been generated correctly, Java can't find them so it can't import them when building. This is the error I get :

10:47:18.928 [main] INFO com.foo.codegeneration.generators.ControllerGenerator -- Generated ZoneController
compiling annotations
compiled IntermediateTableAttribute.java
compiling presentationals
src\main\java\com\foo\jpadataserverprototype\presentation\presentational\PresentationalCategory.java:3: error: package com.foo.jpadataserverprototype.presentation.presentational.annotations does not exist
import com.foo.jpadataserverprototype.presentation.presentational.annotations.*;
^
1 error
java.lang.ClassNotFoundException: com.foo.jpadataserverprototype.presentation.presentational.PresentationalCategory
        at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:445)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:587)
        at java.base/java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:872)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
        at com.foo.codegeneration.GeneratedPresentationalRetriever.compile(GeneratedPresentationalRetriever.java:65)
        at com.foo.codegeneration.GeneratedPresentationalRetriever.retrieveEntities(GeneratedPresentationalRetriever.java:43)
        at com.foo.codegeneration.generators.MapperGenerator.<init>(MapperGenerator.java:31)
        at com.foo.codegeneration.CodeGenerator.main(CodeGenerator.java:93)
10:47:19.503 [main] INFO com.foo.codegeneration.generators.MapperGenerator -- Generating CategoryMapper...
Exception in thread "main" java.util.NoSuchElementException: No value present
        at java.base/java.util.Optional.get(Optional.java:143)
        at com.foo.codegeneration.GeneratedPresentationalRetriever.getEntityByName(GeneratedPresentationalRetriever.java:79)
        at com.foo.codegeneration.generators.MapperGenerator.generateEntityToDTOMapMethod(MapperGenerator.java:128)
        at com.foo.codegeneration.generators.MapperGenerator.generate(MapperGenerator.java:63)
        at com.foo.codegeneration.CodeGenerator.main(CodeGenerator.java:96)

I tried to change the Standard output class location, but I can't seem to find where to put the compiled classes. I also tried many other things not related to this problem when trying to understand what was the problem.





Is it possible to AddModelError for ModelStateDictionary with Reflections?

I have a controller which i doesn't know at compile time. So i need to use reflections to add a modelError. Is that even possible? Or is there another way to do that?

Here is how i thought it might work (but it doesn't).

var modelProperty = controller.GetType().GetProperty("ModelState");
var addErrorMethod = typeof(ModelStateDictionary).GetMethod("AddModelError", new[] { typeof(string), typeof(string) });
addErrorMethod.Invoke(modelProperty, new object [] { "key", "message" });

The error i get: Object does not match target type.





Static member does not have a most specific implementation in the interface [closed]

I've been trying to create a solution for a SQS & .Net solution. Also, I'm new working with SQS and I watched this video Nick Chapsas YT Channel & downloaded GitHub repo used on that video. And, guess what ? dit not work on my pc :D, got this message "Static member 'IMessageHandler.MessageType' does not have a most specific implementation in the interface". I've never used abstract static on interfaces before. So, guys if any of you can help me with this error and explain why this is happenning, I'd really appreciate that because it seems no body else had this error.

I also tried more things like change reflection implementation and DI(classes, interfaces, etc). But, everything ended up worse than before.

VS: 2022 latest version 10/16/2023

Target Framework: .Net 7





dimanche 15 octobre 2023

Get a pointer to a class field inside a class in Java

public class Example {
   private String field_;
   private Stack stack_;
   public void Metod() {
       Field field = this.getField("field_"); !!!! 
   }
}

I want to save a pointer to a class field on the stack, but I don't understand how to get this pointer. I tried using getField, but it didn't work.





samedi 14 octobre 2023

Speed ​up Roslyn solution analyser

I'm developing a tool to visualize programs written in C#, including .sln, .csproj, and .cs files. It has functionality for displaying project references, class diagrams, and method diagrams. However, I've encountered a problem: it takes much more time than I expected to load a .sln file. Is there any way to speed up the process of loading .sln files, considering my specific needs? I believe it performs more actions than necessary.

I tried examining the MSBuildWorkspace class to find any properties that could make it perform fewer actions, but it didn't help.





vendredi 13 octobre 2023

Checking if a method is declared in an interface

I want to check if a method of a class is declared in an interface.

AInterface.java:

public interface AInterface {
    Object hi();
}

AClass.java:

public class AClass implements AInterface {
    public String hi() {
        return "hello!";
    }
}

Main.java:

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        for (Method md : AClass.class.getDeclaredMethods()) {
            System.out.println("Declaring class: " + md.getDeclaringClass().getName());
            System.out.println("Return type: " + md.getReturnType().getName());
            System.out.println("Name: " + md.getName());
            System.out.println();
        }
    }

}

md.getDeclaringClass() returns the same class for both methods. So how do I check which one is in the class?





C# Serialize Generic Wrapper class

I'm trying to implement JSON serialization for an Optional wrapper class. I want the serialization to be akin to a nullable type, so:

"myOptional": null

for null, and

"myOptional": 2

or

"myOptional": { . . . }

for objects.

This is fine until I get to a wrapped object, I don't know how to tell the serializer to "serialize this object like you normally would". The Microsoft docs lead me to believe that I have to implement JsonConverterFactory, but I don't know how to tell the writer to serialize the inner object automatically.

public class OptionalTypeJsonConverterFactory : JsonConverterFactory
{
    public override bool CanConvert(Type typeToConvert)
    {
        return typeToConvert
            .GetGenericArguments()[0].IsClass;
    }

    public override JsonConverter CreateConverter(
        Type type,
        JsonSerializerOptions options
    )
    {
        return (JsonConverter)Activator.CreateInstance(
            type: typeof(OptionalJsonConverter<>).MakeGenericType(type.GenericTypeArguments[0]),
            bindingAttr: BindingFlags.Instance | BindingFlags.Public,
            binder: null,
            args: new object[] { options },
            culture: null
        )!;
    }

    private class OptionalJsonConverter<T> : JsonConverter<Optional<T>>
        where T : struct
    {
        public OptionalJsonConverter(JsonSerializerOptions options) { }

        public override Optional<T>? Read(
            ref Utf8JsonReader reader,
            Type typeToConvert,
            JsonSerializerOptions options
        )
        {
            throw new NotImplementedException();
        }

        public override void Write(
            Utf8JsonWriter writer,
            Optional<T> optional,
            JsonSerializerOptions options
        )
        {
            if (optional.IsNone())
            {
                writer.WriteNullValue();
            }
            else
            {
                // don't know what to put here. I want to serialize objects as if the wrapper was never there.
            }
        }
    }
}

How should I go about achieving this? As an example, if Optional<T> has T = MyClass and MyClass is

{
  public int ID { get; set; } = 2
  public string Name { get; set; } = "myname"
}

then I want this to serialize to

"optionalofMyClass": 
{
  "ID": 2,
  "Name": "myname"
}




Java: reflection on grandchild class attributes

I'm facing an issue while trying to use Java reflection.

I have a PermanentObject class, that implements a general method to turn an object into a JSON string (the syntax is not yet completely implemented so glide past it)

This is the code of the method:

@Override
public String toFileFormat() {
        String info = "";
        
        try {
            
            Class myClass = this.getClass();
            Class mySuperclass = myClass.getSuperclass();
            Field[] superclassFields = mySuperclass.getDeclaredFields();
            Field[] myFields = myClass.getDeclaredFields();
            
            info += "{\n";
            
            for (int i = 0; i < superclassFields.length; i++) {
                myFields[i].setAccessible(true);
                info += "\"" + superclassFields[i].getName() + "\":\"" + superclassFields[i].get(this) + "\",\n";
            }
            
            for (int i = 0; i < myFields.length; i++) {
                myFields[i].setAccessible(true);
                info += "\"" + myFields[i].getName() + "\":\"" + myFields[i].get(this) + "\"";
                if (i < myFields.length - 1) info += ",";
                info += "\n";
            }
            
            info += "}";
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return info;
}

I then have a User abstract subclass that extends PermanentObject, and a Professor subclass that extends User.

When invoking the method tho I get this error: java.lang.IllegalAccessException: class esercizio2.permanence.PermanentObject cannot access a member of class esercizio2.logic.users.User with modifiers "private"

I was wondering why this is

I can solve the problem by implementing the method in the User class rather than in the PermanentObject class, but this leads to duplication of code since there are other PermanentObject subclasses that will need to use this.

Thanks for the help :>





mercredi 11 octobre 2023

How can I dynamically register DbSets into DbContext and add a row to the table?

I have too many entities and registering everyone of them is giving me a headache not to mention the load to instantiate the dbcontext. so I tried to dynamically register the dbsets.

To dynamically register DbSets into DbContext I used the article in this link: text I added an extension as a file:

public static class ModelBuilderExtensions
{
    public static void RegisterAllEntities<BaseModel>(this ModelBuilder modelBuilder, params Assembly[] assemblies)
    {
        IEnumerable<Type> types = assemblies.SelectMany(a => a.GetExportedTypes()).Where(c => c.IsClass && !c.IsAbstract && c.IsPublic &&
          typeof(BaseModel).IsAssignableFrom(c));
        foreach (Type type in types)
            modelBuilder.Entity(type);
    }
}

then I made an abstract class called BaseEntity that all my entities implimented.

and inside the ApplicationDbContext I overrode the OnModelCreating method:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            var entitiesAssemblyInt = typeof(BaseEntity<int>).Assembly;
            var entitiesAssemblyGuid = typeof(BaseEntity<Guid>).Assembly;
            modelBuilder.RegisterAllEntities<BaseEntity<int>>(entitiesAssemblyInt);
            modelBuilder.RegisterAllEntities<BaseEntity<Guid>>(entitiesAssemblyGuid);
        }

it works perfectly in migration but when I want to use the dbcontext in my commandHandler to add a row to my table named client I don't know how to call client from context.

context.Client.Add(client);

doesn't work because I didn't register the dbsets directly into dbcontext and there is no Client in the context.





Can i force a Type loaded in the default AssemblyLoadContext to return a type loaded in my plugin AssemblyLoadContext?

I am migrating an testing application from .NET Framework to .NET. The main purpose was to start another application and run tests on that application with nunit. For the sake of running multiple Test classes in succession, the application lived isolated in a dedicated AppDomain. In .NET this approach no longer works as there is only ever one AppDomain.

This approach was mainly used to make sure that everything was cleanly initialized (especially in regards to static members).

I am trying to rebuild this isolation with AssemblyLoadContext, by creating a new AssemblyLoadContext and loading all needed assemblies of the application into it and creating the TestSuite within that AssemblyLoadContext.

        private IEnumerable<TestSuite> BuildFrom(ITypeInfo typeInfo, IPreFilter filter)
        {
            foreach (var suite in m_source.BuildFrom(typeInfo, filter))
            {
                m_context = new AssemblyLoadContext(suite.Name, true);
                var assembly = m_context.LoadFromAssemblyPath(typeof(PlatformTestSuite).Assembly.Location);
                m_context.LoadFromAssemblyPath(typeof(TestPlatform).Assembly.Location);
                m_context.LoadFromAssemblyPath(typeof(ServiceManager).Assembly.Location);
                m_context.LoadFromAssemblyPath(typeof(UserInterface).Assembly.Location);

                yield return (TestSuite)assembly.CreateInstance(typeof(PlatformTestSuite).FullName, false, BindingFlags.Default, null, new object[]{suite, m_context}, CultureInfo.CurrentCulture,  null);
            }
        }

This should ensure that all types used in the constructor are loaded from my newly created context. This works for most types, except the following:

var converter = TypeDescriptor.GetConverter(typeof(InformationViewModel));

Here, TypeDescriptor is loaded from the Default AssemblyLoadContext, as it is intended as a shared dependency. InformationViewModel is loaded from my custom context. The resulting type "InformationViewModelConverter" is also loaded from my custom context. However, the resulting converter is of type "InformationViewModelConverter", which is loaded from the Default AssemblyLoadContext. The converter in turn then uses only types loaded from the Default AssemblyLoadContext and cannot convert my types, as they are loaded from a different context.

My question

Is there a way to keep TypeDescriptor in the Default Context as a shared dependency and still make sure that created converter are of the type loaded from my custom context? If possible, this should happen without the programmer needing to think about it when using TypeDescriptor.GetConverter().





mardi 10 octobre 2023

Copy values from php object to eloquent entity

I am creating an API using laravel 10 and eloquent and I want to copy values from an object read from the http request to anoter object that is a laravel entity, I have an object with a lot of properties and I would like to copy automatically all the properties to another object so I can save the changes to the DB without copying values from request to model using $obj1->name = $request->name for each property in my object.

Let me explain:

I have this class:

class Usuarios extends Model
{
    protected $table = 'usuarios';
    protected $primaryKey = 'id';
    protected $fillable = [... a lot of properties]
}

I have this method in my controller:

function save(Request $request){
    $data = $request->all();
    $user = new Usuario($data);
    $userFromDB = Usuarios::find($data->id);
    // is there a way to do this? I just want to copy properties 
    // without creating a new object, or is there another way to do this? 
    // using reflection or something like that? or does laravel have 
    // any other way to do this without copying each value??
    copy_values($user,$userFromDB);  //????????????
    $userFromDB->save();
}

is this possible?

Thanks





Debugging Enumerators and Coroutines: Use Reflection to get the current line of an iterator block

I am building a Coroutine wrapper system. I would like users to be able to jump to the Coroutine's last yield statement, or "state".

The wrapper is implemented as an Enumerator wrapper, that is passed to StartCoroutine. I have access to the iterator object, its current value and the source MonoBehaviour.

Here's the gist of it

    public static CoroutineWrapper StartCoroutineWrapped(this MonoBehaviour component, IEnumerator coroutineEnumerator)
    {
      CoroutineWrapper wrapper = new(component, coroutineEnumerator);
      component.StartCoroutine(wrapper);
      return wrapper;
    }

public class CoroutineWrapper: IEnumerator
  {
    public readonly MonoBehaviour Source;

    public readonly IEnumerator Child;

    internal CoroutineWrapper(MonoBehaviour source, IEnumerator coroutine)
    {
      Source = source;
      Child = coroutine;
    }

    public bool MoveNext() => Child.MoveNext();

    public object Current => Child.Current;
  }

Currently, the only ways I have found to be able to do this:

  1. force the user to wrap their return value inside an object. In Debug mode, that object stores a stack trace in its constructor, which can be recovered.
yield return new YieldWrapper(null);
yield return new YieldWrapper(new WaitForEndOfFrame());
//etc

In Current or MoveNext, I check for the type of the yielded value, and store the frame if it is a YieldWrapper.

object Current {
  get {
    object current = Child.Current
    if (current is not YieldWrapper wrapper) return current;
    Trace = wrapper.Trace;
    return wrapper.Value;
  }
}
  1. allow the user to set a flag on the coroutine that will break on the next MoveNext call. Users can then move into the MoveNext call to see the current state.

  2. display the hidden "<>1__state" value of the iterator, which gives a rough idea of the state of the coroutine, but cannot be mapped to any line code.

Obviously they all have drawbacks

  1. Any yield statement that's not wrapped cannot be jumped to. Lots of needless allocations even in Release mode. Otherwise the best hope for a solution.

  2. Cannot see current state, only next one. Useless if a "WaitWhile" instruction is blocked and you want to find which one.

  3. Cannot actually be used as is, only by comparing it to others. Can tell you if a coroutine is actually changing state, or staying in the same one.

Potential ideas:

  • Find some way to get the stacktrace of a method before or after calling the method. If that were possible, I could easily do this with MoveNext and get a file name and line.

  • Find some hidden reflection magic to turn that "<>1__state" into a file position. Current research tells me "<>1__state" is not documented, not guaranteed to exist and might kill my dog if I rely on it in any way shape or form.

  • Instead of displaying said state, store it over multiple iterations to build a map of the iterator. But since I can never get a guaranteed stack trace inside the user coroutine, not actually that helpful. Could be used to infer that some states yield to more stalling maybe.

  • Simply use UniRx instead





jeudi 5 octobre 2023

How to find out type args of a superclass?

I have

trait Foo[T]
class Bar extends Foo[String]

If I do typeOf[Foo[String]].typeArgs, I get String back.

But typeOf[Bar].baseClasses.flatMap(_.typeArgs) is empty.

Is it impossible to find the actual complete super-type and a given type? (If it helps, I am actually writing a macro, so all the compile-time info should still be there ... though I don't think it actually matters, because I am only looking at types here, not actual objects) ...





mardi 3 octobre 2023

Scala/Java reflection array type

I am trying to instantiate case classes using reflection. I am using this reference code: https://gist.github.com/ConnorDoyle/7002426


import scala.reflect.runtime.universe._

object ReflectionHelpers extends ReflectionHelpers

trait ReflectionHelpers {

  protected val classLoaderMirror = runtimeMirror(getClass.getClassLoader)

  /**
    * Encapsulates functionality to reflectively invoke the constructor
    * for a given case class type `T`.
    *
    * @tparam T the type of the case class this factory builds
    */
  class CaseClassFactory[T: TypeTag] {

    val tpe = typeOf[T]
    val classSymbol = tpe.typeSymbol.asClass

    if (!(tpe <:< typeOf[Product] && classSymbol.isCaseClass))
      throw new IllegalArgumentException(
        "CaseClassFactory only applies to case classes!"
      )

    val classMirror = classLoaderMirror reflectClass classSymbol

    val constructorSymbol = tpe.declaration(nme.CONSTRUCTOR)

    val defaultConstructor =
      if (constructorSymbol.isMethod) constructorSymbol.asMethod
      else {
        val ctors = constructorSymbol.asTerm.alternatives
        ctors.map { _.asMethod }.find { _.isPrimaryConstructor }.get
      }

    val constructorMethod = classMirror reflectConstructor defaultConstructor

    /**
      * Attempts to create a new instance of the specified type by calling the
      * constructor method with the supplied arguments.
      *
      * @param args the arguments to supply to the constructor method
      */
    def buildWith(args: Seq[_]): T = constructorMethod(args: _*).asInstanceOf[T]

  }
}

Everything works great for most types of fields in the case class. My only issue is when trying to populate array fields.

Basically it boils down to this issue:

case class MyClass(arr: Array[String])

object Main {
  def main(args: Array[String]): Unit = {
    val f = new CaseClassFactory[MyClass]
    f.buildWith(Seq(Array[String]("1","2","3"))) //This works
    f.buildWith(Seq(Array[Object]("1","2","3"))) //This does not work
  }
}

Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at scala.reflect.runtime.JavaMirrors$JavaMirror$JavaVanillaMethodMirror1.jinvokeraw(JavaMirrors.scala:415)
    at scala.reflect.runtime.JavaMirrors$JavaMirror$JavaMethodMirror.jinvoke(JavaMirrors.scala:380)
    at scala.reflect.runtime.JavaMirrors$JavaMirror$JavaVanillaMethodMirror.apply(JavaMirrors.scala:396)

In my use case the array is being created using reflection as well as an Array[Object]. I have the scala.reflect.api.Types#Type of the array field of the case class. I need to somehow convert the existing array to one with the correct type I understand the internal implementation of arrays causes the issue. How can I convert the array to the needed type at runtime. I tried to use Arrays.copyOf but did not get it to work





How to use Reflection in Java to dynamically create classes?

Im sorry if this will sound confusing but I will try best. I have a question about dynamically creating classes using reflection.

I have a holding class, that only has member attributes of 'subclasses', all the holding class's attributes are the same subclass type but just have different variable names.

The holding class will receive a json object with attributes like idNo, some text, and an identifier, this identifier will point to the specific subclass that will have its attributes created.

So three parts here

  1. Holding class with attributes of sub classes
  2. JSON Array
  3. HashMap that contains identier to the name of the subclass like

HashMap

    dictionary.put("blue", "two");
    dictionary.put("black", "one");
    dictionary.put("red", "three");
    dictionary.put("green", "four");

Json Array is something like

"[{\"identifier\":\"blue\",\"invoId\":1,\"questNo\":1,\"seqId\":\"1a\","answerText\":1},{\"identifier\":\"red\",\"invoId\":1,\"questNo\":2,\"seqId\":\"2a\",\"answerText\":0},{\"identifier\":\"green\",\"invoId\":1,\"questNo\":3,\"seqId\":\"3a\",\"answerText\":1},{\"identifier\":\"black\",\"invoId\":1,\"questNo\":4,\"seqId\":\"4a\"}.\"answerText\":0]"

As you can see, the JSONARRAY has a colour, the HashMap has a colour to a number, and that number specifies which subclass to construct.

HOLDING CLASS
`public class HoldingClass {
    private SubClass one;
    private SubClass two;
    private SubClass three;
    private SubClass four;`
    



SUBCLASS
'public class SubClass<T> {
    private String identifier;
    private String seqId;
    private int questNo;
    boolean answerText;
    private int invoId = 1;'

The part I cannot figure out, is how to use reflection such that, it points to a specific subclass attribute in the holding class, then construct's that subclass of the specific array element's info.

Any help would be greatly appreciated!