lundi 31 octobre 2022

Golang set reflect.Value by sql.NullString

How can I set item.SourceId(the type is sql.NullString) by inData.SourceId(the type is String) ? I don't know how to write the code in the red block enter image description here

I found reflect.ValueOf(&foo).Elem().Field(0).SetInt(321) in Using reflect, how do you set the value of a struct field?. Is there something like SetInt for sql.NullString ?

   type InDataType struct {
        Id          string  
        SourceId    string
    }

    type ItemType struct {
        Id          string      
        SourceId    sql.NullString 
    }

setField(item, inData, "SourceId")


func setField(item interface{}, inData interface{}, fieldName string) {
    // t := reflect.TypeOf(inData)
    // fmt.Println(t)
    itemValue := reflect.ValueOf(item).Elem().FieldByName(fieldName)
    itemType := reflect.ValueOf(item).Elem().FieldByName(fieldName).Type().String()
    fmt.Println(itemType, ",", itemValue)

    inDataValue := reflect.ValueOf(inData).Elem().FieldByName(fieldName)
    inDataType := reflect.ValueOf(inData).Elem().FieldByName(fieldName).Type().String()
    fmt.Println(inDataType, ",", inDataValue)
    if itemType == "sql.NullString" {
        // itemValue = sql.NullString{String: inDataValue.Value().String(), Valid: inDataValue.String() != ""}

    }
}




dimanche 30 octobre 2022

C# : is it possible to access sibling props of a prop?

Is there any way to access sibling properties of a property ? I'm interested how to access the containg type of a property.

protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
{
    var t = TypeDescriptor.GetProperties(value);
    object defaultValue = Activator.CreateInstance(value?.GetType());
    PropertyInfo propertyInfo = defaultValue.GetType().GetProperty(_property.Name);
    if (propertyInfo.GetValue(value) == _property.Value)
    {
        //TypeConverter tc = TypeDescriptor.GetConverter(someType);
    }
    else
    {

    }

    return defaultValue.Equals(value)
        ? new ValidationResult($"Parameter \"id\" cannot have its default value.")
        : null;
}




samedi 29 octobre 2022

Function returns empty objects but right before the return object is populated [duplicate]

I tried to make a function that will return any type of DTO from a stored procedure with EF CORE 6. My approach:

  • got a DataTable
  • used reflection to map the DataTable to a generic T

DTO

    public class JobsDTO
    {
        public string Luna;
        public int NrSaptamana;
        public string ServiciuPrestat;
        public bool IsServiciuPrestat;
    }

This is the function that does it and it works as expected. It populates a List with data

public async Task<List<T>> ExecuteProc<T>() where T : new()
        {
            DataTable dataTable = new DataTable();
            var connection = databaseContext.Database.GetDbConnection();
            var dbFactory = DbProviderFactories.GetFactory(connection);

            using(var cmd = dbFactory!.CreateCommand())
            {
                cmd.Connection = connection;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "GetJob";

                using(var adapter = dbFactory.CreateDataAdapter())
                {
                    adapter.SelectCommand = cmd;
                    adapter.Fill(dataTable);
                }
            }
            List<T> list = new List<T>();

            FieldInfo[] fields = typeof(JobsDTO).GetFields();

            foreach (DataRow dr in dataTable.Rows)
            {
                T t = new T();
                foreach (FieldInfo fi in fields)
                    fi.SetValueDirect(__makeref(t), dr[fi.Name]);

                list.Add(t);
            }
                
            return list;
        }

The enpoint

[HttpGet("getJobs")]
        public async Task<IActionResult> GetJobs()
        {
            try
            {
                var res = await unitOfWork.ExecuteProc<JobsDTO>();
               
                return Ok(res);  *HERE I TOOK THE PRINTSCREEN*
            }
            catch(Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

Please look at the values of res right before returning Ok(res) Data before reutrn And here is the result that arrives in swagger Data after return

I assumed it has something to do with the object reference so I copied by value an object from list and returned the copy insted but the result was the same.

If anyone has a different approach in getting DTOs from stored procedures with ef core 6 please let me know





Compare between 2 class properties dynamic

I have this person class

    public class Person : IPerson
    {
        public Person(int id, string fullName, int salary, int age, decimal height)
        {
            Id = id;
            FullName = fullName;
            Salary = salary;
            Age = age;
            Height = height;
            InitTimer();
        }

        public int Id { get; private set;}

        public string FullName { get; private set;}

        public int Salary { get; private set;}

        public int Age { get; private set;}

        public decimal Height { get; private set;}
}

I want by user input (for the name of the property) to compare which value is bigger (between existing value and what we wanna add now).

        public IPerson Run(IPerson MaxOrMinPerson, string PropertyName, IPerson PersonToAdd)
        {
            var currentMaxMinPerson = MaxOrMinPerson.GetType().GetProperties().Where(x => x.Name.ToLower() == PropertyName).FirstOrDefault().GetValue(MaxOrMinPerson, null);
            var currentMaxMinPersonType = MaxOrMinPerson.GetType().GetProperties().Where(x => x.Name.ToLower() == PropertyName).FirstOrDefault();
            var personToAddPropertyValue = PersonToAdd.GetType().GetProperties().Where(x => x.Name.ToLower() == PropertyName).FirstOrDefault().GetValue(PersonToAdd, null);
            var personToAddPropertyValueType = PersonToAdd.GetType().GetProperties().Where(x => x.Name.ToLower() == PropertyName).FirstOrDefault();

            return TheBiggerValueBetweenCurrentMaxMinPersonAndPersonToAdd
        }

I'm getting the value but as object. the value could be any of the class members types (int, string, decimal).

how can I do it dynamically?





vendredi 28 octobre 2022

C# cast type to generic interface without knowing interface type

Is it possible to cast to a generic interface type where you don't know the actual generic type but DO know that the type is derived from some shared interface?

I have a generic interface:

public interface IFooGenericObjectProvider<TModel> where TModel : class, IBaseModelType
{
    SomeObject ProvideSomeObject(TModel model);
}

Classes implement it like so:

public class SomeObjectProvider : IFooGenericObjectProvider<ConcreteModel>
{
    public SomeObject ProvideSomeObject(ConcreteModel model)
    {
        // create instance of 'SomeObject' using 'ConcreteModel'
    }
}

And I'm creating instances of types which implement the IFooGenericObjectProvider<TModel> type via reflection / Activator.CreateInstance

This all works great however the issue arises when I need to use the created types.

I'm trying to cast them to IFooGenericObjectProvider<IBaseModelType> when I need to call the method from the implemented interface, and since all ConcreteModel instances derive from a shared IBaseModelType interface, I figured this would be perfectly fine but it throws an exception during the cast:

Unable to cast object of type 'SomeObjectProvider' to type 'IFooGenericObjectProvider`1[IBaseModelType]'.

I can fix this by changing to:

public class SomeObjectProvider : IFooGenericObjectProvider<IBaseModelType>
{}

However the caller is provided with an instance of IBaseModelType rather than ConcreteType which is what I would like:

public SomeObject ProvideSomeObject(IBaseModelType model)
{
    // This works, but would like access to the concrete model type instead
}

I know that I can cast IBaseModelType model to the concrete type but this isn't as nice and is an extra step for the caller.

Is what I'm trying to achieve possible? Perhaps theres another approach that would work better?





How to change Time.deltaTime value?

Is there any way to change Unity's Time.deltaTime value with reflection or with some other method. We have a replay system which we use mainly for bug hunting. It stores all the input events and delta time values than we can simulate the game exactly the same . But to force delta time values we have to define and use a custom deltaTime variable. I want to get rid of that variable and also force unity's systems to use our value.

class SystemManager
{
     List<System> systems;
     void Update()
     {
          if(replay)
          {
               DTime.deltaTime = deltaTimeBuffer.GetValue();
          }else
          {
               DTime.deltaTime = Time.deltaTime;
          }

          foreach system in systems
               system.Update();

     }
}


class System
{
     void Update()
     {
          position += DTime.deltaTime * velocity;
          // I want to get rid of DTime.deltaTime and use Time.deltaTime
     }
}




jeudi 27 octobre 2022

Getting method with Generic Types within signature using Reflection

I would like to invoke this method using Reflection but am a bit confused with getting the method with getDeclaredMethod(), how would this be done?

 private static <T> void registerServiceClass(final Class<T> service, final T instance) {
        Collection<Class<?>> serviceClasses = SERVICE_MAP.get(service);
        if (null == serviceClasses) {
            serviceClasses = new LinkedHashSet<>();
        }
        serviceClasses.add(instance.getClass());
        SERVICE_MAP.put(service, serviceClasses);
    }
}




Get annotation value via reflection

I am trying to get all the "Keys" of annotations for use later, I am initializing the value like this:

private val wgKeys = SpecialRequestContext::class.members.associate { m ->
    m.name to run {
        val headerAnnotation = m.annotations.find { a -> a is Header } as? Header
        headerAnnotation?.key
    }
}

Unfortunately, the result is a Map with name for keys (correct), but all the values are null. While debugging I see that m.annotations has no values.

Are annotations not available at this step?





mercredi 26 octobre 2022

How to judge the type of Struct and modify it in Golang?

Original question:

I want to make a function that takes in different commodity Struct and encrypts their ids. I have a encryption function:

func encryption(in string, typeOf string) string {
  result := in + typeOf
  return result } 

and 2 commodity Struct:

type cloth struct {
  clothId   string
  name string }

type pants struct {
  pantsId   string
  name string } 

I want to modify them through a function, by passing in variadic parameters, to perform different operations, it should modify the id of the Struct

func encryptId(in interface{}) {
  switch in := in.(type) {
  case cloth:
      in.clothId = encryption(in.clothId, "cloth")
  case pants:
      in.pantsId = encryption(in.pantsId, "pants")
  default:
      return
  }
}

But although this function can determine the type, it cannot modify them, how can I do? I found theseonline, but it can only judge and not modify. I hope after doing this

func main() {
  clo := cloth{"cloth", "blue"}
  pan := pants{"pants", "green"}
  encryptId(clo)
  encryptId(pan)
  fmt.Println(clo)
  fmt.Println(pan) }

it will output

{clothcloth blue}

{pantspants green}

Solved by mkopriva

It cannot modify them because they are copies. Use pointers instead. E.g. encryptId(&clo) and inside the function's switch use case *cloth:

go.dev/play/p/4uYzqZ0BKVy (note the assignment in the switch statement, i.e. switch in := in.(type) {)

func encryptId(in interface{}) {
    switch in := in.(type) {
    case *cloth:
        in.id = encryption(in.id)
    case *pants:
        in.id = encryption(in.id)
    default:
        return
    }
}

func main() {
    clo := cloth{"cloth", "blue"}
    pan := pants{"pants", "green"}
    encryptId(&clo)
    encryptId(&pan)
    fmt.Println(clo)
    fmt.Println(pan)
}

Done.





mardi 25 octobre 2022

Avoid Unchecked cast warning to generic Type when using reflection

I have a piece of code which looks like this,

the field is a private static final HashMap from a source code which I need to modify.

void <T extends MyInterface> registerMyClass (Class<T> myClass) throws NoSuchFieldException, 
                                                                       IllegalAccessException, 
                                                                       ClassCastException {

    Field field = SomeClass.class.getDeclaredField(FIELD_NAME);
    field.setAccessible(true);
    Map<Class, Collection<Class<?>>> map = (Map<Class, Collection<Class<?>>>) field.get(null);
    Collection<Class<?>> classes= map.computeIfAbsent(KeyClass.class, k -> new LinkedList<>());
    
    if (!classes.contains(myClass)) {
        services.add(myClass);
    }

}

I would like to do this without getting an Unchecked warning which does not comply with the requirements for a merge request.

Is there an approach to achieve the same result without causing an unchecked cast warning?





lundi 24 octobre 2022

Overriding toString() of generated code in Java 8

I am required to use a generated Java class to connect with a third-party application, and we frequently have to regenerate that Java class with new field names. The generated Java class does not have a toString() method for easy viewing of the fields, and the toString() method it inherits from its base class (which we cannot change) is useless for viewing fields in the generated Java class. I am not permitted to change the generated Java class in any way except to regenerate it when necessary, and I do not have access to the class code generator itself. I also cannot use any other Java version than 8. We have many generated Java classes like this.

Is there a way to extend the useless toString() method used by the generated code so we can see the fields in the generated code classes? I'm not sure that wrapping with a method like "stringify" would work because lots of code relies on the generated code classes functioning as they do right now; perhaps toString() can be extended dynamically with reflection?

Can anyone give me any ideas for how I might be able to make this work?

Thanks!





dimanche 23 octobre 2022

Dynamically get top level package in source root

I world like to get a root package where inner package branching starts.

For example: src/main/java/com/my/pack/example

and inside there is a fist occurance of multiple packages: inner1 and inner2

Given this structure I want to get com.my.pack.example

I know I can iterate over packages starting from some class deep inside and do some filtering. but is there any easier way or existing util?





Call a method on any field of a specific type c#

I know that is easy with reflection to find a property of a specific name and call a method on it

            var fields = this.GetType().GetFields(BindingFlags.NonPublic |
                         BindingFlags.Instance).Where(x=>x.FieldType == typeof(IMyType));

            foreach (var field in fields)
            {
                var myMethod = typeof(ITenantService).GetMethod("MyMethod");
                var test = myMethod ?.Invoke(field, new object[]
                {
                    myParameter
                });
            }

This doesnt work because field is FieldInfo. GetFieldValue is a string which is of no use

How can I do this please?

What I am aiming for in the end is for something that given a type I find all of the fields that have a field of a specific type, and call my method on that field

Cheers

Paul





samedi 22 octobre 2022

How to Add a UnityEngine Assembly Reference Into a Code Snippet Invoked Using System.Reflection

I'm trying to add c# code compilation and execution at runtime to my unity game so that I can implement modding support. It's based around this code example so far:

https://gist.github.com/fearofcode/3abb41d0b1a60194765f1fdd81da5269. However, adding "using UnityEngine;" to the executed code in the string throws the following error:

error CS0246: The type or namespace name `UnityEngine' could not be found. Are you missing an assembly reference?

I assumed you had to add an assembly reference to the "references" variable so that the code could find the correct namespace, but both adding "UnityEngine.dll" or just "UnityEngine" to "references" and adding all of the used assemblies in the running script itsself via "AppDomain.CurrentDomain.GetAssemblies()" throws the following error for each unity related assembly:

error CS0006: Metadata file `name of the file' could not be found.

With the GetAssemblies() method 12 other assemblies are accepted and used like you would expect, but all of the unity specific ones throw errors.

Am I doing the right thing, but just in a wrong way? Or is there a different way to reference the required assemblies/namespaces that I just can't find?





vendredi 21 octobre 2022

Setting RenderingHints from a String value

I'm trying to populate some RenderingHints from a value that will be set using a String (e.g. from a value in the application.properties file), but cannot get it to pass through the value when setting the field dynamically.

Is there any easy way I can achieve this? I guess I'm either missing a Cast statement, or just not understanding how reflection works. Thanks.

import java.awt.RenderingHints;
import java.lang.reflect.Field;

...

// create the string we want to populate the hint from
String myHint = "VALUE_ANTIALIAS_ON";


// create the new hints that we want to populate
RenderingHints renderingHints = new RenderingHints(null);


// setting the value directly (like this) works:
renderingHints.put(RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);


// but using reflection to retrieve the field:
Field hintField = RenderingHints.class.getField(myHint);


// doesn't work...
renderingHints.put(RenderingHints.KEY_ANTIALIASING, hintField);


// and gives the error:
// public static final java.lang.Object java.awt.RenderingHints.VALUE_ANTIALIAS_ON incompatible with Global antialiasing enable key




jeudi 20 octobre 2022

Java generic parametrized parameter constrained by other parameters

I have a generic class, which has a function that returns an instance of a functional interface:

/**
 * @param <FF> - FF is a functional interface
 */
public abstract class MyFunctionalInterfaceGetter<FF> {
    public abstract <PC, AC> FF getMyFunction(Class<PC> pojoClass, Class<AC> attributeClass);
}

And I have a couple of derived classes:

public class MyGetterGetter extends MyFunctionalInterfaceGetter<java.util.function.Function> {
    public <PC, AC> Function<PC, AC> getMyFunction(Class<PC> pojoClass, Class<AC> attributeClass) {
         ...
    }
}
public class MySetterGetter extends MyFunctionalInterfaceGetter<java.util.function.BiConsumer> {
    public <PC, AC> BiConsumer<PC, AC> getMyFunction(Class<PC> pojoClass, Class<AC> attributeClass) {
         ...
    }
}

And the question:
I do not thing so, but I wanted to know if there is any way to constrain the returning parametrized type from the function parameters at the parent class.
Something like this:

public abstract class MyFunctionalInterfaceGetter<FF> {
    public abstract <PC, AC> FF<PC, AC> getMyFunction(Class<PC> pojoClass, Class<AC> attributeClass);
}

I am using Java-8





How can I get hold of a function reflectively within in the same module

I need to be able to be able to call a function reflectively that's defined within the same module e.g

a = getattr('foo_1')
b = a(5)

def foo_1(x) : return x*x

This fails because getattr requires 2 params, but I don't know what to put for the first param, as there is no enclosing type or other module to import by name. If feel sure that the answer is very simple, but I haven't found it yet.

(Yes, I know this looks silly - if the function is defined in the same module, why not just call it directly? The reason is that the code is being built dynamically from multiple sources and then run. foo_1 might or might not exist and will anyway be one of many functions following name style foo_<n>. I need to find the ones that do exist, and then call them. This is just a simplified example. I would also appreciate advice on the best way to test whether, say, foo_1 does or does not exist before attempting to call it.)





mercredi 19 octobre 2022

Check if a class has an explicit static constructor?

In the ECMA standard under $14.5.6.2 it states that having a static constructor affects the static field initialization order. I want a way to enforce this, but cannot find a way to check for an explicit static constructor in a type. It seems like the C# runtime automatically generates one if there isn't one already (and if the class has some static fields). Is it possible to check if a class has an explicit static constructor using reflection?

For example - the following will return a constructor in both these cases, and I cannot see any difference between them:

static class NoStaticConstructor
{
    public static string Field = "x";
}

static class HasStaticConstructor
{
    static HasStaticConstructor() {}
}

public void Test()
{
    typeof(NoStaticConstructor)
        .GetConstructors(BindingFlags.Static | BindingFlags.NonPublic)
        .ShouldBeEmpty(); // FAILS

    typeof(HasStaticConstructor)
        .GetConstructors(BindingFlags.Static | BindingFlags.NonPublic)
        .ShouldNotBeEmpty(); // SUCCEEDS
}




My annotation created with reflection API return null even when there is data

so I'm building ORM Manager from scratch with reflection API, everything works fine but there is one annotation @Table that i created and it doesn't want to work as it should. So annotation looks like this

@Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.TYPE)
   public @interface Table {
    String value() default "";
}

and I'm using it on my model class as so

@Entity
@Table(value = "Books")
public class Book {

and now i'm trying to get that value passed as a parameter like this

@Override
    void register(Class... entityClasses) throws SQLException {
        for (Class entityClass : entityClasses) {

            if (entityClass.isAnnotationPresent(Entity.class)) {

                String tableName;

                if (entityClass.isAnnotationPresent(Table.class)) {
                    tableName = entityClass.getClass().getDeclaredAnnotation(Table.class).value();
                } else {
                    tableName = entityClass.getSimpleName();
                }

Dont mind @Entity annotation it works fine. Only problem is that @Table annotation always returns null so it throws NullPointerException and crashing.

Where is a problem, how can i solve this. I already implemented @Column annotation and when i use .value() on @Column annotation it works fine so no clue why it doesn't work for @Table





Get class properties in string list in c#?

Please find the below entities :

public class Country
{
    public int Id;
    public string name;
    public string code;
}
public class City
{
    public int Id;
    public string name;
    public country {get;set;}
}
public class Person
{
    public int Id;
    public string name;
    public DateTime dob;
    public string gender;
    public city {get;set;}
}

I need to get all properties as string list as mentioned below:

"Id"
"name"
"dob"
"gender"
"city.Id"
"city.name"
"city.country.Id"
"city.country.name"
"city.country.code"

And my method to get property is

private List<string> GetProps(Type type)
{
    var result=new List<string>();
    var properties = type.GetProperties().ToDictionary(x => x, x => x.GetType().GetProperties());
    foreach (var item in properties)
    {
        result.Add(item.Key.ToString());
    }
    return result;
}

GetProps(typeof(Person)); // calling in main method;

The coming result is

"Id"
"name"
"dob"
"gender"
"city"

But my expected result is : "Id" "name" "dob" "gender" "city.Id" "city.name" "city.country.Id" "city.country.name" "city.country.code"

Please help :)





How to access in the code to meta tags from a struct field [duplicate]

I have:

type myStruct struct {
    myField string `json:"my-field" validate:"required"`
}

I have the struct as interface{}, I know how to use the reflect to get the value, and the type. But how can I retrieve the "meta" json and validate??????'





mardi 18 octobre 2022

Find object properties of a certain type

I am trying to recursively build a list of all the properties of an object that are of a certain type. Recursion is needed because the object can hold arrays of objects which, in turn, may contain fields of a certain type.

So, if an object has a member of type Wanted, I want that object in the list.

class a
{
    Wanted m_var;
};

If an object has an array that contains other objects and these objects contain a member of type Wanted, I'd also like those added to the list.

class b
{
    int m_whatever;
    a[] m_vararray;
};

I've been trying all sorts of approaches, including Reflection but I am not getting anywhere. All the attempts were some variation of this

private IList<object> ListOfTypeWanted(object fields)
{
    IList<object> result = new List<object>();

    System.Reflection.MemberInfo info = typeof(object);
    object[] properties = type.GetProperties();

    foreach (var p in propoerties)
    {
        if (true == p.GetType().IsArray)
        {
            result.Add(ListOfTypeWanted(p));
        }
        else
        {
            Type t = p.GetType();
            if (p is WantedType)
            {
                result.Add(this);
            }
        }
    }
    return result;
}

I've also tried Linq statements using Where() but they did not get me any useful results either.

Does anyone know what the best way is to achieve this?





lundi 17 octobre 2022

Immutables custom create and of methods

I am changing a library that uses Immutables. In the class that I change I just added a new variable and in the generated classes I see different signatures in the create and of methods.

ImmutableMyClass.of(previous variables ...,  int varNew)

ModifiableMyClass.create(previous variables ...,  int varNew)

Since there are users of this library that call the previous versions of these methods I need to keep previous versions while providing the new versions for a new feature; otherwise, apparently, I am breaking the backward compatibility.

How do I have Immutables create custom create and of methods?





How to convert LINQ Select-like statement to JSON / DQL query

I am trying to build a .NET extension method that will take a type parameter and a .Select() statement and convert it to JSON, but I am not sure how I can access subobjects and lists using reflection.

string str = Extensions.GetJson((DataItemList element) => new
{
    name = element.Name,
    subObject = element.Subobject,
    data = element.DataItems.Select(x => new
    {
        x.Id,
        x.Name
    })
});

I don't have an actual instance of the class at all, as I would want to use reflection to make that .GetJson() return something like this (I know it's not exactly JSON, but I want something like this. I am essentially trying to dynamically create a DQL query for Dgraph:

{
    name
    element {
        prop1
        prop2
    },
    data
    {
        id
        name
    }
}




dimanche 16 octobre 2022

given a DI Generic object of

yes, while there are other answers for Compile time, but not runtime; i.e. I can do this at compile time when I have the object name; However after searching SO I was unable find an answer on SO for RUNtime, when using a generic object at runtime.

Question:

Given an DI injected someObjectList at RUNtime, of a Generic POCO/ViewModel object of <T>; for e.g. myCustomerList or myZooAnimals whatever the service injects,

How can get back a List<AttributeName, List<DistinctValues>> of ALL the distinct values for EACH col/prop or attribute of that object??

For e.g. you have two different objects

// For e.g. this are the objects or data
Customer[Name, Address, Phone ...]

Zoo[Animals, Country, IsAmphibian ...]

Objective/ get back all the distinct values by property:

 //List<AttributeName, List<DistinctValues>>
  public List<string, List<string>> GetDistinctValuesByProperty<T>(List<T> injectedList) {
  ...
  return List<AttributeName, List<DistinctValues>>
  }

At runtime, how can I pass in an object<T>(CustomerList) and get distinct values for EACH attribute DistinctNames, DistinctAddress & DistinctPhone


What I tried:

// Option 1: 
this only works at ** compile time and requires that i know the properties of the instance ahead of time, 
// ** How do I make this this generic to work for any object and all properties at runtime

   var distinctAddress= myCustomerList.Select(x => x.Address).Distinct();


// Option 2:
// I tried reflection, to get the property names at ** runtime, 
// but I could not figure out ** how to get the distinct properties and values for each

    foreach (var objectPropertyName in typeof(myObject).GetPropertyNames())
        {
            distinctAttirbutesList.Add(myObject.Select(m => m.objectPropertyName).distinct;
          ... no clue stuck.. tried to add the property name from reflection

        }





samedi 15 octobre 2022

find all classes which which implemented another class in dart

I have a base generic class, and I want to find all classes which implements this class, do we have such thing in dart?

for clarifying this is my base class

abstract class IBaseClass<T>{
    void (T command);
}

and these are its implementation:

class CreateHandler implements IBaseClass<CreateCommand>{
    void (CreateCommand command)
    {
        //do something
    }
}

class DeleteHandler implements IBaseClass<DeleteCommand>{
    void (DeleteCommand command)
    {
        //do something
    }
}

Do we have something to pass base class to it and it returns these two classes? Maybe like this:

var implementations = GetImplementationsForClass(Typeof(IBaseClass<>));




vendredi 14 octobre 2022

why reflect.TypeOf(new(Encoder)).Elem() != reflect.TypeOf(interfaceVariable)?

Here's the short test:

type Encoder interface {
    Encode()
}
func main() {
    encoderInterface1 := reflect.TypeOf(new(Encoder)).Elem()
    var en Encoder
    encoderInterface2 := reflect.TypeOf(en)
    fmt.Println(encoderInterface1 == encoderInterface2)
}

Outputs false.

Why is it false? I was expecting it to be true.





Expression API - No increase in performance

I posted a question yesterday about this and the answer I received worked somewhat, however it is not enough. I'm using reflection to extract attribute data from my DTO classes, and these classes are quite heavy (most are 100+ properties with around 3 attributes each). I stumbled upon the Expression API and tried throwing something together, but it proved to be fruitless. The performance hit is still very noticeable. As I said, I just stumbled upon the Expression API so I'm sure I'm doing something wrong.

The heavy stuff:

public async Task<IEnumerable<DTOPropertyInfo>> GetPropertiesInfoAsync(BaseDTO dto)
{
    List<DTOPropertyInfo> info = new();
    List<DTOPropertyInfo> favorites = new();
    QueryType type = dto.ToQueryType();
    PropertyInfo[] properties = dto.GetType().GetProperties();

    for (int i = 0; i < properties.Length; i++)
    {
        PropertyInfo property = properties[i];
        DisplayDataAttribute display = 
            (DisplayDataAttribute)property.GetCustomAttribute(typeof(DisplayDataAttribute));
        if (display is null)
        {
            continue;
        }

        object value = property.GetValue(dto);

        if (value is BaseDTO[] dtos)
        {
            for (int j = 0; j < dtos.Length; j++)
            {
                IEnumerable<DTOPropertyInfo> nestedInfo =
                    await GetPropertiesInfoAsync(dtos[j]);
                info.Add(new()
                {
                    DisplayName = $"{display.DisplayName} {j + 1}",
                    Value = nestedInfo,
                    Section = Section.SubSection
                });
            }
            continue;
        }
        else if (value is string[] strings)
        {
            if (strings.Length == 0)
            {
                continue;
            }

            List<DTOPropertyInfo> dtoProperties = new();
            for (int j = 0; j < strings.Length; j++)
            {
                dtoProperties.Add(new()
                {
                    DisplayName = (j + 1).ToString(),
                    Value = strings[j]
                });
            }

            info.Add(new()
            {
                DisplayName = display.DisplayName,
                Value = dtoProperties,
                Section = Section.SubSection
            });
            continue;
        }
        else if (property.PropertyType.IsArray)
        {
            //Only support arrays of type string[] and BaseDTO[]
            //If more needed, add them to the if-chain
            continue;
        }

        value = (value as string).FormatDisplayValue();
        if (string.IsNullOrEmpty(value.ToString()))
        {
            continue;
        }


        SectionAttribute section =
            (SectionAttribute)property.GetCustomAttribute(typeof(SectionAttribute));
        if (section is null)
        {
            section = (SectionAttribute)dto.GetType().GetCustomAttribute(typeof(SectionAttribute));
            if (section is null)
            {
                continue;
            }
        }

        if (type is not QueryType.None)
        {
            string favorite = await storage.GetAsync($"{type}/{display.DisplayName}");
            if (!string.IsNullOrEmpty(favorite))
            {
                favorites.Add(new()
                {
                    DisplayName = favorite,
                    Value = value,
                    IsFavorite = true,
                    Section = section.Section,
                    Unit = display.Unit
                });
                continue;
            }
        }

        info.Add(new()
        {
            DisplayName = display.DisplayName,
            Value = value,
            Section = section.Section,
            Unit = display.Unit
        });
    }

    info.InsertRange(0, favorites);
    return info;
}

The Expression API:

MethodInfo method = typeof(SettingsService).GetMethod(
            nameof(GetPropertiesInfoAsync),
            BindingFlags.Instance | BindingFlags.NonPublic,
            null,
            new[] { typeof(BaseDTO) },
            null);
        ConstantExpression constant = Expression.Constant(this, typeof(SettingsService));
        ParameterExpression parameter = Expression.Parameter(typeof(BaseDTO), "dto");
        MethodCallExpression call = Expression.Call(constant, method, parameter);
        LambdaExpression lambda = Expression.Lambda<Func<BaseDTO, Task<IEnumerable<DTOPropertyInfo>>>>(call, parameter);
        func = (Func<BaseDTO, Task<IEnumerable<DTOPropertyInfo>>>)lambda.Compile();

Then I simply the func variable when needed but there was no performance increase. What am I doing wrong?





C# Reflecting into a subclass

I'm trying to reflect into a class instance within a class. I can reflect into the class (Jig) but when I get the config property and try to reflect into that it gives me system. properties and not the properties within that Config class. Is it possible to reflect into the config class in the current manner?

Class structure:

public class Jig : IJig
{
    public string ConfigQuery { get; }
    public string ResultsQuery { get; }

    public Config Config { get; set; } = new Config();

    public static class Results { }
}


public class Config
{
    public testClass testClassProp { get; set; } = new testClass();

    public string prop {get; set;}
}

public class testClass
{
    public string Testprop { get; set; }
    public int avs {get; set;}
}

Reflection:

    public async Task Initialise()
    {
            await SetConfigs(Jig.Config.GetType());
    }

    
    private async Task SetConfigs(Type configType)
    {
        List<PropertyInfo> propertyInfos = configType.GetProperties().ToList();

        bool IsUserDefinedClass(PropertyInfo x) { return x.PropertyType.Assembly.FullName == configType.Assembly.FullName && x.PropertyType.IsClass; }
        List<PropertyInfo> subClass = propertyInfos.FindAll(x => IsUserDefinedClass(x)).ToList();
        propertyInfos.RemoveAll(x => IsUserDefinedClass(x));

        foreach (PropertyInfo x in subClass)
        {
            await SetConfigs(x.GetType());
        }
    }




jeudi 13 octobre 2022

Store information about class properties

I apologize for my previous post, I'll try to be more detailed here.

I've got a few DTO classes, containing 100+ properties which in turn have several attributes on them containing even more data related to the properties. For example:

    [JsonPropertyName("saldo")]
    [DisplayData("Saldo", Unit.Currency)]
    [Section(Section.Taxes)]
    public string saldo { get; set; }

Other properties might have more attributes and others might have fewer. When I fetch the data from the API I deserialize the stream into the specified DTO class. Once that finishes I do the reflection part in order to extract all the data.

    public async Task<IEnumerable<DTOPropertyInfo>> GetPropertiesInfoAsync(BaseDTO dto)
    {
        List<DTOPropertyInfo> info = new();
        List<DTOPropertyInfo> favorites = new();
        QueryType type = dto.ToQueryType();
        PropertyInfo[] properties = dto.GetType().GetProperties();

        for (int i = 0; i < properties.Length; i++)
        {
            PropertyInfo property = properties[i];
            DisplayDataAttribute display = 
                (DisplayDataAttribute)property.GetCustomAttribute(typeof(DisplayDataAttribute));
            if (display is null)
            {
                continue;
            }

            object value = property.GetValue(dto);

            if (value is BaseDTO[] dtos)
            {
                for (int j = 0; j < dtos.Length; j++)
                {
                    IEnumerable<DTOPropertyInfo> nestedInfo =
                        await GetPropertiesInfoAsync(dtos[j]);
                    info.Add(new()
                    {
                        DisplayName = $"{display.DisplayName} {j + 1}",
                        Value = nestedInfo,
                        Section = Section.SubSection
                    });
                }
                continue;
            }
            else if (value is string[] strings)
            {
                if (strings.Length == 0)
                {
                    continue;
                }

                List<DTOPropertyInfo> dtoProperties = new();
                for (int j = 0; j < strings.Length; j++)
                {
                    dtoProperties.Add(new()
                    {
                        DisplayName = (j + 1).ToString(),
                        Value = strings[j]
                    });
                }

                info.Add(new()
                {
                    DisplayName = display.DisplayName,
                    Value = dtoProperties,
                    Section = Section.SubSection
                });
                continue;
            }
            else if (property.PropertyType.IsArray)
            {
                //Only support arrays of type string[] and BaseDTO[]
                //If more needed, add them to the if-chain
                continue;
            }

            value = (value as string).FormatDisplayValue();
            if (string.IsNullOrEmpty(value.ToString()))
            {
                continue;
            }


            SectionAttribute section =
                (SectionAttribute)property.GetCustomAttribute(typeof(SectionAttribute));
            if (section is null)
            {
                section = (SectionAttribute)dto.GetType().GetCustomAttribute(typeof(SectionAttribute));
                if (section is null)
                {
                    continue;
                }
            }

            if (type is not QueryType.None)
            {
                string favorite = await storage.GetAsync($"{type}/{display.DisplayName}");
                if (!string.IsNullOrEmpty(favorite))
                {
                    favorites.Add(new()
                    {
                        DisplayName = favorite,
                        Value = value,
                        IsFavorite = true,
                        Section = section.Section,
                        Unit = display.Unit
                    });
                    continue;
                }
            }

            info.Add(new()
            {
                DisplayName = display.DisplayName,
                Value = value,
                Section = section.Section,
                Unit = display.Unit
            });
        }

        info.InsertRange(0, favorites);
        return info;
    }

DTOPropertyInfo looks like the following:

public readonly struct DTOPropertyInfo
{
    public readonly string DisplayName { get; init; }
    public readonly Section Section { get; init; }
    public readonly object Value { get; init; }
    public readonly bool IsFavorite { get; init; }
    public readonly Unit Unit { get; init; }

    public DTOPropertyInfo(string name, Section section, string value, bool favorite, Unit unit)
    {
        DisplayName = name;
        Section = section;
        Value = value;
        IsFavorite = favorite;
        Unit = unit;
    }
}

The app is built with .NET MAUI and I haven't really made any 'proper' tests, I've installed the app on several iOS phones (both old & newer ones). Same with Android phone (both old & newer ones) and they all behave the same. iOS has no problem at all when it does the reflection, everything is just instant. However, Android phones are really slow when they do the reflection part. Although newer Android phones do perform a little better than the old ones but the performance hit is still quite noticeable.

I guess I could just write out each and every property by hand but that would be very, very tedious.





System.AggregateException: 'Some services are not able to be constructed only when running through visual studio

I'm registering some services for MediatR with reflection in my web api app with .NET6.

When I'm running the application from docker/command prompt the application running successfully. When I'm trying to run the application from visual studio with/without debugging I'm getting the next error:

InvalidOperationException: Unable to resolve service for type 'Verte.UnifiedCommerce.MessagingModel.WarehouseManagement.AsnCommands.AsnGenerationCommand' while attempting to activate 'Verte.UnifiedCommerce.DomainModel.Cqrs.Commands.Events.SagaInitiationCommand`1[Verte.UnifiedCommerce.MessagingModel.WarehouseManagement.AsnCommands.AsnGenerationCommand]'.

My code to register the services is:

var eventType = typeof(IApplicationEvent);

var assemblies = typeof(AsnGenerationSaga).Assembly.GetReferencedAssemblies()
    .Select(a => Assembly.Load(a))
    .ToArray();

var commands = assemblies.SelectMany(a => a.GetTypes())
    .Where(t => !t.Name.Contains("ClientNotificationCommand") && !t.IsInterface && !t.IsAbstract && t.GetInterfaces().Any(i => i.FullName == eventType.FullName) && (t.IsSubclassOf(typeof(Command)) || t.IsSubclassOf(typeof(ModificationCommand))))
    .ToArray();

var events = assemblies.SelectMany(a => a.GetTypes())
    .Where(t => !t.IsInterface && !t.IsAbstract && t.GetInterfaces().Any(i => i.FullName == eventType.FullName) && t.IsSubclassOf(typeof(SagaEvent)))
    .ToArray();

services.AddMediatR(typeof(ProductsReader).Assembly);

foreach (var type in commands)
{
    var sagaInitiationCommandType = typeof(SagaInitiationCommand<>).MakeGenericType(type);
    var irequestHandlerType = typeof(IRequestHandler<,>).MakeGenericType(sagaInitiationCommandType, typeof(Unit));
    var sagaEventInitiatorType = typeof(SagaEventInitiator<,>).MakeGenericType(sagaInitiationCommandType, type);

    if (sagaEventInitiatorType != null)
    {
        services.AddTransient(typeof(IRequest<Unit>), sagaInitiationCommandType);
        services.AddTransient(irequestHandlerType, sagaEventInitiatorType);
    }
}

foreach (var type in events)
{
    var sagaPublishCommandType = typeof(SagaPublishEvent<>).MakeGenericType(type);
    var irequestHandlerType = typeof(IRequestHandler<,>).MakeGenericType(sagaPublishCommandType, typeof(Unit));
    var sagaEventInitiatorType = typeof(SagaEventInitiator<,>).MakeGenericType(sagaPublishCommandType, type);

    if (sagaEventInitiatorType != null)
    {
        services.AddTransient(typeof(IRequest<Unit>), sagaPublishCommandType);
        services.AddTransient(irequestHandlerType, sagaEventInitiatorType);
    }
}




mercredi 12 octobre 2022

Is there a way to detect the notnull constraint via reflection on a generic method?

When trying to get constraints applied to a generic method with reflection, after calling GetGenericArguments on the MethodInfo, if I use GenericParameterAttributes I get None and GetGenericParameterConstraints returns an empty Type[] when there's only a notnull constraint.

I have tried finding differences in the generated IL and (from what I understand) there's only a NullableAttribute (from System.Runtime.ComplierServices) applied to either the generic method, its declaring type or the type parameter that has the notnull constraint depending on the definition of the class nor method.

Since the attribute's location is not always the same and I'm pretty sure there are others ways it can appear I don't think looking for this attribute is a reliable solution.

Is there something more that can tell me a type parameter has the notnull constraint using reflection?





mardi 11 octobre 2022

Generate proto files from unity game use il2cpp

Hello i would like to regenerate the proto files from a unity game that use the GoogleProtobuf lib.

I tried to use the generated reflection classes by GoogleProtobuf but the lib Cpp2Il from Samboy generate the class without body so i cannot invoke this.

Do you have any idea to realise this task ?

Thanks in advance





lundi 10 octobre 2022

Func

The problem

I have the following code:

Action function = async () => await Task.CompletedTask;

The problem with this code is that even though technically speaking it is an async delegate (one that can be awaited) I cannot await it. In other words, the above could be written equivalently as

Func<Task> function = async () => await Task.CompletedTask;

The latter can be awaited, while the former cannot, even though this is the same method internally. Obviously, this is a contrived example, in my use case more complex code resides in a more complex codebase and it is not easy to spot all misusages.

The question

Can I check the actual type of function at runtime and cast it to the correct one?

What I tried

Code below only throws if I declare function as Func<Task> (aka does not work as I expect it to)

Action function = async () => await Task.CompletedTask;
if (function.GetMethodInfo().ReturnType.IsEquivalentTo(typeof(Task)))
{
    throw new Exception();
}

Code below does not even compile

Action function = async () => await Task.CompletedTask;
if (function is Func<Task> func)
{
    
}




dimanche 9 octobre 2022

C# Reflection: how to get List

I am trying to use reflection to query the public interface of a class library, then produce classes and methods from info in the query.

The problem is that the generated source code won't compile:

  • The original class library has a function parameter being "List<Employee>", but the generated source code has "System.Collections.Generic.List`1[Employee]". It is generated by Type.ToString().

  • The original class library has "Dictionary<string, Employee>", but the generated code has "System.Collections.Generic.Dictionary`2[string, Employee]".

Here is the reflection code to generate source code:

            foreach (MethodInfo methodInfo in type.GetMethods())
            {
                if (!methodInfo.IsStatic)
                    continue;

                Console.Write($"    {(methodInfo.IsStatic ? "static" : "")} {methodInfo.ReturnType} {methodInfo.Name} (");
                ParameterInfo[] aParams = methodInfo.GetParameters();

                for (int i = 0; i < aParams.Length; i++)
                {
                    ParameterInfo param = aParams[i];

                    if (i > 0)
                        Console.Write(", ");

                    string strRefOrOut;

                    if (param.ParameterType.IsByRef)
                    {
                        if (param.IsOut)
                            strRefOrOut = "out ";
                        else
                            strRefOrOut = "ref ";
                    }
                    else
                        strRefOrOut = "";

                    Console.Write($"{ strRefOrOut }{ param.ParameterType.ToString() } {param.Name}");
                }

                Console.WriteLine(");");
            }

It produces the following source code that cannot be compiled:

static System.Void Test1 (System.Collections.Generic.List`1[Employee] employees);
static System.Void Test (System.Collections.Generic.Dictionary`2[System.String, Employee] dict);

I want it to be

static System.Void Test1 (List<Employee> employees);
static System.Void Test (Dictionary<System.String, Employee> dict);

How do I get the desired outcome from the Type?

I don't want to do ugly "if/else if/else if/else" string manipulations to convert them, because if I forget to include a type of collection then it will break.

Is there an elegant way of automatically get the former, such as Type.ProperName?





samedi 8 octobre 2022

Creating a mock library

I want to create a Mock Library class that implements InvocationHandler interface from Java Reflection.

This is the template I have created:

import java.lang.reflect.*;
import java.util.*;

class MyMock implements InvocationHandler {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            // todo
        }
        
        public MyMock when(String method, Object[] args) {
            // todo
        }
        
        public void thenReturn(Object val) {
            // todo
        }
}

The when and thenReturn methods are chained methods.

Then when method registers the given mock parameters.

thenReturn method registers the expected return values for the given mock parameters.

Also, I want to throw java.lang.IllegalArgumentException if the proxied interface calls methods or uses parameters that are not registered.

This is a sample interface:

interface CalcInterface {
    int add(int a, int b);
    String add(String a, String b);
    String getValue();
}

Here we have two overloaded add methods.

This is a program to test the mock class I wanted to implement.

class TestApplication {     
        public static void main(String[] args) {
            MyMock m = new MyMock();
            CalcInterface ref = (CalcInterface) Proxy.newProxyInstance(MyMock.class.getClassLoader(), new Class[]{CalcInterface.class}, m);
            
            m.when("add", new Object[]{1,2}).thenReturn(3);
            m.when("add", new Object[]{"x","y"}).thenReturn("xy");
            
            System.out.println(ref.add(1,2)); // prints 3
            System.out.println(ref.add("x","y")); // prints "xy"
        }
}

This is the code which I have implemented so far to check the methods in CalcInterface:

class MyMock implements InvocationHandler {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            int n = args.length;
            if(n == 2 && method.getName().equals("add")) {
                Object o1 = args[0], o2 = args[1];
                if((o1 instanceof String) && (o2 instanceof String)) {
                    String s1 = (String) o1, s2 = (String) o2;
                    return s1+ s2;
                } else if((o1 instanceof Integer) && (o2 instanceof Integer)) {
                    int s1 = (Integer) o1, s2 = (Integer) o2;
                    return s1+ s2;
                }
            }
            throw new IllegalArgumentException();
        }
        
        public MyMock when(String method, Object[] args) {
            return this;
        }
        
        public void thenReturn(Object val) {
        
        }
}

Here I am checking only for methods with the name add and having 2 arguments, with their type as String or Integer.

But I wanted to create this MyMock class in a general fashion, supporting different interfaces not just CalcInterface, and also supporting different methods not just the add method I implemented here.





vendredi 7 octobre 2022

Is there a mechanism to disable Reflection in .NET 6?

I am writing an extensible server application. I’d like to expose a library that can be consumed by a third party to write extensions to the server application. When I load the 3rd parties assembly I want to block loading it if the assembly uses Reflection.

The goal is to allow the 3rd party library developer to implement server interfaces and the server will execute those implementations, but will block loading the assembly if reflection is used.

The purpose behind this is to maintain a reasonable level of security when loading a 3rd party assembly into the server. I.E. the 3rd party assembly should be restricted and unable to use reflection to gain access to other parts of the application.

I read about assembly Evidence, but I don’t know if that will allow me to glean the information I need to know.





C# Getting methods with attribute in abstract class

I'm trying to get methods from which have a specific Callback attribute inside the constructor of an abstract class. The challenge here is that I also want the methods from the concrete class which have this attribute.

My abstract class:

public abstract class BaseScript
{
    protected readonly CallbacksDictionary Callbacks;

    protected BaseScript(CallbacksDictionary callbacks)
    {
        // Get all methods with the [Callback] attribute including the concrete instance
        var methodsWithCallbackAttr = // ?
    }
}
public class SomeScript : BaseScript {
    public SomeScript(CallbacksDictionary callbacks) : base(callbacks) { }

    [Callback("transaction")]
    internal Task<bool> Transaction(int amount) {
       // I need to get this method
    }

    internal Task<bool> GetBalance(int accountId) {
         // But not this method
    }
}

In the example above I want methodsWithCallbackAttr to be a list containing the Transaction method if the concrete instance is SomeScript i.e. I don't want all the methods from all the classes that inherit from BaseScript and have the Callback attribute.

I've tried the following. Which does not work. This only returns the methods from BaseScript which have the Callback attribute, but not the methods from SomeScript.

var callbackMethods = GetType().GetMethods()
    .Where(m => m.GetCustomAttributes(typeof(CallbackAttribute), true).Length > 0);




Getting null when trying to create instance of class at run time in .NET Core

I am trying to create an instance of a class at runtime and call the method but it's not working for me.

I have a class library where I have a class and method as below :

Class library MyApp.Service:

namespace MyApp.Service.SchedularOperations
{
    public class WeeklyTaskSchedular : ISchedular
    {
        private readonly IDbConnection _dbConnection;
        private readonly IProductService _productService;
        
        public WeeklyTaskSchedular(IDbConnection dbConnection,IProductService productService)
        {
            _dbConnection = dbConnection;
            _productService = productService;
             Frequency = Frequencies.Weekly
        }

        public Frequencies Frequency { get ; set ; }

        public int Process (ScheduleInfo info)
        {
            //process logic 
            return 0; indicate success
        }
    }
}

BackgroundService project:

namespace MyApp.BackgroundSchedularService
{
    public class RunSchedular : BackgroundService
    {
        private readonly ILogger<RunSchedular> _logger;
        private readonly IProductService _productService;

        public RunSchedular(ILogger<RunSchedular> logger, IProductService productService)
        {
            _logger = logger;
            _productService = productService;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                string connectionString = GetThirdPartyConnectionStringFromDatabase();
                string executionClassName = "MyApp.Service.SchedularOperations.WeeklyTaskSchedular"; //coming from database
                IDbConnection connection = new SqlConnection(connectionString);
                object[] constructorArgs = { connection, _productService};
                
                Type type = GetInstance(executionClassName); //getting null
                object instance = Activator.CreateInstance(type,constructorArgs);
                
                object[] methodArgs = { new ScheduleInfo() };
                
                type.GetMethod("Process").Invoke(instance,methodArgs);
                await Task.Delay(1000, stoppingToken);
            }
        }
        
        public Type GetInstance(string strFullyQualifiedName)
        {
            foreach(var asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                Type type = asm.GetType(strFullyQualifiedName);
                if(type !=null)
                    return type;
            }
            return null;
        }
    }
}

public class Program
{
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<RunSchedular>();
                    services.AddTransient<IProductService, ProductService>();
                });
}

Problem is this :

Type type = GetInstance(executionClassName); //getting null

Can someone please help me create an instance of a class at run time with constructor arguments and call the method?





How to call a private class's static function using Kotlin's reflection?

I know how to invoke it in Java's reflection and it works like a charm, but I can't seem to get it to work using Kotlin's reflection.

Sample code:

    fun main() {
        // using Java reflection
        val clazz = AccessAHiddenClass::class.java
        val method = clazz.getMethod("someStaticFunction", String::class.java, Int::class.java)
        val result = method.invoke(null, "Java", 27) as String
        println(result)

        // using Kotlin reflection
        val klass = AccessAHiddenClass::class
        klass.memberFunctions.find {
            it.name == "someStaticFunction"
        }?.let {
            val kotlinResult = it.call( null, "Kotlin", 6)
            println(kotlinResult)
        }
    }

    private class AccessAHiddenClass {
        companion object {
            @JvmStatic
            fun someStaticFunction(name: String, age: Int) = "my name is $name, I'm $age years old"
        }
    }

After messing around I managed to write the following Kotlin reflection code, but only after removing the private visibility modifier from AccessHiddenClass class.

val klass = AccessAHiddenClass::class.companionObject
val kompanionObject = AccessAHiddenClass::class.companionObjectInstance
klass?.functions?.find {
    it.name == "someStaticFunction"
}?.let {
    val kResult = it.call(kompanionObject, "Test", 10)
    println(kResult)
}

Is there a way to modify AccessAHiddenClass's class visibility reflectively?





java generics reflection: get Class

This is my code, shared here, so you can run it.

public interface GenericRepository<T> {
    default Class<T> getEntityClazz() {
        ParameterizedType pType = (ParameterizedType)this.getClass().getGenericInterfaces()[0];
        Type tT = pType.getActualTypeArguments()[0];
        Class<T> clazz = (Class<T>) tT.getClass();
        
        return clazz;
    }
}
public class GenericRepositoryImpl<T> implements GenericRepository<T> {
    
}

My main is:

public class Main
{
    public static void main(String[] args) {
        GenericRepository<Example> genericObject = new GenericRepositoryImpl();
        Class<Example> clazz = genericObject.getEntityClazz();
        System.out.println("Generic class: " + clazz.toString());
    }
}

And output is:

Generic class: class sun.reflect.generics.reflectiveObjects.TypeVariableImpl

I was expecting to get Generic class: class Example.

Any ideas?





jeudi 6 octobre 2022

A strange clause in the documentation of java.lang.Class::getDeclaredMethods

From the documentation of java.lang.Class::getDeclaredMethods:

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods. The declared methods may include methods not in the source of the class or interface, including bridge methods and other synthetic methods added by compilers. If this Class object represents a class or interface that has multiple declared methods with the same name and parameter types, but different return types, then the returned array has a Method object for each such method...

AFAIK java doesn't allow a class or an interface to have methods differing only by their return type(return type is not part of a function's signature), so how would this happen?





Is there a way to get the source columns from a column object in PySpark?

I'm writing a function that (hopefully) simplifies a complex operation for other users. As part of this, the user passes in some dataframes and an arbitrary boolean Column expression computing something from those dataframes, e.g. (F.col("first")*F.col("second").getItem(2) < F.col("third")) & (F.col("fourth").startswith("a")).

The dataframes may have dozens of columns each, but I only need the result of this expression, so it should be more efficient to select only the relevant columns before the tables are joined. Is there a way, given an arbitrary Column, to extract the names of the source columns that Column is being computed from, i.e. ["first", "second", "third", "fourth"]?

I'm using PySpark, so an ideal solution would be contained only in Python, but some sort of hack that requires Scala would also be interesting.

Alternatives I've considered would be to require the users to pass the names of the source columns separately, or to simply join the entire tables instead of selecting the relevant columns first. (I don't have a good understanding of Spark internals, so maybe the efficiency loss isn't as much I think.) I might also be able to do something by cross-referencing the string representation of the column with the list of column names in each dataframe, but I suspect that approach would be unreliable.





mardi 4 octobre 2022

Golang: Is there a way to iterate over a slice in a generic way using reflect?

Is there a way to iterate over a slice in a generic way using reflection?

type LotsOfSlices struct {
    As []A
    Bs []B
    Cs []C
    //.... and lots more of these
}

type A struct {
    F string
    //.... and lots of other stufff that's different from the other structs
}

type B struct {
    F string
    //.... and lots of other stufff that's different from the other structs
}

type C struct {
    F string
    //.... and lots of other stufff that's different from the other structs
}

I want to use reflection to reduce code complexity and duplicate code. Is this possible? Is this a bad idea?

For example, not this:

func processData(l LotsOfSlice){
    for _, a := range l.As{
        // use a.F
    }
    for _, b := range l.Bs{
        // use b.F
    }
    for _, c := range l.Cs{
        // use c.F
    }
    ...
}

But something like this instead:

func processData(l LotsOfSlices){
    t := reflect.TypeOf(l)
    for i := 0; i < t.NumField(); i++ {
        zs := reflect.ValueOf(l).Field(i).Interface()
        for _, z := range zs{
            // use z.F
        }
    }
}




samedi 1 octobre 2022

C# reflection: How to load multiple assemblies in different folders

My code uses Assembly.LoadFrom to load the main assembly, and uses reflection to inspect the types and functions in this assembly. This assembly references some other assemblies which are in different folders. When my code tries to inspect the types defined in those other assemblies, FileNotFoundException is thrown.

I can't use app.config setting to solve this problem. It all has to be done programmatically.

How do I solve this problem?





Get a pointer to a struct created using reflect in golang

I have the following code that mocks the structure of a code I'm working on. The main idea is that the ListOf function receives an array of some struct and populates it with elements created using reflection. The type of the structs is unknown so it must work with "any" type, this is why the list parameter is passed as interface{}. This part seems to be working: elements are created and appended to the array.

Before appending to the the array, the elements must be passed to the SetValue function which expects a pointer to a struct in order to modify the struct it receives.

In the code below I'm mocking this function, its internal logic is not relevant because I don't control this function. I cannot change it and, as far as I have tested, if this function receives a pointer to a struct it works as expected.

However, I have been unable to find a way to pass a pointer to the new created struct to the SetValue function. When I run the code below I get the following error:

panic: interface conversion: interface {} is main.MyStruct, not *main.MyStruct

The question I have is, how can I modify ListOf to be able to pass a *main.MyStruct to the SetValue function. Apparently I'm missing something simple here.

This is the code. You can try it at the Go Playground. Thanks in advance.

package main

import (
         "fmt"
         "reflect"
)

type MyStruct struct {
     Metadata struct {
        Name string
    }
}

// Expects a pointer to an struct and modifies it
func SetValue(obj interface{}) {
    // This code mocks the logic that modifies the generic objects
    // It only shows that I need a pointer in oder to modidy obj
    // I dont control this logic.
    s := obj.(*MyStruct)
    s.Metadata.Name = "name"
}

func ListOf(list interface{}) {
    // type of the elements of the list (main.MyStruct)
    e := reflect.TypeOf(list).Elem().Elem()
    // new value of type main.MyStruct
    v := reflect.New(e)
    // Call SetName, here is where I need *main.MyStruct
    SetValue(v.Elem().Interface())
    // value of list used below
    l := reflect.ValueOf(list).Elem()
    // append new value to list
    l.Set(reflect.Append(l, v.Elem()))
}

func main() {
    list := []MyStruct{}
    ListOf(&list)
    fmt.Printf("%v", list)
}