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