mercredi 5 juillet 2023

How I can use method call with some argument [Reflection]

I try to use Dynamic DLL (Hangfire Core). Some methods of this lib has non-standard arguments, for example


 public static IGlobalConfiguration UseSimpleAssemblyNameTypeSerializer([NotNull] this IGlobalConfiguration configuration)

If i want call method with reflection help, I did:

  1. Load Assembly
  2. Get type from assembly
  3. Get method from type
  4. Try Invoke method

and, I got error:

Object of type 'System.RuntimeType' cannot be converted to type 'Hangfire.IGlobalConfiguration'."

My code:

        private static void GetField(string typeName, string pathToDll, string fieldName)
        {
            Type GlobalConfigurationType = Assembly.LoadFile(@pathToDll).GetType(typeName);
            Type GlobalConfigurationExtensionType = Assembly.LoadFile(@pathToDll).GetType("Hangfire.GlobalConfigurationExtensions");

            var propertyInfos = GlobalConfigurationType.GetProperties();
            var someProperty = propertyInfos[0];

            var UseSimpleAssemblyNameTypeSerializerMethod = GlobalConfigurationExtensionType.GetMethod("UseSimpleAssemblyNameTypeSerializer");

            UseSimpleAssemblyNameTypeSerializerMethod?.Invoke(null, new object[] { someProperty.PropertyType });
        }

How to do the conversion correctly?

I tried to set .PropertyType as argument





How to get all properties of instance of EF entity that are used to build relation

I have to write generic repository, so also method to add entities. The problem is with entities that have relationships to existing entities - they must be tracked.

So I have to write some code that will recognize which properties of some entity are used to built relationship and attach them.

How? I thought about something like that:

public async Task StoreAsync(TEntity model, CancellationToken cancellationToken = default)
{
    foreach (var prop in model.GetType().GetProperties().Where(p => p.GetType().IsClass))
    {
        var related = prop.GetValue(model)!;
        if (_dbContext.Entry(related).State == EntityState.Detached)
            _dbContext.Attach(prop.GetValue(model));
    }

    await _dbContext.Set<TEntity>().AddAsync(model, cancellationToken);
    await _dbContext.SaveChangesAsync(cancellationToken);
}

But there are multiple problems with this code - firstly, we get properties that are not value types, so record, delegate and class. Delegates and records cannot be entities.

And another (im not sure if this is problem) thing is that we attach all detached entities. But what if some entity currently doesnt exist in database? What if we attach non-exsiting and will use it like existing?

So how to get all properties of instance of EF entity that are used to build relation?

I use NET7





mardi 4 juillet 2023

How to use Fluent Assertions Should().Throw() with NOT hardcoded exception type?

I would like to use fluent assertions .Should().Throw, but do not want to hardcode the type of the expected exception, instead I want it parametrized, so it is in a variable which type is Type.

Without parametrized it should be the following:

Action act = () => sut.MyMethod();
act.Should().Throw<MyException>().Where(myPredicate);

However I would like to the type of MyException to be a parameter in a variable





lundi 3 juillet 2023

How can I find the defined type of a property/field at runtime in TypeScript?

I am trying to get the type of a property/field in TypeScript. Specifically, from the property decorator. The property does not have a value set so I can not derive it from the type of the value. Consider an example

class Example {
  abc: ABC
}

How would I get the class/class name of the property? To be specific, not the JavaScript 'primitive' type given by typeof x but the actual class(name), in this case ABC.

I've tried using reflect-metadata but it doesn't look like it's retaining the defined type in the metadata, running the following code:

console.log(Reflect.getMetadataKeys(target) + ", " + Reflect.getMetadata("design:type", target, propertyKey)

// -> ", undefined"

So it doesn't seem like there is any metadata relating to the type defined, or at all for that matter.





How to get the name of the embedding struct in Go? [duplicate]

I have a struct Base which is embedded in another struct. I want to access the name of the embedding struct dynamically within a method of Base. Here's an example:

package main

type Base struct{
}

func (b *Base) GetStructName() {
    // want to access which embedding struct called it i.e Test
}

type Test struct {
    Base
}

func main() {
    test := &Test{}
    test.GetStructName()
}

I have tried utilizing the runtime and reflect packages, but unfortunately, they haven't provided the desired outcome.





dimanche 2 juillet 2023

Enumerate classes within packages and jars in Kotlin

I have a project in Kotlin with two modules (ProjectName.ModuleA and ProjectName.ModuleB). Within these modules I have a package (com.company.projectName.moduleA and com.company.projectName.moduleB). Module B references Module A.

In ModuleA I have a library that defines an interface (called Flag). This interfaces has implementations in ModuleA and ModuleB. I'm now writing tests for ModuleB.

The thing is that I'd like a function in ModuleA (the main library) that loads all the classes that implement the Flag interface. What I'm expecting is that, when I run the tests of ModuleA only the ModuleA implementations are loaded, but when I run the tests of ModuleB, both ModuleA and ModuleB implementations are loaded, because when I use this library in the "real world" I will like to load all the implementations that exist in the libraries referenced.

I have this code, but this code only loads the classes of the current package.

private fun findFlags(packageName: String) {
    // Translate the package name into an absolute path
    var name = packageName
    if (!name.startsWith("/")) {
        name = "/$name"
    }
    name = name.replace('.', '/')
    // Get a File object for the package
    val url: URL = SimplyTheFlag::class.java.getResource(name)
    val directory = File(url.file)

    if (directory.exists()) {
        // Get the list of the files contained in the package
        directory.walk()
            .filter { f -> f.isFile && !f.name.contains('$') && f.name.endsWith(".class") }
            .forEach { it ->
                val className = it.canonicalPath.removePrefix(directory.canonicalPath)
                    .dropLast(6) // remove .class
                    .drop(1) // drop initial .
                    .replace('/', '.')
                val fullyQualifiedClassName = "$packageName.$className"

                val isFlag = Class.forName(fullyQualifiedClassName).interfaces.any { i -> i.simpleName == Flag::class.java.simpleName }
                if (isFlag) {
                    availableFlags[className] = fullyQualifiedClassName
                }
            }
    }
}

How can I implement this?





Specifying child method with base class object in Java

I've written below snippet to produce better and reusable code in all of Child classes.

Base Entity :

public class BaseEntity{
     Integer id; 
     //setter getters etc
}

Child Entity :

public class MyChild extends BaseEntity{
    String name;
    //setter getters etc
}

I have many child classes that extends BaseEntity and want to write a method to remove boilerplate code.

Util Class :

public class Util{
    public String getName(BaseEntity base){
        return base != null ? base.getChild().getName() : "";
    } 
}

The problem is base.getChild.name() How to do something like that when child isn't in a composition form ? I've reading about Java Reflection but don't know how to do it in an optimise way in this scenario.. Is there any better option than Reflection ?