jeudi 30 septembre 2021

PowerShell iterate through json of key value pairs

I have a json file that maps alpha-2 codes to country names:

{
    "AF": "Afghanistan",
    "EG": "Ägypten",
    ...
}

I want to iterate over each key value pair to process the data. How would I be able to achieve that?

I tried the following but it always returns one big object that is not iterable in a key value manner:

$json = Get-Content -Path C:\countries.json | ConvertFrom-Json




Get ToString-expression from compiled class using reflection?

I have a class such as:

public class Person
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public override string ToString() => $"{LastName}, {FirstName}";
}

and I would like to be able to extract the ToString-expression in runtime using reflection like so:

var exp = typeof(Person).GetMethod("ToString").GetMethodBodyAsString();

where exp would be something like this: "${LastName}, {FirstName}" or at least enough to make it possible to reconstruct the expression with some more effort..

Is it possible to extract this from the IL-code returned by reflection on the method-body?





How I can put a string contain data from an api into a HashMap or Dictionary?

I'm new to c# and I have created a library that contain currency exchange rate from an API to a string

using System.Net;
namespace RateLib
{
    public class CurrencyRate
    {
        public void getRate()
        {
            string url = "apikey";

            WebClient myClient = new WebClient();
            string txt = myClient.DownloadString(url);

        }
    }
}

Now, how I can put this txt string into a hashmap (if it does exist in c#) or a Dictionary ?





mercredi 29 septembre 2021

Java Reflection Question about String... parameter for method

public static Client initClient(boolean paramBoolean, String... paramVarArgs) {

How would I reflect this method? I tried the follow -

final Method runClientMethod = clientClass.getMethod("initClient", Boolean.class, String.class);
final Method runClientMethod = clientClass.getMethod("initClient", Boolean.class, String[].class);

I am not sure how to properly declare String... paramVarArgs in reflection. If your getMethod isn't identical, the method cannot be found.. my above attempt throws a MethodNotFound exception





Macro for detecting non-static non-type members in classes

In C++ Templates - The complete guide, 2nd edition, at page 434, a macro is defined to generate predicates testing the existence of a nontype memeber in a class:

#include <type_traits>

#define DEFINE_HAS_MEMBER(Member)                    \
    template<typename T, typename = void>            \
    struct HasMemberT_##Member : std::false_type {}; \
    template<typename T>                             \
    struct HasMemberT_##Member<T, std::void_t<decltype(&T::Member)>> : std::true_type {};

The the text reads

It would not be difficult to modify the partial specialization to exclude cases wehre &T::Member is not a pointer-to-member type (which amounts to excluding static data members).

So I've played around with static_asserts and compiler errors and remember about types of static and non-static of members of classes:

struct A {
    int begin;
    static int end;
};
static_assert(std::is_same<decltype(&A::begin), decltype(A::begin) A::*>::value, ""); // passes
static_assert(std::is_same<decltype(&A::end), decltype(A::end)*>::value, "");         // passes

And thought that maybe a good modification of the lambda above aimed at detecting non-static members only is to change

: std::true_type

to

std::is_same<decltype(&T::Member), decltype(T::Member) T::*>

whereas if I wanted to check for static memebers only, I could change it to

std::is_same<decltype(&T::Member), decltype(T::Member)*>

Is it really this easy? Or am I overlooking something important?





Renamed WPF exe throws FileNotFoundException (not typical)

I have a WPF exe that after being built, if the exe is renamed, will not run because a FileNotFoundException is thrown. I have never seen this in ten years of working with .NET executables and this is not supposed to be a problem. Our exe name is built as "Installer.exe", but if we rename it to anything else and try to run it it fails with the following call stack:

Application: test.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
   at System.Reflection.RuntimeAssembly._nLoad(System.Reflection.AssemblyName, System.String, System.Security.Policy.Evidence, System.Reflection.RuntimeAssembly, System.Threading.StackCrawlMark ByRef, IntPtr, Boolean, Boolean, Boolean)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(System.Reflection.AssemblyName, System.Security.Policy.Evidence, System.Reflection.RuntimeAssembly, System.Threading.StackCrawlMark ByRef, IntPtr, Boolean, Boolean, Boolean)
   at System.Reflection.Assembly.Load(System.Reflection.AssemblyName)
   at System.Windows.Navigation.BaseUriHelper.GetLoadedAssembly(System.String, System.String, System.String)
   at MS.Internal.AppModel.ResourceContainer.GetResourceManagerWrapper(System.Uri, System.String ByRef, Boolean ByRef)
   at MS.Internal.AppModel.ResourceContainer.GetPartCore(System.Uri)
   at System.IO.Packaging.Package.GetPartHelper(System.Uri)
   at System.IO.Packaging.Package.GetPart(System.Uri)
   at System.Windows.Application.GetResourceOrContentPart(System.Uri)
   at System.Windows.Application.LoadComponent(System.Object, System.Uri)
   at Installer.App.InitializeComponent()
   at Installer.App.Main()

If I debug the executable I can further expand that to:

System.IO.FileNotFoundException: 'Could not load file or assembly 'Installer, Version=1.0.0.0,
Culture=neutral' or one of its dependencies. The system cannot find the file specified.'

I have also investigated the Fusion Log:

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
Running under executable  C:\Users\dande\Downloads\test.exe
--- A detailed error log follows. 

=== Pre-bind state information ===
LOG: DisplayName = Installer, Version=1.0.0.0, Culture=neutral
 (Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: Installer, Version=1.0.0.0, Culture=neutral | Domain ID: 1
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Users/dande/Downloads/
LOG: Initial PrivatePath = NULL
Calling assembly : PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35.
===
LOG: This bind starts in default load context.
LOG: No application configuration file found.
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/dande/Downloads/Installer.DLL.
LOG: Attempting download of new URL file:///C:/Users/dande/Downloads/Installer/Installer.DLL.
LOG: Attempting download of new URL file:///C:/Users/dande/Downloads/Installer.EXE.
LOG: Attempting download of new URL file:///C:/Users/dande/Downloads/Installer/Installer.EXE.

And I have investigated and ruled out the following:

  • We are not using Assembly.Load to load 'Installer' (which is the executing assembly)
  • We do not have any pack:// usages in XAML.
  • We have no code analysis warnings, errors, or XAML errors
  • It is not related to a application configuration file
  • It is not related to the application manifest
  • Application crashes even if I change the code to use a normal Window and not our MainWindow (eliminating a lot of XAML from the equation)
  • .NET version doesn't make a difference. It's targeting and built for .NET 4.6, but changing this doesn't change the outcome
  • Confirmed that all dependencies are referenced/present using DotPeek/JustDecompile
  • Confirmed that all namespaces internally are still 'Installer'
  • Investigated the partial binding via reading documentation, but this isn't a reference issue, the error indicates its the executing assembly itself that is the issue (it's looking for itself?)
  • Is not related to code signing as it occurs with or without it
  • It is not related to strong name signing as we are not using that

Things I have observed:

  • This happens prior to OnStartup. I cannot debug into the application.
  • It appears to be PresentationCore.dll (from Fusion Log) originating this issue
  • Confirmed with ProcMon.exe that it is in fact trying to access one of the four logged fusion log paths (Installer.DLL, Installer/Installer.DLL, Installer.EXE, Installer.Installer.EXE)
  • This occurs on any environment and I can reproduce locally by building the solution then renaming, the output file and then running it
  • If I copy the executable and rename that and run it it works fine because Installer.exe is present in the same directory

I have never seen this problem before and researching it I have not been successful because I'm just finding all the basic stuff new developers typically run into with reference problems and the like.

My only assumption is that possibly its XAML related but I haven't found anything in XAML out of the ordinary and we don't have any pack:// usages or anything.





GraphQL dotnet - Add fields at runtime using reflection

We have a decent sized dataset that we are using graphql dotnet to query. We have custom logic in place to parse the GQL query string and generate a function that will select the appropriate fields from the database and not the full object.

As such, the 'Query' object in our schema has a load of almost identical calls to Field in it which just look an object up by it's Id, issue the parsed select command, and return the resulting object.

For example:

// expression based department query
Field<DepartmentType>(
    "department",
    arguments: new QueryArguments(
        new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "organisationId" },
        new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "employerId" },
        new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "Id" }),
    resolve: context =>
    {
        var query = context.Document.OriginalQuery.Substring(context.Document.OriginalQuery.IndexOf("{"));

        var organisationId = new Guid(context.GetArgument<string>("organisationId"));
        var employerId = new Guid(context.GetArgument<string>("employerId"));
        var Id = new Guid(context.GetArgument<string>("Id"));

        appContext.OrganisationId = organisationId;
        appContext.EmployerId = employerId;

        var retVal = database.Departments()
            .Where(x => x.Id == Id && x.Deleted != true);

        var selectStatement = GraphDocumentParser.GenerateSelect(query, "department");
        var builder = new ExpressionBuilder();
        var statement = builder.BuildSelector<Department, Department>(selectStatement);
        var result = retVal.Select(statement);

        return result.FirstOrDefault();
    }).AuthorizeWith(Constants.GraphQL.Policies.API_ACCESS);

So I thought that I could just use reflection to loop our graphql types like this:

var queryableObjectTypes = Assembly.GetExecutingAssembly().GetTypes()
    .Where(x => x.IsClass && x.Namespace == "my.namespace.query.api" && !x.FullName.Contains("+<>c"))
    .ToList();

//Loop through our GQL types
foreach (var queryableObjectType in queryableObjectTypes)
{
    Console.WriteLine(queryableObjectType.FullName);

    //Grab the fields property from the type
    var fieldsProperty = queryableObjectType.GetProperties().FirstOrDefault(x => x.Name == "Fields");

    //If this has our 'fields' property which we require
    if (fieldsProperty != null)
    {
        //Get the instance of this
        var instanceOfType = database.GetServiceProvider().GetService(queryableObjectType);

        //If this fields is the type we definitely want - i.e.actually get the value from the
        // instance and check it
            if (fieldsProperty.GetValue(instanceOfType) is GraphQL.Types.TypeFields typeFields)
        {
            //If this type contains an employerid, then we need to generate a query for this
            if (typeFields.Any(x => x.Name.ToLower() == "employerid"))
            { ... } //These are the objects that I want to generate fields for

Which does give me the correct collection of GQL Type objects that I can loop over and use to add a field (any one of our objects with an employerId... which I will blacklist a few of later on, but that would be a simple list to skip over)

I can then parse various bits like the 'base' entity that this type points to, and get most of the required data for the Field to add to our GQL query.

I am able to get almost everything I need to create a field type to add to our query... as shown here:

var f = new FieldType();
f.Name = genericTypeNameFormatted;
f.Description = string.Empty;
f.Type = queryableObjectType;
f.Resolver = ????????
f.Arguments = new QueryArguments(
    new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "organisationId" },
    new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "employerId" },
    new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "Id" });
f.AuthorizeWith(Constants.GraphQL.Policies.API_ACCESS);

However, I am totally stuck with the mix of generics etc.. required to create the resolver. It's definition is as follows:

public class AsyncFieldResolver<TSourceType, TReturnType> : IFieldResolver<Task<TReturnType>>
{
    private readonly Func<IResolveFieldContext<TSourceType>, Task<TReturnType>> _resolver;

    /// <inheritdoc cref="AsyncFieldResolver{TReturnType}.AsyncFieldResolver(Func{IResolveFieldContext, Task{TReturnType}})"/>
    public AsyncFieldResolver(Func<IResolveFieldContext<TSourceType>, Task<TReturnType>> resolver)
    {
        _resolver = resolver ?? throw new ArgumentNullException(nameof(resolver), "A resolver function must be specified");
    }

    /// <inheritdoc cref="AsyncFieldResolver{TReturnType}.Resolve(IResolveFieldContext)"/>
    public Task<TReturnType> Resolve(IResolveFieldContext context) => _resolver(context.As<TSourceType>());

    object IFieldResolver.Resolve(IResolveFieldContext context) => Resolve(context);
}

Is it possible to create a Func<IResolveFieldContext<TSource>, Task<TReturn>> using data from reflection etc? or is it actually not possible?





mardi 28 septembre 2021

Loop through objects properties in an object

I have got an object like below

public class MainObj 
{
    public int BankDetailPercentage { get; set; }
    public int PersonalDetailPercentage { get; set; }
    public BankDetail BankDetail { get; set; }
    public PersonalDetail PersonalDetail { get; set; }
}
public class BankDetail
{
    public string Name { get; set; }
    public string Branch { get; set; }
    public string AccountNumber { get; set; }
}
public class PersonalDetail
{
    public string Name { get; set; }
    public string address { get; set; }
}

I need to loop through that MainObj Object and find how many properties of BankDetail and PersonalDetail objects are filled and on the basis of that I should set the percentage of filled properties in MainObj object's BankDetailPercentage and PersonalDetailPercentage fields and return it. How can I accomplish this, I have tried below but couldn't get how to do it

    public MainObject calculatePercentage(MainObject mainObject) 
    {
        int bdCount = 0, pdCount = 0, bdTotal = 3, pdTotal = 2;

        PropertyInfo[] properties = typeof(MainObject).GetProperties();
        foreach (var property in properties)
        {
            var value = property.GetValue(mainObject);
            if (property.Name == "BankDetail")
            {
              //
            }
        }
        return mainObject;
    }




How to create Reflections object?

I wanna find all classes which implement my interface. For this I use reflection provided by org.reflections:reflections:0.9.12 but the problem is I can't create an instance of the Reflections class.

My code:

Reflections reflections = new Reflections("com.example.projectName.Sortables");
Set<Class<? extends Sortable>> set = reflections.getSubTypesOf(Sortable.class);

Where "Sortable" is my interface.

The debager says

org.reflections.ReflectionsException: Scanner SubTypesScanner was not configured

I tried to put as the parameter Sortable.class, but this wasn't working. I'm confused because on this page and this page it works.





Using reflection to find all Classes of a Type(), ordering them, and invoking a named method

I have taken a leaf out of EFC and tried to develop something similar to modelBuilder.ApplyConfigurationsFromAssembly() for SQL commands that I need to run against my database in a specific order.

I would like to invoke all the methods of any class where that class inherits from my Interface. But I want to invoke them in groups or orders.

My interface is:

public interface IDatabaseSqlCommands
{
    public ExecutionGroups ExecutionGroup { get; }
    public Task Configure(DbContext context);
}

An example nested class is:

private sealed class SqlCommands : IDatabaseSqlCommands
{
    public ExecutionGroups ExecutionGroup { get; } = ExecutionGroups.G1;

    public async Task Configure(DbContext ctx)
    {
        await ctx.Database.ExecuteSqlRawAsync(
        @"
            CREATE TRIGGER Customers_Timestamp
            AFTER UPDATE ON Customers
            BEGIN
                UPDATE Customers
                SET Version = Version + 1
                WHERE rowid = NEW.rowid;
            END 
        ");
    }
}

So using System.Reflection I am able to find the interface and invoke the interface by using:

public async Task EnsureSqlCreatedAsync()
{
    // We are only interested in non-abstact private nested classes which are sealed
    var classCollection = Assembly.GetExecutingAssembly()
                            .DefinedTypes.Where(
                                t => !t.IsAbstract &&
                                t.IsClass &&
                                t.IsSealed &&
                                t.IsNestedPrivate);

    foreach (var type in classCollection)
    {
        // Class must have an empty constructor
        if (type.GetConstructor(Type.EmptyTypes) == null)
            continue; // Constructor is not empty

        foreach (var @interface in type.GetInterfaces())
        {
            if (@interface.GetTypeInfo() == typeof(IDatabaseSqlCommands))
            {
                var instance = Activator.CreateInstance(type);
                await ((IDatabaseSqlCommands)instance).Configure(this);
                return;
            }
        }
    }
}

So that all works fine, and all the instances get invoked, but what I now want to do is

  1. find all the classes that have that Interface; and
  2. invoke Configure() by the order of ExecutionGroup

The definition of ExecutionGroups is:

public enum ExecutionGroups
{
    G1=1, G2=2, G3=3, G4=4, G5=6
}

I can't work out the Linq to order my classes by the value of ExecutionGroup so that my Sql executes in order of dependency.





lundi 27 septembre 2021

ClassNotFoundException While running on Cloud Server but works from Local Eclipse

I have a Spring boot Project which Contains a DTO object. In one of our Jar we have a program to Read a file and create the DTO object. I am trying to load the DTO through Reflection. Its working perfectly from local eclipse workspace but when I deploy it in the cloud it fails, giving class not found exception. The below code is in the Jar which is added as maven dependendy.

    public class AbcFileReader<T extends ReaderInterface>{
        public List<T> readFile(File, String className){
           T newObj = (T)Class.forName(className).newInstance();        
    }

Here className = "com.abc.dto.AbcDTO";Its implements ReaderInterface.java and the class is present in the package. I have also tried the below line. But not working on cloud.

ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
T newObj = (T)Class.forName(className,true, contextCL).newInstance();




dimanche 26 septembre 2021

get reflect.struct from interface

hi a have this func for get type of value, but i try this and never can get reflect.struct:

type Test struct {
    Code int   
    Name string
}
func main(){
    test := getTest()
    data, err := getBytes(slice...)
    sanitizedFile := bytes.Split(data, []byte("\r\n"))
    err = Unmarshal(sanitizedFile[0], &test)
}
func getTest() interface{} {
    return Test{}
}

With this code i don't can get the reflecet.struct from v params in Unmarshall func

func Unmarshal(data []byte, v interface{}) error {
    rv := reflect.ValueOf(v)

    if rv.Kind() == reflect.Ptr {
        rvElem := rv.Elem()
        
        switch rvElem.Kind() {
        case reflect.Struct:
           // implement me
        }
    }
    return ErrInvalid
}

I would like to know if I can somehow find out if an interface is of type struct or access the values ​​of that struct.





samedi 25 septembre 2021

Gorm Find result to interface

I am trying to build a generic CrudRepository struct using Gorm for my api. I know generics are coming to GoLang in version 2 but I try to build this lib using reflection or any other lib.

In my CrudRepository:

func (repository *BaseRepository) find(result interface{}, pageSize int, page int) error {
  if page < 1 {
    return errors.ExceedsMinimumInt("page", "", 0, true, nil)
  }

  offset := (page - 1) * pageSize

  ent := reflect.Zero(reflect.TypeOf(result))

  repository.db = repository.db.Limit(pageSize).Offset(offset)
  err := repository.db.Find(&ent).Error

  result = ent

  if err != nil {
    return err
  }
  return nil
}

And calling this method sth like:

func List(){
  var entityList []MyEntity
  find(entityList, 1, 10)
}

I think, I cannot pass any interface reference into Gorm.db.Find() method Is there any other way to succeed?





Annotation not getting copied to getter and setter

So, I have this annotation class

@Target(AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class MyTestAnnotation(val text: String)

And I'm using this like this

interface MyTestInterface {

    @MyTestAnnotation("temp")
    var tempString: String
}

This is how I'm instantiating my interface using reflection.

fun <T> with(myInterface: Class<T>): T {
    return Proxy.newProxyInstance(
        myInterface.classLoader,
        arrayOf<Class<*>>(myInterface),
        invocationHandler
    ) as T
}

private val invocationHandler = InvocationHandler { _, method, args ->
    Log.e("Called method:", method.name) // setTempString
    Log.e("declaredAnnotations", method.declaredAnnotations.size.toString()) // 0
    Log.e("annotations", method.annotations.size.toString()) // 0
    Log.e("args", args.size.toString()) // 1
}

I'm calling it like this

val myInterface = with(MyTestInterface::class.java)
myInterface.tempString = "123"

I'm not able to access the member text of the annotation class because in my invocationHandler I'm not getting the annotation(as you can see both the arrays are of length zero).

My question: Is there any way I can copy the annotation to the getter and setter so I can get access to the data which I put in the annotation?





vendredi 24 septembre 2021

Is there a better way to test the generic type (without type arguments) in Scala?

Given I'm using reflection to go through a list of members (giving me runtime.universe.Symbol), how can I check the generic type without the type arguments? In other words, how do I find the members which are List[] generic type, regardless of what the type argument is?

Currently I'm using this approach which does work, but I'm wondering if there's a better way to do it:

import scala.reflect.runtime.currentMirror

// ...

val listTypeConstructor = typeOf[List[_]].typeConstructor
val myListMembers = currentMirror.reflect(MyObject)
  .symbol
  .asClass
  .typeSignature
  .members
  .filter(member => member.typeSignature.resultType.typeConstructor == listTypeConstructor)

This results in a list of runtime.universe.Symbol of all the List[] members, including any List[String], List[Int], etc. as expected.

The usage of typeOf[List[_]].typeConstructor seems a bit messy to me though. Is this the best way to do this kind of filtering?





Extract the default argument value in method

I am trying to create a UI to test a scala interface. To do so, I am extracting all the declared methods from the interface using java reflection. I am able to get the method names via

Class[MyClass].getDeclaredMethods.map(_.getName)

I am also able to extract all the parameter names and types via:

val paramNames = method.getParameters.map(_.getName)
val paramType = param.getParameterizedType.getTypeName

Now I am also trying to extract any default value of a parameter if there are any. However, I couldn't find a way to do so yet.





How to invoke method on a specific definition of a class using reflection?

I am trying to pull a field via reflection that is an array of the below class.

package com.api.Person
public class Person {

    private String name;
    private int age;

    public Person() {

    }

    public void setName(String name) {
    this.name = name;
    }

    public String getName() {
    return name;
    }
    
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
}
package com.client.Client
public class Client{
    ...
    People[] peoples;
    ...
}

I know how to get the field I am looking for and declare my methods. So below, obj would be my People[] and methodgetAge and methodsetAge are two methods I have defined that act on a Person class. How do I take my obj and loop through it to get individual People and call methodgetAge on each person?

Class<?> mainClass = cl.loadClass("com.client.Client");
Class<?> peopleClass = cl.loadClass("com.api.Person");
Field allPersons = mainClass.getDeclaredField("peoples");
allPersons.setAccessible(true);
Object obj = allPersons.get(mainClass);

Method methodgetAge = peopleClass .getDeclaredMethod("getAge");
Method methodsetAge = peopleClass .getDeclaredMethod("setAge", int.class);




Updating field using reflection from parent class

I have a Parent class that has a method that uses reflection to retrieve and update fields. This method will be called by the child class

package com.torchai.service.common.response;

import java.lang.reflect.Field;

public class TestReflection {
    private String foo;

    public void update() throws IllegalAccessException {
        final Field[] fields = getClass().getDeclaredFields();
        for (final Field f : fields) {
            //   f.setAccessible(true);
            //   final Object value = response.get(f.getName());
            Object value = "new value";
            f.set(this, value);

        }
    }

    public static void main(final String[] args) throws IllegalAccessException {
        final TestReflection t = new TestReflection() {
            private String abc;
        };

        t.update();
    }
}

When the child class (in this case, an anonymous class) calls the method, which is inherited form the parent, the value of this is the child class. Because of that, I thought there would be no problem in retrieving and setting private fields. It turns out that getDeclaredFields() can retrieve private fields, but Field.set() cannot update them, unless I setAccessible to true. Is this correct behavior? Why can't the child class set its own fields? If I can see the field (i.e., I can retrieve the private field) shouldn't I be able to update it?

The exception I get is

java.lang.IllegalAccessException: Class com.torchai.service.common.response.TestReflection can not access a member of class com.torchai.service.common.response.TestReflection$1 with modifiers "private"

Note that it implies that it is the parent class that it trying to access the child class. Why is the parent class being considered the caller?

If I change the main method to eliminate the use of the child class

TestReflection t = new TestReflection();
t.update()

then it works as expected. The class is updating its own fields, so setAccessbile is not necessary





Swift: obtain all active compilation conditions at runtime?

In Swift, at runtime, is it possible to obtain all active compilation conditions?

I know I can check known ones, like ye olde

#if DEBUG

I want all of them at once, like (and this is totally imaginary code)

let acc: [String] = CompileTimeInfo.activeCompilationConditions

Related.





Swift: obtain module at runtime?

In Swift, at runtime, is it possible to know the name of the module code is running in?

I'd want something like (and this is totally imaginary code)

let moduleName: String = CompileTimeInfo.moduleName

Related.





3js cubemap reflections artifacts

I'm getting those weird artifacts in the mesh when cubemap is enables. I think its the reflection but I'm not sure. Hope for some ideas on how to solve this.

The mesh is a .glb file. Tried with and without vertex normals calculation.

enter image description hereenter image description here





Get all foreign keys used by a primary key

I'm trying to get all foreign keys used by a specific primary key ,is there any way to print all foreign keys related to an id (primary key) using java code or pl/sql procedure ?

Thanks,





Extracting list of types using reflection

I am trying to write an application which loads an assembly and list outs which assemblies this again depends on. This part is working fine using Assembly.LoadFrom(asmPath) and GetReferencedAssemblies().

I would also like to extract some public information from the dll. Mainly I want to find classes which implements certain tags (typically Microsoft.AspNetCore.Mvc.ApiControllerAttribute) and the arguments that these functions have. When I try to call asm.GetTypes(), I get an ReflectionTypeLoadException because Microsoft.AspNetCore.Mvc.Core is not loaded.

Is there a way to load Microsoft.AspNetCore.Mvc.Core using the referenced assembly? I am trying to do this for a lot of dlls, so adding a nuget reference in my "assembly examination program" for all the references is not possible. Or is there a better way to get the information I am looking for?





jeudi 23 septembre 2021

C# HashSet Overlap Reflection

I have two HashSets that I'm trying to use the Overlap method with via reflection. Here's what I've got so far in LinqPad. You'll see that invocation works and returns true. I'm expecting the same to happen with comp.

var bigSet = Enumerable.Range(1, 10).ToList().ToHashSet();
var smallSet = Enumerable.Range(3, 1).ToList().ToHashSet();
var p1 = Expression.Parameter(typeof(HashSet<int>));
var p2 = Expression.Parameter(typeof(HashSet<int>));

MethodInfo overlap = typeof(HashSet<int>).GetMethod("Overlaps");
var body = Expression.Call(overlap, p1, p2);
var lam = Expression.Lambda<Func<HashSet<int>, HashSet<int>>>(body, p1, p2);


var invocationTest = overlap.Invoke(bigSet, new object[] { smallSet });
Console.WriteLine(invocationTest);


var comp = lam.Compile()
var x = comp(bigSet, smallSet);

My problem is that comp has an off by one error in the arguments. I think I've got lam written incorrectly or possibly body as well and thats actually causing it. Thank you





How do I make a type of a System.Func with dynamic type arguments

I have

    Type tsomething = /* ... */ ;
    Type comparer = typeof(Func).MakeGenericType(new Type[]{tsomething, tsomething, int});

but the compiler doesn't like the unspecialized Func. Is there a way to spell this out so I can get the generalized type to specialized dynamically.

I can't replace with a directly specialized Func because I don't know my own types at compile time. Reflection.Emit is involved; trying to write typeof(Func<something, something>, int) is impossible.

The exact same construct appears a few lines down with

    il.DeclareLocal(typeof(IEnumerator).MakeGenericType(new Type[]{tsomething}));




How to make a macro that generates a method with a target class's members?

Can a macro be made to generate a method for a target class with its variables? specifically a class method that just gets the target class's member offsets. like in below code, a method named GetOffsets(){} for my usage scenario, either a generated method that returns a list or a void return method that sets to a static list variable called offsets would be fine.

MetaClass(Actor,{
public:
    float integer = 70.0f;
    float floater = 2;
    vec3 vector = vec3(5,3,3);
    std::vector<float> lister({56,3,4,5});
    std::vector<size_t> GetOffset(){
        std::vector<size_t> offsets;
        offsets.Add(offsetof(Actor,integer));
        offsets.Add(offsetof(Actor,floater));
        offsets.Add(offsetof(Actor,vector));
        offsets.Add(offsetof(Actor,lister));
        return offsets;
    }
});

Here above, MetaClass is the macro and Actor is the target class for the macro. as an example. some code or alternate suggestions for would be helpful. this meta/offset information will be used for reflection purposes.





How to call a function from a string [duplicate]

I'm trying to get a result from a simple function with reflection but I can't seem to get it working.

I have tried the following options:

          var classType = Type.GetType("ConfigHelper");

                //1.
                Type thisType = classType.GetType();
                MethodInfo theMethod = thisType.GetMethod("GetBool");
                var aa = theMethod.Invoke(classType, null);

                //2.
                MethodInfo method = classType.GetMethod("GetBool");
                ParameterInfo[] parameters = method?.GetParameters();
                object instance = Activator.CreateInstance(classType, null);
                var result = method.Invoke(instance, parameters);

                //3.
                var aaa = classType.GetMember("GetBool") != null;

Option 3 recognizes the function exists, but I cant seem to call the function. At option 1 theMethod will be null and with option 2 var method is null.

Function I'm trying to call

    public static bool GetBool
    {
        get
        {
            // More logic comes here later
            return true;
        }
    }

Could anyone point me in the right direction?





Map array of values to generic type in Typescript

I am trying to create a function to map array of string values to a generic type in Typescript. The index of the value in the array has the same index as the key in the object. For instance:

I have a Person interface

interface Person {
    lastName: string;
    firstName: string;
}

An array of values

const values = ['foo', 'bar']

And the desired result is an instance of Person

{
    lastName: 'foo',
    firstName: 'bar'
}

The desired function type should look like something like this

const parse = <T extends Record<string, string>>(values: string[])<T> => {
  ...
}

const result: Person = parse(['foo', 'bar']);

Mapping 2 arrays to one object is no problem but i want the typing of the returned generic to make things easier. Things like Object.keys(T) or for key in T does not work so it's hard to get an index of a key.





Java reflection java.lang.ClassNotFoundException. Related to finding the full class name

I am currently trying to develop a method for invoking a specific class. The problem I am having is that I need to get the fully-qualified name or full class name when I invoke the class.

public static void testAlgorithm(String className, String methodName, long n) throws Exception 
{
    Class<?> myClass = null;
    Object myObject = null;
    try {
        
        myClass = Class.forName(className);
        myObject = myClass.newInstance();
        
        Class<?>[] params = new Class[1];
        params[0]=Long.TYPE;
        
        Method m = myClass.getMethod(methodName, params);
        
        m.invoke(myObject, n);
    }catch(Throwable e) {
        System.err.println(e);
    }
}

I call it from main

try {
    testAlgorithm("Algorithms", "linear", 50);      
    } catch (Exception e) {
        e.printStackTrace();
    }

I tried passing different arguments for className and I also directly modified the method inside to try to get the full class name but I didn't get anything to work. I have the class in the same project file Session01 and in the same package as well lab01.

I also checked out a similar question here.

And it leed me to also trying out:

Class currentClass = new Object() {}.getClass().getEnclosingClass();

inside the Algorithms class but I don't get the java.lang.String that I need to use for the method I am working on.





Get types of all instance variables in Java

I have a class named Attributes, which has some instance variables as listed below:

public class Attributes {
   protected A variable1;
   protected B variable2;
   protected C variables3;
   
   /*
     Getters and Setters of each method.
  */
   
}

I want the list of all instance variables' types present in the class.

The output: [A,B,C]

This contains all possible dataTypes present in this class.

Can someone please suggest a way?

NOTE: I've seen reflection, but I think it is useful only if we have filled the values for these variables and we want to fetch the values and names of those variables, not the types.





mercredi 22 septembre 2021

¿How to get a list of the properties set in C#? [duplicate]

I have a class Project like this

class Project
{
   public int IdProyecto { get; set; }
   public string Nombre { get; set; }
   public string Descripcion { get; set; }
   public string Distrito { get; set; }
   public string Provincia { get; set; }
   public string Departamento { get; set; }
   
   public List<string> GetSetProperties ()
   {
          ///
   }
}

Project project = new Project();
project.Nombre = "Project name";
project.Distrito = "District";

Console.Write(project.GetSetProperties()); // this should print: [Nombre, Distrito];

I would like to get only the properties that were set.

can you help me?





How efficiently create Java proxy object using CGLib (or any other reflection library)

Objective: (as the question title says): to efficiently create proxy (domain) objects using CGLib or any other reflection library (e.g. ByetBuddy?)

Having our domain class (please note Lombok annotations):

@Getter
@Setter
@RequiredArgsConstructor
public class DomainFoo {

    @NonNull
    private final Integer id;

    // some other fields, final or otherwise!

    public void doSomething() {
        // do something here!
    }
}

I'm trying to create a proxy object of type DomainFoo which responds only to getId method with the given ID (see below), otherwise (calling any other method) it throws an UnsupportedOperationException.

I managed to do this using GCLib (Spring version if it matters):

public static final ObjenesisStd OBJENESIS = new ObjenesisStd();

public static Factory newFoo(Integer id) {
    val enhancer = new Enhancer();
    enhancer.setSuperclass(domainClass);
    enhancer.setCallbackType(MethodInterceptor.class);
    val proxyClass = enhancer.createClass();

    // Since there's no default constructor in domains:
    val instantiator = OBJENESIS.getInstantiatorOf(proxyClass);
    val proxyInstance = instantiator.newInstance();

    val factory = (Factory) proxyInstance;
    factory.setCallbacks(new Callback[]{new DomainProxyInterceptor(id)});
    return factory; // see below for why it's called factory!
}

where DomainProxyInterceptor is:

@RequiredArgsConstructor
private class DomainProxyInterceptor implements MethodInterceptor {
    @NonNull
    private final Integer id;
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        if (method.getDeclaringClass() != Object.class && method.getName().equals("getId")) {
            return id;
        } else {
            throw new NotSupportedException(method.getName());
        }
    }
}

Everything works just fine. Now to make it efficient, I'm trying to cache factory and actually use it a factory:

// newFooFactory is the above method rename!
private static final Factor FOO_FACTORY = newFooFactory(0);

public static DomainFoo newFoo(Integer id) {
    val callbacks = new Callback[]{new DomainProxyInterceptor(id)};
    return (DomainFoo) FOO_FACTORY.newInstance(callbacks);
}

But calling the above method throws a NoSuchMethodError:

Exception in thread "main" java.lang.NoSuchMethodError: com/example/demo/DomainFoo$$EnhancerByCGLIB$$8423c3c4.<init>()V (loaded from file:/Users/rad/works/demo/target/classes/ by jdk.internal.loader.ClassLoaders$AppClassLoader@85a856f6) called from class com.example.demo.DomainFoo$$EnhancerByCGLIB$$8423c3c4 (loaded from file:/Users/rad/works/demo/target/classes/ by jdk.internal.loader.ClassLoaders$AppClassLoader@85a856f6).
    at com.example.demo.DomainFoo$$EnhancerByCGLIB$$8423c3c4.newInstance(<generated>)
    at com.example.demo.DomainFactory.proxyFoo(DomainFactory.java:28)
    at com.example.demo.DemoApplication.main(DemoApplication.java:6)

Which presumably is because Factory.newInstance tries to use the normal constructor but it's not there (because we created the object using Objenesis?). I also tried ReflectionFactory to create the factory instance, but it has the same issue.

Questions (they're kinda related):

  1. Do I need to worry about efficiency at all? (Those objects are normal domains, so there's usually too many of them.)
  2. Is there a better way to do the above? In terms of efficiency or otherwise? Specifically what's the right way to instantiate using GCLib when there's no default constructor?
  3. Is there a way to fix the above issue? Resolving NoSuchMethodError failure?
  4. Any other library or solution I could try?

Thanks.





How to query(Where) on generic type with just a string name

I want to create a generic methods to handle the unique fields in table.
for example I have 2 unique field, and I want to when I call _entities.Add() automatically checks the 2 unique fields that there is no records in the database with that record. I have this entity

[Index(nameof(Product.ProductNumber), IsUnique = true)]
[Index(nameof(Product.Url), IsUnique = true)]
public class Product
{
    public int Id { get; set; }

    [Required]
    [MaxLength(50)]
    public string Title { get; set; }

    public int ProductNumber { get; set; }

    [Required]
    [MaxLength(50)]
    public string Url { get; set; }
}

Now this is my generic service

public class GenericService<TEntity> : IGenericService<TEntity> where TEntity : class
{
    private readonly DbSet<TEntity> _entities;

    public GenericService(ApplicationDbContext dbContext)
    {
        _entities = dbContext.Set<TEntity>();
    }

    public bool Add(TEntity entity)
    {
        List<string> uniqueFieldsOfEntity = entity.GetType()
            .GetCustomAttributes<IndexAttribute>()
            .Where(x => x.IsUnique)
            .Select(x => x.PropertyNames.FirstOrDefault())
            .Where(x => x != null)
            .ToList();
        foreach (string uniqueField in uniqueFieldsOfEntity)
        {
            // HERE how can I work with Any with just a string
            //var hasAlready = _entities.Any(x => x.uniqueFiled == entity.uniqueFiled);
            if (hasAlready)
                return false;
        }
        _entities.Add(entity);
    }
}




Can't get razor views work with custom assembly loading context

I'm using assembly loading context to load plugin web apps in my host app (previously I used AppDomains)


public class PluginAssemblyLoadContext : AssemblyLoadContext
    {
        private AssemblyDependencyResolver _resolver;
        private IDictionary<string, Assembly> _loadedAssemblies;
        private IDictionary<string, Assembly> _sharedAssemblies;

        private string _path;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path">assembly file path</param>
        /// <param name="sharedTypes"></param>
        public PluginAssemblyLoadContext(string path, params Type[] sharedTypes)
             : base(isCollectible: false) // TODO: make collectible
        {

            _path = path;

            var fileInfo = new FileInfo(_path);
            if (fileInfo.Exists)
            {
                _resolver = new AssemblyDependencyResolver(_path);

                _sharedAssemblies = new Dictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase);
                foreach (var t in sharedTypes)
                {
                    LoadReferencedAssemblies(t.Assembly);
                }

                _loadedAssemblies = new Dictionary<string, Assembly>();

                var assembly = LoadFromAssemblyPath(fileInfo.FullName);

                _loadedAssemblies.Add(fileInfo.FullName, assembly);
            }
            else
            {
                throw new FileNotFoundException($"File does not exist: {_path}");
            }
        }

        public bool LoadReferencedAssemblies(Assembly assembly)
        {
            if (!_sharedAssemblies.ContainsKey(assembly.Location))
            {
                _sharedAssemblies.Add(assembly.Location, assembly);
                foreach (var an in assembly.GetReferencedAssemblies())
                {
                    var ra = Assembly.Load(an);
                    LoadReferencedAssemblies(ra);
                }
                return true;
            }
            else
            {
                return false;
            }


        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IEnumerable<Type> GetCommandTypes<T>()
        {
            var cmdType = typeof(T);
            return _loadedAssemblies.Values.SelectMany(a => a.GetTypes()).Where(t => cmdType.IsAssignableFrom(t));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="assembly"></param>
        /// <returns></returns>
        public IEnumerable<T> CreateCommands<T>(Assembly assembly)
        {
            foreach (var cmdType in GetCommandTypes<T>())
            {
                yield return (T)Activator.CreateInstance(cmdType);
            }
        }

        protected override Assembly Load(AssemblyName assemblyName)
        {
            var path = _resolver.ResolveAssemblyToPath(assemblyName);
            if (path != null)
            {
                if (_sharedAssemblies.ContainsKey(path))
                {
                    return _sharedAssemblies[path];
                    // return null; // should be the same (using default ALC)
                }
                if (_loadedAssemblies.ContainsKey(path))
                {
                    return _loadedAssemblies[path];
                }
                return LoadFromAssemblyPath(path);
            }
            return null; // using default ALC
        }
    }

The problem is that razor cant load load views normally.

I'm getting:



System.ArgumentNullException: Value cannot be null. (Parameter 'item')
   at Microsoft.AspNetCore.Mvc.Razor.Compilation.CompiledViewDescriptor..ctor(RazorCompiledItem item)
   at Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.RuntimeViewCompiler.CompileAndEmit(String relativePath)
   at Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation.RuntimeViewCompiler.OnCacheMiss(String normalizedPath)

I've used dnSpy and detected that view assembly generation works ok, but RazorCompiledItemLoader.LoadItems(assembly) gives 0 items because assembly.GetCustomAttributes() gives 0 attributes.

But RazorCompiledItemAttribute is actually there! I've saved view assembly via dnSpy and dumped to disk. When I'am trying to GetCustomAttributes inside plugin during ConfigureServices(IServiceCollection services)... (for example) I'm getting 0 matching attributes. But outside plugin call I.m getting 1 matching attribute! How can I make razor load this RazorCompiledItemAttribute?





mardi 21 septembre 2021

Reflection in .NET

class Program
{
    static void Main(string[] args)
    {
        Type doub = typeof(Doub);
        object result = doub.InvokeMember("Call", BindingFlags.InvokeMethod, null, null, new object[] { });
    }
}

public class Doub
{
    public Collection<string> Call()
    {
        Collection<string> collection = new Collection<string>();
        return collection;
    }

    public Collection<T> Call<T>()
    {
        Collection<T> collection = new Collection<T>();
        return collection;
    }
}

I tried to call the Call method, but the program cannot figure out which method to call. Error: (System.Reflection.AmbiguousMatchException: "Ambiguous match found). How can you call exactly the Call() method of the class?





How to programmatically get the name of a static method in Java?

I am developing a Java program that persists a Java class and static method name to JSON. I want to write this code to be as safe as possible, so that if the class/method changes (e.g., is moved or renamed), then the code will fail to compile. Likewise, if I use refactoring tools to change the class or method name, I would like these tools to be able to automatically update the name of the referenced class/method in the serializer. In order to achieve this, I have been using reflection to get the fully-qualified class name, as follows:

MyClass.class.getName()

But I have not been able to find a similar approach to get the referenced static method. The following code seems to almost work, in that my IDE suggested it, but then throws a syntax error:

MyClass::myStaticMethod.getStaticMethodName()

Is there a way to programmatically get the name of a referenced static method as a string in Java?

Thank you.





How to Stringify a class declaration and define it?

I need to convert my class declaration into a string and I also need the class defined. in the code below i have given an example which results in Identifier Person is undefined or Incomplete type not allowed. but is if this is possible with custom macros, some code would be much apricated.

struct Person;
std::string Person::meta = STRINGIFY(
    struct Person{
        static std::string meta;
        std::string name = "Test";
        int age = 5;
        std::string address = "No:35179 Address";
    };
);
Person person;




dimanche 19 septembre 2021

Disposing Of An Instance from Activator.CreateInstance()

I have software with a plugin system that loads DLL's using Assembly.Load() + Activator.CreateInstance(). The issue that I am having is the fact that the plugin keeps the process open, for example if I close the main window the process still remains open in the background and does not close properly.

My question is, is it possible to remove/unload an instance created by Activator.CreateInstance()? I tried setting the object to null and calling GC.Collect() as suggested in another question, but this was to no avail...

 async public void AddServerModule(Assembly module)
 {
    Type type = module.GetType("ModularModule.ModularModule");
    object instance = Activator.CreateInstance(type, new object[] { this });
    ...
 }




Detect if current method is a Task or not

In my application I use this tecnique to check how many milliseconds a specific task requires:

Private sub Test()
Dim watch as StopWatch
dim Method as System.Reflection.MethodBase = System.Reflection.MethodBase.GetCurrentMethod
watch.Start
' perform the heavy task I need to measure
watch.stop
SaveResult(watch.ElapsedMilliseconds, Method.IsSTA ??? )
End sub

My question: is there a way to detect if that method is running on UI thread or it has been called with Task.Run?

In the pseudo-code above, Method.IsSTA would be the option to get that information

"SaveResult" method has to receive info about if the method ran on main thread or not.

Thank you for your help.





How do I use reflection to call a generic method that accepts lambda input

What I'm trying to do is similar to the question bellow:

How do I use reflection to call a generic method?

but the function I'm trying to call needs a lambda input

(I'm adding masstransit consumers from domain assemblies by selecting assemblies where they are inheriting different interfaces)

The code:

        private static void AddLimitedConcurrencyMessageRecievers(IServiceCollectionBusConfigurator x, Assembly[] assemblies)
        {
            IEnumerable<Type> types = assemblies.SelectMany(s => s.GetExportedTypes())
                .Where(w => w.IsClass && !w.IsAbstract && w.IsPublic && typeof(IMessageReciever).IsAssignableFrom(w)).ToList();
            
            foreach (var item in types)
            {
                //x.AddConsumer<item>(y => y.UseConcurrentMessageLimit(1)); this is how I wished it would be like
                MethodInfo method = typeof(IRegistrationConfigurator).GetMethod(nameof(IRegistrationConfigurator.AddConsumer));
                MethodInfo generic = method.MakeGenericMethod(item);
                generic.Invoke(null, y => y.UseConcurrentMessageLimit(1)); //this still does not work
            }
                
        }




samedi 18 septembre 2021

Is it possible to create generic overrides using Reflections?

We're currently trying to figure out how to create really extended logging. so including the method call stack, method parameters, values, everything.

to do that we're basically using reflections. we have a factory method creating an instance and then comes the dirty point. we're creating this instance using string concatenated c# code.

the target is to append the logging code before and after the executed function in the context while having access to the type signature

i personally would rather like something like this:

public class LoggingWrapper<T> : T{
    public LoggingWrapper(){
        var virtualMethodsOfT = /* Do Reflection magic here */;
        foreach(var method in virtualMethodsOfT){
            this.CreateOverrideFunction(method.Name, ()=> LoggingOutline(method.BaseCall));
        }
    }

    static LoggingOutline(Action baseMethod){
    // Logging Code before
    baseMethod();
    // Logging Code after
    }
}

to make it look sexy i'd probably also store the reflection data in a in-memory dictionary, because i heard it's awfully slow





vendredi 17 septembre 2021

Is there a way to use .apply/.unapply on Generic objects?

I am using a Generic Mapper to map a Model from a DBModel in scala 2.11

it has a method defined as:

def fromModelToDBModel(m: T) : R

where T is the type of the Model and R is the type of the DBModel.

This method is implemented the same way in almost all inheriting objects, ie:

override def fromModelToDBModel(p: RawModel): RawDBModelV1 = {

val values = RawModel.unapply(p).get
val makeDBModel = (RawDBModelV1.apply _).tupled
makeDBModel(values)
}

Is it possible to somehow define a generic object in the base Trait, so I can call apply/unapply on it?





How to efficiently get value and attribute for each value in an enum?

I want to get the value and an attribute for each value in an enum.

I know I can loop the values.

foreach (TEnum value in Enum.GetValues(typeof(TEnum)))
{
    MemberInfo? info = value.GetType().GetMember(value.ToString()).FirstOrDefault();
    if (info != null)
    {
        CustomAttribute? attribute = info.GetCustomAttribute<CustomAttribute>();
        if (attribute != null)
            EnumLookup.Add(attribute.Code, value)
    }
}

But this seems horribly inefficient, having to call GetMember() and GetCustomAttribute() for each and every value.

If I used GetMembers() or GetFields() to get information for all the enum value, and then looped through them, it seems that would be more efficient.

FieldInfo[]? fields = typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (FieldInfo field in fields)
{
    CustomAttribute? attribute = field.GetCustomAttribute<CustomAttribute>();
    if (attribute != null)
        EnumLookup.Add(code, /* Whoops! What to put here? */ );
}

But then how could I get the value for each one?

Enums are strange because the values are like static fields, but there appears to be no way to get the value of a static field through reflection.

Note: EnumLookup is a dictionary that maps a code (stored in CustomAttribute) to the enum value.





Access Implementation's property on variable of type Interface

I'm trying to access the delegate of the property (id) of a class (FooImpl). The problem is, this class implements an interface (Foo), and the property in question overrides a property of this interface. The delegate only exists in the class (not that it could exist in the interface).

The problem is that using the :: operator on a variable of type Foo always returns the property of Foo, not that of the actual instance. The problem in code:

import kotlin.reflect.KProperty
import kotlin.reflect.KProperty0
import kotlin.reflect.jvm.isAccessible

interface Foo {
    val id: Int
}

class FooImpl(
    id: Int,
) : Foo {
    override val id: Int by lazy { id }
}

val <T> KProperty<T>.hasDelegate: Boolean
    get() = apply { isAccessible = true }.let { (it as KProperty0<T>).getDelegate() != null }

fun main() {
    val foo: Foo = FooImpl(1)
    println("foo::id.hasDelegate = ${foo::id.hasDelegate}")
    println("(foo as FooImpl)::id.hasDelegate = ${(foo as FooImpl)::id.hasDelegate}")
}

This prints:

foo::id.hasDelegate = false
(foo as FooImpl)::id.hasDelegate = true

But this requires compile-time knowledge of the correct implementation. What I'm looking for is accessing the correct propert without having to specify FooImpl there.

The information is present at runtime because the least (!) intrusive workaround I have found so far is adding fun idProp(): KProperty0<*> to Foo and override fun idProp() = ::id to FooImpl and accessing the property using that.

Is there any better way than that?





Java reflection setAccessible field of String class

I have the following java code

public static void main(String[] args) {
    Class<?> clazz = "string".getClass();
    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);
    }
}

But receive this warnings when I try to set field accessible:

WARNING: An illegal reflective access operation has occurred WARNING: Illegal reflective access by xxx to field java.lang.String.value WARNING: Please consider reporting this to the maintainers of xxx WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations WARNING: All illegal access operations will be denied in a future release

How can I avoid this warning and fix this piece of code?





Is there a way to get an object's private method to do nothing when called?

I'm writing an integration test in Java using JUnit, Mockito, and ReflectionTestUtils. I have the following situation:

Source code that I want to test:

class AClassINeed extends SomeClass{


  public method_I_need_to_call(){

    //some code
    method_that_fails();
    // lots of other calls

  }

  private boolean method_that_fails(){
    // Instantiate a new local object of external dependency
    // Call a method from this new object ==> AKA FAILURE
  }
}

Inside my test method: I need to create a realObject here so that all the real code gets exercises. Except for the method that will fail. I'm currently trying like this:

AClassINeed realObject = new AClassINeed(Lots.class, Of.class, Parameters.class);
AClassINeed spyObject = Mockito.spy(realObject);
Method spyObjectPrivateMethod = spyObject.getClass().getDeclaredMethod("method_that_fails");
spyObjectPrivateMethod.setAccessible(true);
when(spyObjectPrivateMethod).thenReturn(true); // <== Syntax error "Cannot resolve method thenReturn(boolean)"

How can I achieve this? I cannot create a mock object of AClassINeed because I want execute all methods normally except the one that fails.

I also tried with ReflectionTestUtils like this:

Method failingMethod = realObject.getClass().getDeclaredMethod("method_that_fails", String.class, String.class);
failingMethod.setAccessible(true);
ReflectionTestUtils.setField(realObject, "method_that_fails", failingMethod); // <== Wrong! This cannot be done for methods

At this point, I'm stumped.

Is there a way for me to get that failing method to do nothing without mocking out the entire class?





jeudi 16 septembre 2021

.NET Core plugin mixed dependency injection (sharing a dependency)

  • I have created a plugin with some services inside it.
  • The plugin library has its very own dependency injection container where all dependencies are registered.

Now, the problem.

I would like the plugin library to share a dependency with the "main" application. So, I designed the plugin boostrapping method so it provides you with an Action<ContainerBuilder> in which you could register extra dependencies for the plugin library (to share a dependency between them).

This is how it looks in a test:

[Fact]
public void Test()
{
    var pluginLocation = "somepath\\bin\\Debug\\net5.0\\Functions.dll";
    var functions = Core.Functions.Load(pluginLocation, containerBuilder => containerBuilder.RegisterType<Something>().As<ISomething>());
            functions.Should().NotBeEmpty();
}

The problem is that, even though ISomething is registered in the same container builder (I'm using AutoFac) it's not found when resolving the functions.

The following exception is thrown:

Autofac.Core.DependencyResolutionException : An exception was thrown while activating Deployer.Functions.Unzip.Unzip. ---- Autofac.Core.DependencyResolutionException : None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'Deployer.Functions.Unzip.Unzip' can be invoked with the available services and parameters: Cannot resolve parameter 'Share.ISomething something' of constructor 'Void .ctor(Deployer.Compression.IZipExtractor, Zafiro.Network.IDownloader, Shared.ISomething, System.IO.Abstractions.IFileSystem)'.

It looks like the ISomething used in the test isn't the same the plugin uses!!

NOTE: ISomething resides inside its own project called "Shared".

How do I fix this? Is it possible to do it?





Reflective Java exception when invoke method is used

I just started using reflective programming in Java, there is not much going on really, I am simply trying to invoke the class itself. Keep in mind that the code is all inside a class called TestBench and the package is lab01. The exception appears after the line before the last catch

m.invoke("lab01.TestBench", args);

I am confident that the issue is at the first argument.

public static void main(String[] ars)  
{
    
    try {
        testAlgorithm("Algorithms", "linear", 50);
        
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.err.println(e);
    }
    
      
}
 
{

    try
    {
        String name = "lab01.TestBench";
        Class cls = Class.forName("TestBench");
        
        Class partypes[] = new Class[4];
        partypes[0] = String.class;
        partypes[1] = Integer.TYPE;
        partypes[2] = Integer.TYPE;
        partypes[3] = Integer.TYPE;
        Method m = cls.getMethod(name, partypes);
        
        //TestBench ts = new TestBench();
        //String str = java.lang.String("TestBench");
        
        //Algorithms a = new Algorithms();
        Object args[] = new Object[4];
        args[0] = new String(methodName + ".txt");
        args[1] = Integer.valueOf(3);
        args[2] = Integer.valueOf(1);
        args[3] = n;
        
        m.invoke("lab01.TestBench", args);
        
    }
    catch (Throwable e)
    {
        System.err.println(e);
    }
}




IOS - Generic Decoder with reflection

I am using Realm with Swift. I need to create a generic method to initialize Realm classes with the type "required init(from: decoder: Decoder) because i can't write an initializer for every class. Possibly, i need even a method to generate CodingKeys automatically, because they are always the same as the class fields.

I tried with reflection but i's not working, because "mirror.children" is always empty.

Could someone help me?

Thank you for your patience and help!

This is my actual Code, and i wanna generalize the init(from decoder:Decoder)

import Foundation
import RealmSwift

class Items: Object, Decodable {
    
    var id = RealmProperty<Int?>()
    @objc dynamic var prop1: String? = nil
    @objc dynamic var prop2: String? = nil
    
    override static func primaryKey() -> String? {
        "id"
    }
    
    override init() {
        super.init()
    }
    
    enum CodingKeys: String, CodingKey {
        case id, prop1, prop2
        
    }
    
    required init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        let idV = Int(try (values.decodeIfPresent(String.self, forKey: .id) ?? "0"))
        id.value = idV
        prop1 = try values.decodeIfPresent(String.self, forKey: .prop1)
        prop2 = try values.decodeIfPresent(String.self, forKey: .prop2)
    }

    
}

This was the function i tried to do with reflection, but children is always empty. With this function i would loop over every field to specify how to decode it, in base of his type.

func reflect <T : Decodable>(_ t: T.Type){

let mirror = Mirror(reflecting: T.self)
        
for field in mirror.children {
    print("value: \(field.value)")
}

}

Thanks again!





C# Generic Return Type of Calling Object Type

I am making a class to abstract some functionality that I will be using in multiple other classes in my project. This class converts objects to and from JSON and also deep copies objects.

[Serializable]
public abstract class Serializable
{
    public T Copy<T>()
    {
        return Deserialize<T>(Serialize());
    }

    public string Serialize()
    {
        return JsonConvert.SerializeObject(this);
    }

    public static T Deserialize<T>(string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }
}

This code works as intended; however, I would like to simplify the syntax of the Copy and Desirialize functions. Currently, a call looks like this copy = descendantClassInstance.Copy<descendantClass>() which is wordy and also leaves room for error in that copy = otherdescendantClassInstance.Copy<descendantClass>() would compile but yield an error at runtime. I would prefer the return type be automatically inferred based on the type of the calling object, like copy = descendantClassInstance.Copy(), without overriding the Copy or Desirialize method in each descendant class.

How can I do this?





What does "loading a class" mean with the Android Runtime (ART) when using reflection?

I try to understand the process of ART when using reflection. As it can be seen in the simple example below, the DexClassLoader is used to load a class from the DEX-file. The question now is what is ART doing internally when loading a class?

From other sources, I found out that the previously used dalvikVM loads the bytecode of the class into memory and initializes static content during loading. The bytecode can then be interpreted by the dalvikVM (e.g. creating an instance of that class).

The Android documentation states that ART uses Ahead-of-time (AOT) compilation, which converts the bytecode in a DEX-file into some optimized code that is then executed on the device.

So, if I load a class via reflection is it compiled again and then executed? Or does it work the same way it did with the dalvikVM by loading and interpreting the bytecode?

Example:

ClassLoader cl = Thread.currentThread().getContextClassLoader();
DexClassLoader dexClassLoader = new DexClassLoader("path/to/dex", null, ".", cl);

Class<?> loadedClass = dexClassLoader.loadClass("com.package.MyClass");
            
Object instance = loadedClass.newInstance();

Method method = loadedClass.getDeclaredMethod("myMethodName", String.class);

Object result = method.invoke(instance, "my method input");

I would appreciate any additional information on this topic. Thanks!





Check some data for containing fields for some interface (Typescript)

I want to find solution for API (nodejs). When I get request with any data, I want to handle this data for specific model (interface, type etc.).

This repo descriptions perfectly my case. How can I get same result without changes typescript-compiler?

I tried to use reflection, but my knowledge of typesctipt isn't enough.

My example code logic:

type Person = {
    name: string,
    age: number,
    address: {
        city: string,
        street: string,
        house: number,
    },
};

const input_data = {
    name: 'John',
    age: 23,
    address: {
        city: 'NY',
        street: "Grand Street",
        house: 15,
    },
}


function check (data: any, InterfaceObjTitle: string): boolean {
    // *getting type InterfaceObjTitle (current case person) from the variable*
    // * cycle for checking fields of InterfaceObjTitle within data
}

check(input_data, 'Person ');




How to apply string comparision invariant to expression call in c# reflection?

I ahve a method like following and using entity framework search.

public static Expression Equals(Expression left, Expression right)
{
    var methodInfo = typeof(string).GetMethod("Equals", new[] { typeof(string) }) ?? throw new InvalidOperationException();

    var expr = Expression.Call(left, methodInfo, right);

    return expr;
}

But I want to add StringComparer.InvariantCulture in this expression call.

How can I do this?





How to apply cultureinfo to expression call in c# reflection?

I have an expression like following and using with entity framework:

    public static Expression Equals(Expression left, Expression right)
    {
        var methodInfo = typeof(string).GetMethod("Equals", new[] { typeof(string) }) ?? throw new InvalidOperationException();
        var toLowerMethod = typeof(string).GetMethod("ToLower", new Type[0]) ?? throw new InvalidOperationException();
        var trimMethod = typeof(string).GetMethod("Trim", new Type[0]) ?? throw new InvalidOperationException();

        var expr = Expression.Call(left, toLowerMethod);
        expr = Expression.Call(expr, trimMethod);
        expr = Expression.Call(expr, methodInfo, right);

        return expr;
    }

I want to add CultureInfo.InvariantCulture for typeof(string).GetMethod("ToLower" expression.

How can I do this?





Get annotation for enum type

How can I get SemanticId annotation value?:

@SemanticId("Something")
public enum SomeEnum {
    FIRST("First"),
    SECOND("Second")
}




How to get the complete Class type of Field in Java [duplicate]

class X {
    private String y;
}

class T {
    private List<X> w;
    private void run() {
        Field f = getClass().getDeclaredField("w");
        Class t = f.getType();// t is "Class of interface java.util.List", but what I want is "Class of java.util.List<X>", how to achieve it
    }
}

I have tried getAnnotatedType or something, but nothing valuable found





mercredi 15 septembre 2021

Static method in base class reflect the derived class name

Here is base class:

class Product
{
public:
    static void RegisterClass() {
        string b = __FUNCTION__;
    };
}

and here is the derived class.

class Milk: Product
{}

in the main function I call the static method this way:

main(){
    Milk.RegisterClass();
}

Then it writes value Product::RegisterClass into variable b. Is there a way to get value Milk::RegisterClass in the static method.

I don't want to instantiate the classes. And the main goal behind this scenario is to register Milk string somewhere.





How to use reflection to get all mvc pages and not partial views

I have used reflection to get all pages in a mvc .net framework application. I have looked for controller/action combination to name the items in the pages list. How ever it brings back views and partial views and I am just interested in the main views. How can I get just the main pages with reflection? Note I am using this to dictate which users can view which pages.

Assembly asm = Assembly.GetExecutingAssembly();

            var methods = asm.GetTypes()
                .Where(type => typeof(Controller).IsAssignableFrom(type)) //filter controllers
                .SelectMany(type => type.GetMethods())
                .Where(method => method.IsPublic && !method.IsDefined(typeof(NonActionAttribute)));




mardi 14 septembre 2021

Convert decimal to binary with reflection and generics in the static Convert class?

I'm trying to make a static generic function to convert decimal (numeric type) to a binary string.

Let me explain. I know that what I have to do is this:

int number = 12;
string binaryString = Convert.ToString(number, 2);

This is simple, but I also want to make the convertion decimal to binary with other parameters types, like bytes, shorts(Int16), longs(Int64). I know that Convert.Tostring() have all of the overloads for that and I simple need to do overloads like:

public static string DecToBinary(short number)
{
   return Convert.ToString(number, 2);
}

public static string DecToBinary(long number)
{
   return Convert.ToString(number, 2);
}
//etc

But I want to make it with generics and reflection... So I tried this:

public static string DecToBinary<T>(T number) where T : struct, IComparable, IFormattable, IConvertible
{
   return (string)typeof(Convert).GetMethod("ToString").Invoke(null, new object[] { number, 2 });
}

But I'm getting a problem on runtime that say:

Ambiguous match found.

and make sense, since reflection use a object as parameter type and never know what type I want...

Anyone can help me solve this problem?





How to make reflection work on JDK 16 and later?

I have the following legacy code that I migrated to Java 16 but that doesn't work:

try {
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);
    method.invoke(URLClassLoader.getSystemClassLoader(), file.toURI().toURL());
} catch (Exception e) {
    e.printStackTrace();
}

... Is there a way to make it works?





Create a delegate which returns enum's underlying int, without knowing the enum type at runtime

I am writing a settings system which relies on adding attributes to properties, and then using reflection.

For example, I create sliders by adding a SliderAttribute to float properties, then finding all those attributes and creating delegates to modify the associated property like so:

Func<float> getterDelegate = Delegate.CreateDelegate(typeof(Func<float>), arg, property.GetGetMethod()) as Func<float>;
Action<float> setterDelegate = Delegate.CreateDelegate(typeof(Action<float>), arg, property.GetSetMethod()) as Action<float>;

settingObj = new Slider(sliderAttribute, getterDelegate, setterDelegate);

Now, I'd like to create multiple choice objects by applying the same logic to enum values. That is I want to generate getter/setter delegates which modify the enum property via the underlying type (which we can assume is always int.)

The ideal would be the following, which returns the error ArgumentException: method return type is incompatible. Same result if I use the 'Enum' type.

Func<int> getterDelegate = Delegate.CreateDelegate(typeof(Func<int>), arg, property.GetGetMethod()) as Func<int>;
Action<int> setterDelegate = Delegate.CreateDelegate(typeof(Action<int>), arg, property.GetSetMethod()) as Action<int>;

settingObj = new MultipleChoice(multipleChoiceAttribute, getterDelegate, setterDelegate, property.PropertyType);




lundi 13 septembre 2021

Java reflection: add final modifier to a class field

I'm looking for a way to make an object immutable dynamically by setting all properties of a POJO to be final. One way I thought of is to use Java Reflection to set the modifier to final.

Consider the following POJO:

public class Task {

   private String id;
   private String code;

   // getters and setters placed here

}

Using the above POJO example, I'd like to make id and code have a final modifier. By researching some examples on the internet, these examples refer to using bitwise operators to unset the final modifier.

e.g. the common line that does that is:

modField.setInt(idField, idField.getModifiers() & ~Modifier.FINAL);

However, is there an example of setting the FINAL modifier to a field? thanks.





C# - A generics method with lambda as input [closed]

I am trying to rewrite some code that is part of a huge codebase. The code uses lambda expressions to pass objects to a common "Handler" that I am trying to rewrite. Here is a typical sample of code that I am given.

public class MyMessage : MyBaseClass
{
   public int ValueA {get;set;}
   public int ValueB {get;set;}
}
public class MyOtherMessage : MyBaseClass
{
   public int ValueC {get;set;}
   public int ValueD {get;set;}
}

public class Sender
{
   Handler handler = new Handler();
   handler.Send<MyMessage>(m => { m.ValueA=10; m.ValueB=20; });
}

Notice the Send-invocation with a lambda expression as input. The codebase has similar invocations 1000 of times. I would like to keep this code as it is. This code above used to call a Send-implementation in an old library that I am replacing with a new implementation of the Send-method. So I know that the invocation above work somehow.

I want to write a new Send method implementation that works with the Send invocation above.

In other words, I want to write the code of the Handler which shall receive the MyMessage object or the MyOtherMessage object. I know they are all subclasses of the common MyBaseClass.

I have tried it like this:

public class Handler
{
    public void Send<T>(Action<T> actionmessage)
    {
        // actionmessage is an object of type Action<T>, 
        // I want to get the object of type T that was passed into the method.
    }
}

The problem is that the object that is created with the lambda expression in the invocation is not easily retrieved. With my attempt here I get an action not an object. How do I get the object itself? I have also tried:

public class Handler
{
    public void Send<T>(T message)
    {
         // This will not compile. I get:
         //    Cannot convert lambda expression 
         //    to type 'object' because it is not a delegate type
    }
}

Maybe I need to use reflection somehow?





Issues running obfuscated DEX modules - AbstractMethodError

I'm developing an Android application based on a main APK installed on the mobile device, and some android modules that are compiled to a .dex file. These files are loaded at runtime by the main application and the classes inside the .dex files are instantiated via Dynamic Dex Loading.

I'm facing some issues related to proguard, as even if I use the @Keep annotation on exposed methods in the modules and the main APK and I tell to proguard to keep interfaces methods, when I call one of the methods implemented in a module i get:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.myproject, PID: 13893
java.lang.AbstractMethodError: abstract method "z.a com.android.myproject.MyClass.mymethod()"
    at com.android.myproject.MainService.H(:784)
    at com.android.myproject.MainService.M(:258)
    at com.android.myproject.MainService.a0(:198)
    at com.android.myproject.MainService.U(:148)
    at com.android.myproject.MainService.C(:133)
    at com.android.myproject.MainService.onServiceConnected(:90)...

If i try to debug, and i place a breakpoint right on the method call, using the "Evaluate Expression" tool in Android Studio I'm able to call the method with success, but if I let it execute on its own it crashes with the previous exception.

Can someone help me please? Thank you very much





dimanche 12 septembre 2021

How to get a specific Set

I want to use dart:analyzer for code generation and i want to construct a specific Set Type from a given DartType. So something like this:

final DartType t = getMyType(); // previously extracted type
final DartType result = Set<t>; // this does not work, just trying to illustrate what i want

Can i in any way create an instance of DartType for Set<t> or can i somehow get the LibraryElement to dart:core to get to the ClassElement of Set and then somehow place in my template parameter to get to the ClassElement of Set<t>?





instantiate object from derived class with constructor that takes super argument

Maybe what I am trying to do is not worthwhile, it sure feels that way after spending many days on it.

I have A Base Class shown here:

package jimmy.kilmer.com;

import java.awt.Color;


import jarPackageImports.AI;
import jarPackageImports.MovementAction;
import jarPackageImports.Info;
import jarPackageImports.PlayerAction;

public class GameAI extends AI {

    public gameAI(Info info) {
        super(info);
        setJerseyNumber(32);
    }

    public Color getColor() {
        return Color.RED;
    }

    public String getName() {
        return "Usain Bolt";
    }

    public PlayerAction update() {

        // TODO game movement actions
        // all available methods not listed here...
        info.getVelocity();
        info.getX();
        info.getY();


    MovementAction steeringBehavior = null;

        return steeringBehavior;
    }

    //basically used for testing setup
    public int[][] populateAllPossibleNodes() {
            int[][] allPossibleNodes = new int[screenWidth/20][screenHeight/20];
            return allPossibleNodes;
    }
}

I have been given a jar, that sets up the game environment. It uses reflection for the setup. I am not familiar with reflection, unfortunately, as I am more beginner level.

I have read a lot about TDD, and am convinced that can help me stay orderly, and code in a disciplined way. I have some say that TDD is not really useful for Game development, which the arguments may be true, in regard to making an "enjoyable game." But, from a purely coding standpoint, I remain steadfast in my believe that TDD is the way to go. But, that remains to be seen, since it is still theoretical. I would like to try it.

I have installed Junit 5, and have done many tutorials, but it's all pretty basic examples. My particular test case uses reflection, super classes, derived classes, dynamic data. My head is spinning.

My goal is just to get setup such that I can start doing some Test driven development.

Here is my Junit test class:

package jimmy.kilmer.com;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import jarPackageImports.Info;

class GameAITest {

  private GameAITest AIObject;
  private jarPackageImports.Info info;

    @BeforeEach
    void setUp() throws Exception {
        AIObject = new GameAITest(info);


    @AfterEach
    void tearDown() throws Exception {
    }

        @Test
    void testPopulateAllPossibleNodes() {
        // 1. given/arrange
        int[][] array1 = new int[80][65];
        // 2. when/act
        int[][] array2 = AIObject.populateAllPossibleNodes();
        // 3. then/assert
        assertArrayEquals(array1, array2);
    }

}

That is my best stab so far, but it still get a compile error. Specifically:

java.lang.NullPointerException:Cannot invoke "jarPackageImports.Info.getScene()" because "this.info" is null

In summation:

  1. maybe everything I am trying is rubbish?
  2. Do I need to use dynamic junit testing? I would have to read up on that.
  3. Do I need to mock (use Mockito?) to instantiate an object to test? I would need to read up on that as well.
  4. Is it possible to instantiate an object from GameAI? Do I need to/how would I use relection to do that? class.getConstructors()? And, I would have to read up on that.

thanks in advance.





'System.Reflection.TargetException: Object does not match target type' exception being thrown for trying to use property.setvalue call

In trying to optimize my code which used to have a select block for multiple fields, like diamond_0_color, diamond_0_quantity, I thought I would optimize my code to use reflection instead. The below code fails every time I try to set a property value of the baseobject class to a value with an exception of 'System.Reflection.TargetException: Object does not match target type', such as the below code:

SetClassPropertyValue(xmlItem, $"diamond_{intCurrentDiamond}_quantity",
                      clsDiamond.DiamondQuantity)

in the above example, xmlItem is an XML class, intCurrentDiamond is an int32 value = 0, diamond_0_quantity is an int32 field, and clsDiamond.DiamondQuantity is an int32 property. My code for SetClassPropertyValue below. Anyone see what I am doing wrong?

        Private Function SetClassPropertyValue(baseObject As Object, propertyName As String, value As Object) As Boolean

            Try

                Dim baseObjectType As Type = baseObject.GetType()
                Dim propertyInfo As PropertyInfo = baseObjectType.GetProperty(propertyName)

                If propertyInfo IsNot Nothing Then

                    Dim propertyType as Type = propertyInfo.GetType()
                    dim valueType as Type = value.GetType()

                    propertyInfo.SetValue(baseObjectType, value)
                    Return True

                Else

                    Display.ShowMessageBox("Fatal value set", $"Unable to set property '{propertyName}' to '{value}'")
                    Return False

                End If

            Catch ex As Exception

                Display.ShowMessageBox("Fatal value set", $"Unable to set property '{propertyName}' to '{value}' due to exception '{ex}'")
                Return False

            End Try

        End Function




How to clear all static event handlers in a class via reflection?

I have STATIC class with lots of static event callbacks. Instead of hard coding a reset method, I want to use reflection to automatically clear all the event subscriptions.


public static void NotifyA(int p1) { notifyA?.Invoke(p1); }
public static event Action<int> notifyA;

public static void NotifyB(float p1) { notifyB?.Invoke(p1); }
public static event Action<float> notifyB;

// and so on...

I am stuck at this stage don't know how to actually clear the events.

    public static void ResetEvents()
    {
        var type = typeof(ClientEvents);

        var events = type.GetEvents(BindingFlags.Static | BindingFlags.Public);

        foreach (var current in events )
        {
            // current.RemoveEventHandler(???);

        }
    }




samedi 11 septembre 2021

Activate type with generic params array set to null

Let's say I have this ctor:

public MyType<T>(int myInt, string myString, params T[] myObjects) { }

I could set the params array itself to null (rather than pass a null into the array):

MyType(1, "foo", (T[])null)

Let's say I want to do that dynamically. I tried this:

var args = new object[] { 1, "foo", null };
var myType = Activator.CreateInstance(typeof(MyType), BindingFlags.Instance | BindingFlags.NonPublic, null, args, null);

But that throws a MissingMethodException.

If I change the ctor's params T[] to params object[] then it works, but I prefer to keep the generic form.

How can I do this?





vendredi 10 septembre 2021

How to put function as parameter correctly

I can write these methods(onconnected, ondisc, onlogon, onlogof) on the MainClass class (there will be no problems, I will just send the name of the function to the parameter), but it will not be convenient to manage this file (MainClass). Because of this, I wrote these functions in a separate file (CallbackMethodsManager). But now, I can’t send a function from CallbackMethodsManager to MainClass using reflection (no other option came to mind)

When i run the app i getting an error: System.ArgumentException: 'Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.'

:at:

Action<TcallBack> action = Delegate.CreateDelegate(typeof(Action<TcallBack>), T, method) as Action<TcallBack>;

:if I understood correctly then the problem is in the typeof parameter. Please help because of why i getting error, how to correctly construct ReflectCallbackMethod() method, thanks.

ICallbackMethods.cs:

namespace SteamWhoDeletedMe.Interfaces
{
    interface ICallbackMethods
    {
        void OnConnected(SteamClient.ConnectedCallback callback, User user);
        void OnDisconnected(SteamClient.DisconnectedCallback callback, User user);
 
        void OnLoggedOn(SteamUser.LoggedOnCallback callback, User user);
        void OnLoggedOff(SteamUser.LoggedOffCallback callback);
    }
}

CallbackMethodsManager.cs:

namespace SteamWhoDeletedMe.Managers
{
    class CallbackMethodsManager : ICallbackMethods
    {
        public void OnConnected(SteamClient.ConnectedCallback callback, User user)
        {
            Console.WriteLine($"Connected to Steam! Logging in '{user.UserSteamLogin}'...");
 
            user.steamUser.LogOn(new SteamUser.LogOnDetails
            {
                Username = user.UserSteamLogin,
                Password = user.UserSteamPassword,
            });
        }
 
        public void OnDisconnected(SteamClient.DisconnectedCallback callback, User user)
        {
            Console.WriteLine("Disconnected from Steam");
 
            user.isRunning = false;
        }
 
        public void OnLoggedOff(SteamUser.LoggedOffCallback callback)
        {
            Console.WriteLine("Logged off of Steam: {0}", callback.Result);
        }
 
        public void OnLoggedOn(SteamUser.LoggedOnCallback callback, User user)
        {
            if (callback.Result != EResult.OK)
            {
                // if we recieve AccountLogonDenied or one of it's flavors (AccountLogonDeniedNoMailSent, etc) then the account we're logging into is SteamGuard protected
                if (callback.Result == EResult.AccountLogonDenied)
                {
                    // handle steamguard
 
                    Console.WriteLine("Unable to logon to Steam: This account is SteamGuard protected.");
 
                    user.isRunning = false;
                    return;
                }
 
                Console.WriteLine($"Unable to logon to Steam: [{callback.Result}] / [{callback.ExtendedResult}]");
 
                user.isRunning = false;
                return;
            }
 
            Console.WriteLine("Successfully logged on!");
        }
    }
}

MainClass.cs:

// steam user activities
var onCon = Utils<MainClass>.ReflectCallbackMethod<SteamClient.ConnectedCallback>(MC, "OnConnected");
var onDiscon = Utils<MainClass>.ReflectCallbackMethod<SteamClient.DisconnectedCallback>(MC, "OnDisconnected");
var onLogOn = Utils<MainClass>.ReflectCallbackMethod<SteamUser.LoggedOnCallback>(MC, "OnLoggedOn");
var onLogOff = Utils<MainClass>.ReflectCallbackMethod<SteamUser.LoggedOffCallback>(MC, "OnLoggedOff");
     
// register a few callbacks we're interested in these are registered upon creation to a callback manager, which will then route the callbacks to the functions specified
manager.Subscribe<SteamClient.ConnectedCallback>(onCon);
manager.Subscribe<SteamClient.DisconnectedCallback>(onDiscon);
manager.Subscribe<SteamUser.LoggedOnCallback>(onLogOn);
manager.Subscribe<SteamUser.LoggedOffCallback>(onLogOff);

screen: Screen





How can a .NET assembly detect its own version within an IIS ASP.NET context?

I have a c# function that works great in a winforms app to detect its container DLL's version as stamped in AssemblyInfo.cs:

private string getVersion() {
  System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
  FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location);
  string tempFileVersion = fvi.FileVersion;

  if (tempFileVersion.EndsWith(".0")) {
    return tempFileVersion.Substring(0, tempFileVersion.Length - 2);
  } else {
    return tempFileVersion;
  }
}

The problem is, this function throws exceptions when it's called as part of an ASP.NET webapp in IIS. I'm assuming it comes down to permissions problems, but is there a way for a function to ask the DLL it lives in "what is your version" inside an IIS context?





Java 11 reflection

I need a general means to determine if reflective access is allowed to an object member. In Java 8, if the member is public and the class is public, then reflective access is allowed. In Java 11, this is no longer true. So how can I determine if reflective access is allowed to an object member in Java 11? Here is some sample code illustrating the problem:

import java.lang.reflect.*;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;

public class Refl {
    public static void main(String[] args) throws Exception {
        //System.out.println(sun.security.ssl.SSLSocketFactoryImpl.class); // doesn't work
        SocketFactory sf = SSLSocketFactory.getDefault();
        SSLSocketFactory.class.getMethod("getDefaultCipherSuites").invoke(sf);
        Class cls = sf.getClass();
        System.out.println(cls);
        System.out.println(Modifier.isPublic(cls.getModifiers()));
        Method m = cls.getMethod("getDefaultCipherSuites");
        System.out.println(m);
        System.out.println(Modifier.isPublic(m.getModifiers()));
        m.invoke(sf);  // here is the issue
        System.out.println("done");
    }
}