mercredi 31 août 2022

How to sort a list based on multiple fields of sublcass dynamically

I am creating a Android Application which show list of Stores. The main Recyclerview shows the list of Store and every store object has SortingData which holds multiple fields like minimumDistance,rating etc.

By user selection i get a list of selected tags which size varies on the base of user selection and want to sort the main list of stores by it.

Every selected tag holds a propery isAscending which shows that it should be sorted in Ascending or Descending order. Lets say Rating with be Descending and Minimum Distance will be ascending and so on.

I have written a custom comparator to do so, to avoid multiple if conditions inside a loop but this comparator has issues. Like, its sorting the intergers based on first digit only doubles are also not sorted well.

Below is my code

data class Store(
    val name: String,
    val sortingData: SortingData,
    val status: String
) {
}
data class SortingData(
    val averageProductPrice: Int,
    val bestMatch: Double,
    val deliveryCosts: Int,
    val distance: Int,
    val minCost: Int,
    val newest: Double,
    val popularity: Double,
    val ratingAverage: Float
)

data class SortTag(var text: String, var key:String,var isSelected: Boolean,var isAscending:Boolean) {
}

Function

fun sortListByAdditionalTags(
    list: MutableList<Store>>,    selectedTags: List<SortTag>
): MutableList<Store> {
    /*
 Best Match -> Descending highest value on top
 Newest -> Descending highest value on top
 Rating Average -> Descending highest value on top
 Distance -> Ascending lowest value on top
 Popularity -> Descending highest value on top
 Average Product Price ->  Ascending lowest value on top
 Delivery cost ->  Ascending lowest value on top
 Min cost->  Ascending lowest value on top
 */
    var sorted = list
    selectedTags.forEach {
        sorted = list.sortedWith(
            comparator = AdditionalSortComparator(
                it.key,
                it.isAscending
            )
        ) as MutableList< Store 
>

    }
    return sorted

}

Custom Sort Comparator

class AdditionalSortComparator(
    private val sortProperty: String? = null,
    private val isAscending: Boolean
) : Comparator<Store> {
    override fun compare(o1: Store?, o2: Store?): Int {
        val sortingData =
            Store::class.declaredMemberProperties.firstOrNull { it.name == "sortingData" }

        val s1: sortingData = o1?.let { sortingData?.get(it) } as sortingData
        val s2: sortingData = o2?.let { sortingData?.get(it) } as sortingData

        val calledVariable = SortingData::class.declaredMemberProperties.firstOrNull { it.name == sortProperty }
        return if (calledVariable != null) {
            if (calledVariable.get(s1) is Int) {
                val valueFirst = calledVariable.get(s1) as Int
                val valueSecond = calledVariable.get(s2) as Int
                if (isAscending) valueFirst - valueSecond else valueSecond - valueFirst
            } else if (calledVariable.get(s1) is Float) {
                val valueFirst = calledVariable.get(s1) as Float
                val valueSecond = calledVariable.get(s2) as Float
                if (isAscending) valueFirst - valueSecond else valueSecond - valueFirst
            } else if (calledVariable.get(s1) is Double) {
                val valueFirst = calledVariable.get(s1) as Double
                val valueSecond = calledVariable.get(s2) as Double
                if (isAscending) abs(valueFirst-valueSecond) else abs(valueSecond-valueFirst)
            }

            if (isAscending) calledVariable.get(s1).toString()
                .compareTo(calledVariable.get(s2).toString())
            else calledVariable.get(s2).toString()
                .compareTo(calledVariable.get(s1).toString())
        } else {
            val idProperty = Store::name
            val valueFirst = idProperty.get(o1)
            val valueSecond = idProperty.get(o2)
            if (isAscending) valueFirst.compareTo(valueSecond) else valueSecond.compareTo(valueFirst)
        }
    }
}

The dependency i used for Kotlin Reflection is

implementation("org.jetbrains.kotlin:kotlin-reflect:1.7.10")

Can somebody please help me out with this, how i can achieve this functionality in an efficient and correct manner?





Unable to get DeclaredField "usr_paths " via java reflection 17.0.3

Hello to everyone sitting on this forum, enter code hereI ran into a problem, I will be very glad if you can help me.

So I'm trying to get usr_paths, but the console gives an error that it can't find this field, what should I do?

public static void addDir(String s) throws IOException {
    try {
        Field field = ClassLoader.class.getDeclaredField("usr_paths"); // there's a error here !!
        field.setAccessible(true);
        String[] paths = (String[]) field.get(null);
        for (int i = 0; i < paths.length; i++) {
            if (s.equals(paths[i])) {
                return;
            }
        }
        String[] tmp = new String[paths.length + 1];
        System.arraycopy(paths, 0, tmp, 0, paths.length);
        tmp[paths.length] = s;
        field.set(null, tmp);
        System.setProperty("java.library.path", System.getProperty("java.library.path") + File.pathSeparator + s);
    } catch (IllegalAccessException e) {
        throw new IOException("Failed to get permissions to set library path");
    } catch (NoSuchFieldException e) {
        throw new IOException("Failed to get field handle to set library path");
    }
}




mardi 30 août 2022

c# Iterate over var with value obtained with GetValue()

In an MVC 5 c# application, I am attempting to extract values from objects at runtime using strings for property names. The process works fine until the value extracted is a collection. I am unable to write the code to iterate over the extracted value.

using System;
using System.Collections.Generic;               
public class Program
{
    public static void Main()
    {
        Student student = new Student { 
             Lectures = new List<Lecture>{ 
                new Lecture { Title="Science"},
                new Lecture {Title="Math"}
             }
        };
        
        var obj = student;
        string fld = "Lectures";

        // The following code knows nothing about Students or Lectures
        // It does know that the "fld" is a property name of "obj" that contains a collection

        var items = obj.GetType().GetProperty(fld).GetValue(obj);
        foreach (var item in items)
        {
            // Code to process item
        }
    }
}

public class Lecture
{
     public string Title {get;set;}
}

public class Student
{
   public List<Lecture> Lectures {get;set;}
}

The above "for" instruction is flagged as a syntax error with the red highlight on "items". The error indicates that it cannot operate on variables of type "object" because "object" does not contain a public definition for GetEnumerator.

Pasting the above code into https://dotnetfiddle.net illustrates the issue.

Is what I attempting possible? When debugging, "items" does show as a collection of Lecture.





lundi 29 août 2022

IllegalAccessException on calling constructor after loading class via URLClassLoader

I try to load a class from file system(which is not in the cp of my main) and then want a new instance of that loaded class like this:

try {
    File folder = new File("/tmp/");
    URLClassLoader loader = URLClassLoader.newInstance(new URL[] {folder.toURI().toURL()});
    Class clazz = loader.loadClass("testpkg.test");
    Constructor constructor = clazz.getConstructor();
    Object instance = constructor.newInstance();
} catch (Exception e) {
    e.printStackTrace();
}

the class file exists in the /tmp/testpkg directory and has the name test.class. The code for the uncompiled .java looks like this:

package testpkg;
class test{
    public test(){
            System.out.println("I am the constructor!");
    }
}

unfortunately I get a runtimeError at the following line:

Object instance = constructor.newInstance();

which says:

java.lang.IllegalAccessException: Class tmp.ClassLoadingFun can not access a member of class testpkg.test with modifiers "public"
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:102)
at java.lang.reflect.AccessibleObject.slowCheckMemberAccess(AccessibleObject.java:296)
at java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:288)
at java.lang.reflect.Constructor.newInstance(Constructor.java:413)
at tmp.ClassLoadingFun.<init>(ClassLoadingFun.java:16)
at tmp.ClassLoadingFun.main(ClassLoadingFun.java:23)

When i fuzz around with the package or class name, it will terminate earlier stating, there is no proper class found. So I guess the loading of the class works. Only calling the constructor does not. Why can't I access this public(!) constructor?





Is it safe to modify private variables using ReflectionUtils

Java ReflectionUtils gives us a way to make private variables accessible and modifiable. I just wrote some code which intercepts a process and modifies some private variables of an object.

How safe is this? My doubt is, What if in future, the person who owns this object decides to rename it to something else ? Since its a private var, he is completely entitled to.

If this is unsafe, then what is the point of ReflectionUtils allowing us to set private variables at all ?

Thanks in advance.





Use Spirv-Reflect with GLSL shader doesn't find any information

I'm working with vulkan 1.2 and i try to reflect the input, ouput of the shader here:

#version 450

layout(location = 0) in vec2 inPosition;
layout(location = 1) in vec3 inColor;

layout(location = 0) out vec3 fragColor;

void main() {
    gl_Position = vec4(inPosition, 0.0, 1.0);
    fragColor = inColor;
}

The goal is to automatically set correctly the layout(location) line in the pipeline Currently, i reflect my shader like this:

void Shader::reflectInput(const std::vector<char>& code)
    {
        SpvReflectShaderModule spvModule = {};
        SpvReflectResult result = spvReflectCreateShaderModule(sizeof(code), reinterpret_cast<const uint32_t*>(code.data()), &spvModule);
        assert(result == SPV_REFLECT_RESULT_SUCCESS);
        uint32_t count = 0;
        result = spvReflectEnumerateInputVariables(&spvModule, &count, NULL);
        assert(result == SPV_REFLECT_RESULT_SUCCESS);
        std::vector<SpvReflectInterfaceVariable*> input_vars(count);
        result = spvReflectEnumerateInputVariables(&spvModule, &count, input_vars.data());
        assert(result == SPV_REFLECT_RESULT_SUCCESS);
        count = 0;
        result = spvReflectEnumerateOutputVariables(&spvModule, &count, NULL);
        assert(result == SPV_REFLECT_RESULT_SUCCESS);

        std::vector<SpvReflectInterfaceVariable*> output_vars(count);
        result = spvReflectEnumerateOutputVariables(&spvModule, &count, output_vars.data());
        assert(result == SPV_REFLECT_RESULT_SUCCESS);

        if (spvModule.shader_stage == SPV_REFLECT_SHADER_STAGE_VERTEX_BIT)
        {
            binding_description.binding = 0;
            binding_description.stride = 0;
            binding_description.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;

            attribute_descriptions.reserve(input_vars.size());
            for (size_t i_var = 0; i_var < input_vars.size(); ++i_var)
            {
                const SpvReflectInterfaceVariable& refl_var = *(input_vars[i_var]);
                if (refl_var.decoration_flags & SPV_REFLECT_DECORATION_BUILT_IN)
                    continue;
                VkVertexInputAttributeDescription attr_desc{};
                attr_desc.location = refl_var.location;
                attr_desc.binding = binding_description.binding;
                attr_desc.format = static_cast<VkFormat>(refl_var.format);
                attr_desc.offset = 0;  // final offset computed below after sorting.
                attribute_descriptions.push_back(attr_desc);
            }
            std::sort(std::begin(attribute_descriptions), std::end(attribute_descriptions),
                [](const VkVertexInputAttributeDescription& a, const VkVertexInputAttributeDescription& b) {
                    return a.location < b.location; });
            // Compute final offsets of each attribute, and total vertex stride.
            for (auto& attribute : attribute_descriptions) {
                uint32_t format_size = FormatSize(attribute.format);
                attribute.offset = binding_description.stride;
                binding_description.stride += format_size;
            }
        }
    }

    uint32_t Shader::FormatSize(VkFormat format)
    {
        uint32_t result = 0;
        switch (format) {
        case VK_FORMAT_UNDEFINED: result = 0; break;
        case VK_FORMAT_R4G4_UNORM_PACK8: result = 1; break;
        case VK_FORMAT_R4G4B4A4_UNORM_PACK16: result = 2; break;
        case VK_FORMAT_B4G4R4A4_UNORM_PACK16: result = 2; break;
        case VK_FORMAT_R5G6B5_UNORM_PACK16: result = 2; break;
        case VK_FORMAT_B5G6R5_UNORM_PACK16: result = 2; break;
        case VK_FORMAT_R5G5B5A1_UNORM_PACK16: result = 2; break;
        case VK_FORMAT_B5G5R5A1_UNORM_PACK16: result = 2; break;
        case VK_FORMAT_A1R5G5B5_UNORM_PACK16: result = 2; break;
        case VK_FORMAT_R8_UNORM: result = 1; break;
        case VK_FORMAT_R8_SNORM: result = 1; break;
        case VK_FORMAT_R8_USCALED: result = 1; break;
        case VK_FORMAT_R8_SSCALED: result = 1; break;
        case VK_FORMAT_R8_UINT: result = 1; break;
        case VK_FORMAT_R8_SINT: result = 1; break;
        case VK_FORMAT_R8_SRGB: result = 1; break;
        case VK_FORMAT_R8G8_UNORM: result = 2; break;
        case VK_FORMAT_R8G8_SNORM: result = 2; break;
        case VK_FORMAT_R8G8_USCALED: result = 2; break;
        case VK_FORMAT_R8G8_SSCALED: result = 2; break;
        case VK_FORMAT_R8G8_UINT: result = 2; break;
        case VK_FORMAT_R8G8_SINT: result = 2; break;
        case VK_FORMAT_R8G8_SRGB: result = 2; break;
        case VK_FORMAT_R8G8B8_UNORM: result = 3; break;
        case VK_FORMAT_R8G8B8_SNORM: result = 3; break;
        case VK_FORMAT_R8G8B8_USCALED: result = 3; break;
        case VK_FORMAT_R8G8B8_SSCALED: result = 3; break;
        case VK_FORMAT_R8G8B8_UINT: result = 3; break;
        case VK_FORMAT_R8G8B8_SINT: result = 3; break;
        case VK_FORMAT_R8G8B8_SRGB: result = 3; break;
        case VK_FORMAT_B8G8R8_UNORM: result = 3; break;
        case VK_FORMAT_B8G8R8_SNORM: result = 3; break;
        case VK_FORMAT_B8G8R8_USCALED: result = 3; break;
        case VK_FORMAT_B8G8R8_SSCALED: result = 3; break;
        case VK_FORMAT_B8G8R8_UINT: result = 3; break;
        case VK_FORMAT_B8G8R8_SINT: result = 3; break;
        case VK_FORMAT_B8G8R8_SRGB: result = 3; break;
        case VK_FORMAT_R8G8B8A8_UNORM: result = 4; break;
        case VK_FORMAT_R8G8B8A8_SNORM: result = 4; break;
        case VK_FORMAT_R8G8B8A8_USCALED: result = 4; break;
        case VK_FORMAT_R8G8B8A8_SSCALED: result = 4; break;
        case VK_FORMAT_R8G8B8A8_UINT: result = 4; break;
        case VK_FORMAT_R8G8B8A8_SINT: result = 4; break;
        case VK_FORMAT_R8G8B8A8_SRGB: result = 4; break;
        case VK_FORMAT_B8G8R8A8_UNORM: result = 4; break;
        case VK_FORMAT_B8G8R8A8_SNORM: result = 4; break;
        case VK_FORMAT_B8G8R8A8_USCALED: result = 4; break;
        case VK_FORMAT_B8G8R8A8_SSCALED: result = 4; break;
        case VK_FORMAT_B8G8R8A8_UINT: result = 4; break;
        case VK_FORMAT_B8G8R8A8_SINT: result = 4; break;
        case VK_FORMAT_B8G8R8A8_SRGB: result = 4; break;
        case VK_FORMAT_A8B8G8R8_UNORM_PACK32: result = 4; break;
        case VK_FORMAT_A8B8G8R8_SNORM_PACK32: result = 4; break;
        case VK_FORMAT_A8B8G8R8_USCALED_PACK32: result = 4; break;
        case VK_FORMAT_A8B8G8R8_SSCALED_PACK32: result = 4; break;
        case VK_FORMAT_A8B8G8R8_UINT_PACK32: result = 4; break;
        case VK_FORMAT_A8B8G8R8_SINT_PACK32: result = 4; break;
        case VK_FORMAT_A8B8G8R8_SRGB_PACK32: result = 4; break;
        case VK_FORMAT_A2R10G10B10_UNORM_PACK32: result = 4; break;
        case VK_FORMAT_A2R10G10B10_SNORM_PACK32: result = 4; break;
        case VK_FORMAT_A2R10G10B10_USCALED_PACK32: result = 4; break;
        case VK_FORMAT_A2R10G10B10_SSCALED_PACK32: result = 4; break;
        case VK_FORMAT_A2R10G10B10_UINT_PACK32: result = 4; break;
        case VK_FORMAT_A2R10G10B10_SINT_PACK32: result = 4; break;
        case VK_FORMAT_A2B10G10R10_UNORM_PACK32: result = 4; break;
        case VK_FORMAT_A2B10G10R10_SNORM_PACK32: result = 4; break;
        case VK_FORMAT_A2B10G10R10_USCALED_PACK32: result = 4; break;
        case VK_FORMAT_A2B10G10R10_SSCALED_PACK32: result = 4; break;
        case VK_FORMAT_A2B10G10R10_UINT_PACK32: result = 4; break;
        case VK_FORMAT_A2B10G10R10_SINT_PACK32: result = 4; break;
        case VK_FORMAT_R16_UNORM: result = 2; break;
        case VK_FORMAT_R16_SNORM: result = 2; break;
        case VK_FORMAT_R16_USCALED: result = 2; break;
        case VK_FORMAT_R16_SSCALED: result = 2; break;
        case VK_FORMAT_R16_UINT: result = 2; break;
        case VK_FORMAT_R16_SINT: result = 2; break;
        case VK_FORMAT_R16_SFLOAT: result = 2; break;
        case VK_FORMAT_R16G16_UNORM: result = 4; break;
        case VK_FORMAT_R16G16_SNORM: result = 4; break;
        case VK_FORMAT_R16G16_USCALED: result = 4; break;
        case VK_FORMAT_R16G16_SSCALED: result = 4; break;
        case VK_FORMAT_R16G16_UINT: result = 4; break;
        case VK_FORMAT_R16G16_SINT: result = 4; break;
        case VK_FORMAT_R16G16_SFLOAT: result = 4; break;
        case VK_FORMAT_R16G16B16_UNORM: result = 6; break;
        case VK_FORMAT_R16G16B16_SNORM: result = 6; break;
        case VK_FORMAT_R16G16B16_USCALED: result = 6; break;
        case VK_FORMAT_R16G16B16_SSCALED: result = 6; break;
        case VK_FORMAT_R16G16B16_UINT: result = 6; break;
        case VK_FORMAT_R16G16B16_SINT: result = 6; break;
        case VK_FORMAT_R16G16B16_SFLOAT: result = 6; break;
        case VK_FORMAT_R16G16B16A16_UNORM: result = 8; break;
        case VK_FORMAT_R16G16B16A16_SNORM: result = 8; break;
        case VK_FORMAT_R16G16B16A16_USCALED: result = 8; break;
        case VK_FORMAT_R16G16B16A16_SSCALED: result = 8; break;
        case VK_FORMAT_R16G16B16A16_UINT: result = 8; break;
        case VK_FORMAT_R16G16B16A16_SINT: result = 8; break;
        case VK_FORMAT_R16G16B16A16_SFLOAT: result = 8; break;
        case VK_FORMAT_R32_UINT: result = 4; break;
        case VK_FORMAT_R32_SINT: result = 4; break;
        case VK_FORMAT_R32_SFLOAT: result = 4; break;
        case VK_FORMAT_R32G32_UINT: result = 8; break;
        case VK_FORMAT_R32G32_SINT: result = 8; break;
        case VK_FORMAT_R32G32_SFLOAT: result = 8; break;
        case VK_FORMAT_R32G32B32_UINT: result = 12; break;
        case VK_FORMAT_R32G32B32_SINT: result = 12; break;
        case VK_FORMAT_R32G32B32_SFLOAT: result = 12; break;
        case VK_FORMAT_R32G32B32A32_UINT: result = 16; break;
        case VK_FORMAT_R32G32B32A32_SINT: result = 16; break;
        case VK_FORMAT_R32G32B32A32_SFLOAT: result = 16; break;
        case VK_FORMAT_R64_UINT: result = 8; break;
        case VK_FORMAT_R64_SINT: result = 8; break;
        case VK_FORMAT_R64_SFLOAT: result = 8; break;
        case VK_FORMAT_R64G64_UINT: result = 16; break;
        case VK_FORMAT_R64G64_SINT: result = 16; break;
        case VK_FORMAT_R64G64_SFLOAT: result = 16; break;
        case VK_FORMAT_R64G64B64_UINT: result = 24; break;
        case VK_FORMAT_R64G64B64_SINT: result = 24; break;
        case VK_FORMAT_R64G64B64_SFLOAT: result = 24; break;
        case VK_FORMAT_R64G64B64A64_UINT: result = 32; break;
        case VK_FORMAT_R64G64B64A64_SINT: result = 32; break;
        case VK_FORMAT_R64G64B64A64_SFLOAT: result = 32; break;
        case VK_FORMAT_B10G11R11_UFLOAT_PACK32: result = 4; break;
        case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: result = 4; break;

        default:
            break;
        }
        return result;
    }

I'm just following the example Spirv-reflect give, nevertheless, it doesn't find any information. So maybe i'm using wrong (it's probably that^^). Even the simple information spvModule.shader_stage is equal to 0 when i try to do it.

I precise that i translate my shader to spirv code. And it's the spv file i give to my reflection code.

Do you have ideas of what i could do wrong? Bad shader wrting? Bad use of the library?





dimanche 28 août 2022

How to sort a collection based on java.lang.reflect.Field? [duplicate]

I'm stuck in a situation where I only got Fields (java.lang.reflect) of a given class.

To help you better imagine, let's say we have code:

List<Apple> sortApplesByFieldName(List<Apple> apples, String fieldName) {
    Field field = Apple.class.getDeclaredField(fieldName);

    // some stream logic for sorting using this var
    return apples;
}

Can someone actually solve this problem?

Also, using a switch statement is not an option, as fields can change.

Note, the class Apple is a regular POJO with private fields and public getters/setters.





Changing Annotation value via Reflection does not work JDK17

I have spring boot application with some controllers.

All the controllers have @RequestMapping annotation with a path/value attribute. I would like to change the value of this attribute at runtime by hooking into the bean lifecycle.

I am using BeanPostProcessor.postProcessBeforeInitialization() to accomplish this and below is the reflection code that I use:

public class RequestMappingProcessor implements BeanPostProcessor
{
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException
    {
        RequestMapping requestMapping = bean.getClass().getAnnotation(RequestMapping.class);

        System.out.println("OldAnnotation Value " + requestMapping.value()[0]);

        Map<String, Object> attributes = AnnotationUtils.getAnnotationAttributes(requestMapping);
        String[] values = (String[]) attributes.get("path");
        var newValue = getNewPath(path);

        Object handler = Proxy.getInvocationHandler(annotation);
        Field f;
        try
        {
            f = handler.getClass().getDeclaredField("memberValues");
        }
        catch (NoSuchFieldException | SecurityException e)
        {
            throw new IllegalStateException(e);
        }
        f.setAccessible(true);
        Map<String, Object> memberValues;
        try
        {
            memberValues = (Map<String, Object>) f.get(handler);
        }
        catch (IllegalArgumentException | IllegalAccessException e)
        {
            throw new IllegalStateException(e);
        }
        Object oldValue = memberValues.get(key);
        if (oldValue == null)
        {
            throw new IllegalArgumentException();
        }
        memberValues.put(key, newValue);
        memberValues.put("path", newValue);
        
        System.out.println("New Annotation Value " + requestMapping.value()[0]);
}

The things is that I do see it printing the updated values on console, but when I check the actual endpoint in postman or browser, still the old path works and not the new one. JDK 17.

I know that many would suggest to set the prefixed path at API level for all the controllers and all, but in my case, each controller might have a different prefix based upon some annotation. If you have some other suggestions, please suggest.





IQueryable dynamic recursive expression

Fast Question: How to rewrite this

builder.Entity<User>().HasQueryFilter(s =>
            httpContextAccessor.HttpContext.User.GetGroup() == s.Institute ||
            httpContextAccessor.HttpContext.User.IsInRole(ERole.Root.ToString()));

from model builder layer to bussines and logic layer with all includes.

Description and problem itself:

I have this interface

public interface IInstituteEntity
{
    public string Institute { get; set; }
}

And I want to get all entities from database where entity itself or ANY of it's properties(recursive: childs of childs) has Institute property that equals my filter OR user has role "Root" (notice that properties can not be included and can be empty/null as well)

I'm not strong with Expression Trees and can not find suitable solution, I have basic example without recursion:

public static IQueryable<T> HasInstituteAccess<T>(this IQueryable<T> entities,
        IHttpContextAccessor accessor) where T : IInstituteEntity
    {
        var user = accessor.HttpContext?.User;
        if (user is null) return Enumerable.Empty<T>().AsQueryable();
        
        return user.IsInRole(ERole.Root.ToString())
            ? entities.Cast<T>()
            : entities.Where(HasInstituteAccessFilter<T>(user)).Cast<T>();
    }

private static Expression<Func<T, bool>> HasInstituteAccessFilter<T>(ClaimsPrincipal principal)
        where T : IInstituteEntity
        => arg => principal.GetGroup() == arg.Institute;

I need it as workload about global filters that covers includes, that's the thing:

builder.Entity<User>().HasQueryFilter(s =>
            httpContextAccessor.HttpContext.User.GetGroup() == s.Institute ||
            httpContextAccessor.HttpContext.User.IsInRole(ERole.Root.ToString()));

But it not suits me because I need to manualy specify IgnoreQueryFilters() for all queries that have no need in this logic, so it's better to write in manually via extensions above

Expected query:

var userInfo =
            await context.UserInfo.AsNoTracking()
                .Where(ui => !ui.IsDeleted)
                .Include(ui => ui.User)
                .HasInstituteAccess(accessor)
                .FirstOrDefaultAsync(ui => ui.Id == request.Id, cancellationToken);

Expected result: return some info if authorized user has access to ui.User.Institute (UserInfo has no institute property)





samedi 27 août 2022

GetActualTypeArguments returns TypeVariableImpl with only the symbol (T) as the class name

I've looked at the bytecode and I can see that within my class the type parameters have not been erased, I've tried the getActualParameters on generic superclass way as well as using TypeToken but both appear to simply return T/TypeVariableImpl which I don't believe can give me the actual class of the parameter.

This shouldn't be a duplicate as I've searched far and wide and cannot find an answer to this, and each one I've tried either presents me with Object or T, neither of which are of any use to me.

public class EventConsumer<T extends INonkbookEvent<INonkbookEventParameter>> extends EventListener<T>

Essentially I want to reflect the T param, having looked at the bytecode I can see this implementation is compiled: my compiled eventlistener class





vendredi 26 août 2022

Set current context class loader

I have 2 ClassLoaders, one which I don't have access to source code and second which I'm loading classes now. ( I'm using java agents to inject code. )

My problem is when I try to load class which has been loaded by the different ClassLoader, it's not working.

// some different class loader
// also this is the ClassLoader which loaded GL11
ClassLoader cl = getDifferentClassLoader();

this.getClass().getClassLoader() == cl // false

GL11.glPushMatrix(); // NoClassDefFoundError

But when I call it using reflection, it works

Class<?> clazz = cl.loadClass("org.lwjgl.opengl.GL11");
clazz.getDeclaredMethod("glPushMatrix").invoke(null); // this works

I tried something like this but it's not working :(

Thread.currentThread().setContextClassLoader(cl);
GL11.glPushMatrix();

Is something like this possible?





jeudi 25 août 2022

ReflectionClass::getProperties() : properties in order of declaration?

When running this code:

class MyClass {
    public int $one;
    public int $two;
    public int $three;
}

$rc = new ReflectionClass(MyClass::class);
foreach ($rc->getProperties() as $property) {
    echo $property->getName() . "\n";
}

, the properties in the output are ordered like in the class declaration:

one
two
three

Can I rely on this ordering, concerning ReflectionClass::getProperties()?

Context: I want to use a class to represent a specific file format, each class property being a field in the file (using Php attributes to characterize each of them). The ordering of the fields in the file is of course a necessity.





BC32050 Type parameter 'T' .... cannot be inferred

I tried mapping under plain ado.net to object using the excerpt of the code below

calling the code

dim personList as List(of Person) = new List<Person>()
personList = GetList(of Person)(iconn,"persons")

the function

Public Function GetList(Of T As Class)(conn As IDbConnection, tableName As String) As List(Of T)
    ' get body
Using cmd As New MySqlCommand(sql, conn, trans)
        'cmd.Parameters.Add( ,)
        Using rdr = cmd.ExecuteReader()
            ret = MapToObject(rdr) -----> Error line
        End Using
    End Using
    Return ret
' rest of body
End Function

'Map data

Public Function MapToObject(Of T As {Class, New})(dr As IDataReader) As List(Of T)
' Function body
End Function

bu t i get the following error

BC32050 Type parameter 'T' for 'Public Function MapToObject(Of T As {Class, New})(dr As IDataReader) As List(Of T)' cannot be inferred.

Where am i getting it wrong?





How do I use a type switch to determine the type of a protoreflect.MessageDescriptor?

I am writing a protoc generation plugin using the protogen package.

I am looping the fields of a message and want to determine if a field is one of a few different message types.

It is possible to get the name of the message type as a string using:

field.Desc.Message().FullName() // mypackage.MyMessage

The problem with this approach is that I will need to switch against a string, which is error-prone:

switch field.Desc.Message().FullName(){
  case "mypackage.MyMessage":

  case "mypackage.MyMessage2":
}

Is there anyway to do this using a type assertion? I tried to create an instance of the message using dynamicpc, but the type assertion does not work:

mt := dynamicpb.NewMessage(field.Desc.Message())

msg, ok := mt.(*mypackage.MyMessage) // ok is false despite field.Desc.Message().FullName() returning mypackage.MyMessage




mercredi 24 août 2022

Java MethodHandlers.lookup().findStatic throws NoSuchMethodException

So i have been doing some things that involve Java MethodHandlers. And the reflection api has been around for a long time so there is a lot of documentation about it.

MethodHandlers on the other hand hasn't been around as long so there is a lot fewer examples. What im trying to do is to invoke a static void function that mutates a state using the MethodHandlers Api.

Here is a runnable example that demonstrates my problem:

class Main {
    public static void main(String[] args) throws Throwable {

        System.out.println("Times before: " + Foobar.getTimes());
        final Class<?> aClass = MethodHandles.lookup().findClass(Foobar.class.getName());

        incReflectionApi(aClass);
        incMethodHandler(aClass);

    }

    private static void incReflectionApi(Class<?> aClass) throws Throwable {
        final Method init = aClass.getMethod("increment", (Class<?>[]) null);
        init.invoke(null, (Object[]) null);

        System.out.println("Reflection api: " + Foobar.getTimes());
    }

    private static void incMethodHandler(Class<?> aClass) throws Throwable {

        // Here is where we throw
        final MethodHandle handle = MethodHandles.lookup().findStatic(aClass, "increment", MethodType.methodType(Void.class));
        handle.invoke();

        System.out.println("MethodHandler api: " + Foobar.getTimes());
    }

    public static class Foobar {

        private static int times;

        public static void increment() {
            times++;
        }

        public static int getTimes() {
            return times;
        }
    }
}

So basically, access the increment function and invoke it. Doing so with reflective api getMethod works fine. But when i try to use MethodHandler.lookup#findStatic i get a NoSuchMethodException.

Here is the output of the example:

Times before: 0
Reflection api: 1
Exception in thread "main" java.lang.NoSuchMethodException: no such method: Main$Foobar.increment()Void/invokeStatic
    at java.base/java.lang.invoke.MemberName.makeAccessException(MemberName.java:963)
    at java.base/java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:1101)
    at java.base/java.lang.invoke.MethodHandles$Lookup.resolveOrFail(MethodHandles.java:2030)
    at java.base/java.lang.invoke.MethodHandles$Lookup.findStatic(MethodHandles.java:1102)
    at Main.incMethodHandler(scratch_5.java:26)
    at Main.main(scratch_5.java:14)
Caused by: java.lang.NoSuchMethodError: 'java.lang.Void Main$Foobar.increment()'
    at java.base/java.lang.invoke.MethodHandleNatives.resolve(Native Method)
    at java.base/java.lang.invoke.MemberName$Factory.resolve(MemberName.java:1070)
    at java.base/java.lang.invoke.MemberName$Factory.resolveOrFail(MemberName.java:1098)
    ... 4 more

Am i missing something obvious?





org.reflections without specifying a package

I am coding a little "framework" to be used by other people. For that, it is necessary to find a class that has a specific annotation at runtime.

This is a simple task using org.reflections library. However, as far as I know this library needs a package prefix to search the annotation in (cannot leave it blank). But since the framework is supposed to be used by several people, I cannot limit the package prefix.

Instead, I want to search the entire scope for classes with the given annotation.

Is this possible with org.reflections? Note that I cannot rely on any contextual dependencies like spring because the framework should work in every environment





Get arguments from functional interface

What's up, on the backend there was an idea to transfer some functionality to the queue. What is meant:

  1. We have a functional interface analogous to Callable<?>.

    @FunctionalInterface
    public interface QueueFunction<T, R> {
        T runq(R ... args);
    }
    
  2. But a function can have multiple arguments, so I resorted to the barbaric R... args method. I was bitten by a pythonist at that moment.

  3. There is a LinkedBlockingQueue<?> queue, where, in theory, in place of the question mark should be my interface QueueFunction<T, R>

  4. And when the call of the corresponding function with the marked annotation should happen, then (there is still a problem of how to intercept the call of this function in the spring there is @Scheduled I want something like that) I need to intercept this call and redirect it to the queue in order to call from the queue thread pool its implementation.

  5. I don't know how to poop ((((

A little about my research:

I tried to create a FutureTask<?> implementation for myself, but now I can’t really enter how and what works there, I know the principle, but if you climb further along legacy, you can rip permanently.

There is an option to make an adapter for Runnable, which hides Thread.There is something similar in Legacy Java.

private static final class RunnableAdapter<T> implements Callable<T> {
    private final Runnable task;
    private final T result;
    RunnableAdapter(Runnable task, T result) {
        this.task = task;
        this.result = result;
    }
    public T call() {
        task.run();
        return result;
    }
    public String toString() {
        return super.toString() + "[Wrapped task = " + task + "]";
    }
}

Perhaps I have paws in this matter, and not enough skill. I am open to your suggestions :-*

Edition #1

I have a method:

@Queued(paramsCount = 3)
public String mergeInvoices(String acc_owner, String report_oid, String invoice_template_jr) throws IOException {
    //do merge
}

It is a reflection of the QueueFunction<T,R>, where R are the arguments to this method and T is the return value. There can be many such methods as in the example. And there can be different numbers of arguments. I want to annotate them with the number of parameters. And send this method for execution by a queue (so to speak). Execution by analogy with the annotation @Scheduled (Spring/Micronaut), which sets the schedule. Perhaps there will be some other way.

But this function needs to be added to the execution queue. From the queue, it should be picked up by free threads and executed.

Example:

    @EventListener
    @Async
    public void runQueues(final ServiceReadyEvent event) throws InterruptedException {
        logger.info("starting queues...");
        checkQueues(true);
        for (int i = 0; i < workersCount; i++) {
            (new Thread(this::runHouseCalc)).start();
            logger.info("Run thread worker for House Calc " + i);
        }
        for (int i = 0; i < workersCount; i++) {
            (new Thread(this::runInvCalc)).start();
            logger.info("Run thread worker for Invoice Calc " + i);
        }
    }


    private void runInvCalc() {
        while (isRunning) {
            MeHouseInvoiceQueue inv = null;
            try {
                functionsRepository.setUserId(suId);
                inv = calcInvQueue.take();
                functionsRepository.setInvoiceQueueStatus(inv.getId(), "processing", null, null, null, null);

                long startSeed = new Date().getTime();
                logger.info("event inv taken");
                logger.info("oid = " + inv.getId() + " position: " + inv.getPosition() + " state: " + inv.getProcessing_status());


                File file = reportsService.getFile(reportsService.getParametersForInvoices(inv));

                long endSeed = new Date().getTime();

                functionsRepository.setInvoiceQueueStatus(inv.getId(), "ready", file.getPath(), (int) Files.size(Path.of(file.getPath())), null, new SimpleDateFormat("HH:mm:ss").format(new Date((endSeed - startSeed)- 10800000L)));

            } catch (Exception e) {
                if (inv != null) functionsRepository.setInvoiceQueueStatus(inv.getId(), "ERROR", null, null, e.getMessage(), null);
                logger.error(e.getMessage());
            }
        }
    }

Tnx for -2, guys...





mardi 23 août 2022

C# reflection get all properties inside the proerperties with custom attribute

I am writing a method for extracting all properties from an object (including properties of its own) with custom attribute . For example

  public class SomeModel
{

    [Custom]
    public string Name { get; set; }


    public string TestData { get; set; }

    [Custom]
    public string Surname { get; set; }

   public  InnerModel InnerModel { get; set; }
}

And Inner Model :

  public class InnerModel
{
    public string Id { get; set; } = "TestID";

    [Custom]
    public string Year { get; set; }

    public ThirdObject HidedObject { get; set; }
}

And the third one :

 public class ThirdObject
{
    [Custom]
    public string  HidedName { get; set; }
}

I need to find all properties with "Custom" attribute . Testing :

SomeModel model = new SomeModel()
        {
            Name = "farid",
            Surname = "Ismayilzada",
            TestData = "Test" ,
            InnerModel = new InnerModel() { Year ="2022" , HidedObject= New ThirdObject{ HidedName="Secret"}}
        };

I need to write the method

GetMyProperties(model) => List<PropInf>()
[PropertyName= Name,Value=Farid ,Route="Name" ]
[PropertyName= Surname,Value=Ismayilzada,Route="Surname" ]
[PropertyName= Year,Value=2022,Route="InnerModel.Year" ]
[PropertyName= HidedName,Value=Secret,Route="InnerModel.HidedObject.HidedName" ]

How to get this information ?





Is it possible to 'decorate' a function to change its internal variables and function calls?

I have this code

let someFunc1 = () => {
    const name1 = callFn({"k1": "v1", "k2": "v2"})
    const name2 = callFn({"k1.1": "v1.1", "k2.1": "v2.1"})
    const name3 = callFn({"k1.2": "v1.2", "k2.2": "v2.2"})
}

let someFunc2 = () => {
    const name4 = callFn({"k1": "v1", "k2": "v2"})
    const name5 = callFn({"k1.1": "v1.1", "k2.1": "v2.1"})
    const name6 = callFn({"k1.2": "v1.2", "k2.2": "v2.2"})
}

I'd like to add the following behaviour to all of these "someFunc" functions:

  • Take a json object argument of the form { : {k1: v1}, : {k2: v2}, ... } which finds a variable (if it exists) with the same name as and modifies the arguments to that callFn (if exists then update it to , else create a new key-value pair)

Desired behaviour and outcome examples:

eg 1. If I wish to change the parameters to the callFn returning the variable "name2" by updating "k2.1" to "myNewValue" I would then be able to call someFunc1( { "name2": {"k2.1": "myNewValue"} } ), which would effectively change someFunc1 to read:

let someFunc1 = () => {
    const name1 = callFn({"k1": "v1", "k2": "v2"})
    const name2 = callFn({"k1.1": "v1.1", "k2.1": "myNewValue"})
    const name3 = callFn({"k1.2": "v1.2", "k2.2": "v2.2"})
}

eg. 2 To add a new key-value pair ("myNewKey: "myNewValue") to the parameters passed to to the callFn returning the variable named "name6" I would be able to call someFunc2( { "name6": {"myNewKey": "myNewValue"} } ) which would effectively change someFunc2 to read:

let somefunc2 = () => {
    const name4 = callfn({"k1": "v1", "k2": "v2"})
    const name5 = callfn({"k1.1": "v1.1", "k2.1": "v2.1"})
    const name6 = callfn({"k1.2": "v1.2", "k2.2": "v2.2", "myNewKey": "myNewValue"})
}

I'm new to JS to not sure this is possible but if it is, guessing there might be some way to use decorators and/or reflection to achieve this?





lundi 22 août 2022

linq 'where' with using reflection doesn't work

I'm trying to get items with using linq and reflection:

var type = "Home";
var list = new List<object>();
... some initialization
var selectedItems = list.Where(x => x.GetType().GetProperty("Type").GetValue(x) == type);

into selectedItems I want to get 2 items (that matches condition), but I get one

What's wrong in this code? Thanks in advance





can i use reflection and source generators to read structures and make new flattened structures from them I need to flatten these structs C#

Read this using reflection.

public struct WSSort
{
  public byte OrderCount;
  
  [CustomStructSize(20)]
  public Int32[] Product;
  
  public Int32 Length;
  public Int32 Moisture;
  public Int32 Stamps;

and use source generators to flatten[the arrays] in these structures

public byte OrderCount;

[CustomStructSize(20)]
public Int32 Product1; // this has the 1st element from publicInt32[]Product;
public Int32 Product2;  // this has the 2nd element from publicInt32[]Product;
    
public Int32 Product3;
public Int32 Product4;
public Int32 Product5;
    
public Int32 Length;
public Int32 Moisture;
public Int32 Stamps;

I used custom attributes to distinguish btw the stuff to read and flatten and I was able to read the structures but was not able to write them using source generators. I can't figure out how to see the generated file or debug the source generator.





dimanche 21 août 2022

Get actual type parameter from instance at runtime

I have instance of class with type parameter. I want to find actual type parameter, not just some generic information returned by getTypeParameters method:

public class Program {
    public static void main(String[] args) {
        ClassWithParam<Class1> instance1 = new ClassWithParam<>(new Class1());
        Class c1 = getTypeParam(instance1); // I want this to be Class1.class
    }

    private static Class getTypeParam(ClassWithParam<?> instance) {
         var typeParameters = instance.getClass().getTypeParameters();
         // nothing useful here...
    }

    private static class Class1 { }

    private static class ClassWithParam<T> {
        public ClassWithParam(T value) { }
    }
}




how to write dynamic LINQ, using reflection to check property value and sum base on it

I have table in database and class for it

public class LocalDefaultIndicatorCostsDto
    {
        [Column("ReportingYear")]
        public int YearNo { get; set; }
        [Column("Quarter")]
        public int Quarter { get; set; }
        [Column("tur/exc")]
        public int TurOrExc { get; set; }
        [Column("VisitGoalID_New")]
        public double VisitGoalIDNew { get; set; }
        [Column("VisitGoalName_New")]
        public string VisitGoalNameNew { get; set; }
        [Column("ActivityStatusID_New")]
        public double ActivityStatusIDNew { get; set; }
        [Column("ActivityStatusName_New")]
        public string ActivityStatusNameNew { get; set; }
        [Column("RateID")]
        public int RateID { get; set; }
        [Column("RateName")]
        public string RateName { get; set; }
        [Column("GenderID")]
        public int GenderID { get; set; }
        [Column("GenderName")]
        public string GenderName { get; set; }
        [Column("Age_gr_id")]
        public double AgeGrID { get; set; }
        [Column("Age_gr")]
        public string AgeGr { get; set; }
        [Column("xarji_mln_lari")]
        public double? XarjiMlnLari { get; set; }
    }

and I want to sum property XarjiMlnLari, for year 2021 and ActivityStatusIDNew == 1. I have this LINQ, but it not worcking (error massage - could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.)

PropertyInfo propInfo = typeof(LocalDefaultIndicatorCostsDto).GetProperty("ActivityStatusIDNew");

var dicValue = await portalContext.LDIC
                                            .Where(x => x.YearNo == 2021 && 
                                            (double)propInfo.GetValue(x, null) == (double)1)
                                            .SumAsync(x => x.XarjiMlnLari);

thanks for advance





samedi 20 août 2022

C# calling Reactive/ReactiveUI extension methods via reflection

I'm trying to call the equivalent of this code via reflection:

prop.WhenAnyValue(s => s.Value).Skip(1).Subscribe(...);

This is the reflection code I use to "solve" the WhenAnyValue part:

MethodInfo[] whenAnyMethods = typeof(WhenAnyMixin).GetMethods();
MethodInfo whenAnyMethod = new Func<MethodInfo>(() =>
{
    foreach (var mi in whenAnyMethods)
    {
        if (mi.Name == "WhenAnyValue" && mi.GetGenericArguments().Length == 2)
        {
            return mi;
        }
    }

    return null;
})();

MethodInfo whenAnyMethodGeneric = whenAnyMethod.MakeGenericMethod(new Type[] { containingType, propertyType });
var whenAnyResult = whenAnyMethodGeneric.Invoke(null, new object[] { containingObject, expression });

The containing object derives from ReactiveObject (ReactiveUI).

The type of the result is exactly the same as when I'm calling WhenAnyValue directly on a property I'm interested in (without reflection), so I think I got this part right. :)

Now I'm trying to skip:

MethodInfo[] methods = typeof(Observable).GetMethods();
MethodInfo skipMethod = new Func<MethodInfo>(() =>
{
    foreach (var mi in methods)
    {
        if (mi.Name == "Skip" && mi.GetParameters().Length == 2 && mi.GetParameters()[1].ParameterType == typeof(int))
        {
            return mi;
        }
    }

    return null;
})();

MethodInfo skipMethodGeneric = skipMethod.MakeGenericMethod(new Type[] { whenAnyResult.GetType() });
var skipResult = skipMethodGeneric.Invoke(null, new object[] { whenAnyResult, 1 }); <<< this line throws the exception

On execution of the last line an exception is thrown:

System.ArgumentException: "Object of type 'System.Reactive.Linq.ObservableImpl.Select`2+Selector[ReactiveUI.IObservedChange`2[type1,type2],type3]' cannot be converted to type 'System.IObservable`1[System.Reactive.Linq.ObservableImpl.Select`2+Selector[ReactiveUI.IObservedChange`2[type1,type2],type3]]'."

And here I'm stuck. What am I missing?





How to get nullable properties with reflection using GetType().GetProperties()?

I am not getting nullable properties when using reflection with GetType().GetProperties()

The Property is

public DateTime? StartingFrom { get => _startingFrom; set { _startingFrom = value; OnPropertyChanged(); } }

Is there something I must add to include nullable properties??





Setting Event handler in properties of object using reflection

In a C# / WPF App, I have an abstract UI that allows to display and modify the content of objects given.

Change in the objects are detected by the "PropertyChanged" event (PRISM) and the callback needs to be set.

The objects are derived from a base class and contains properties, some of these properties can be also editable objects and contains enumerable, each items of those needs to be set the PropertyChanged action.

Whilst this can be easily done from the child class which has the knowledge of the content of the object, I would like to keep that code on the base class, which doesn't necessarily knows the content of the derived object.

The goal is to loop through the object events and check whether the "PropertyChanged" exists in which case we assign it.

This is as far as I've gotten, but does not work

    void SetModifiedCallback(object src)
    {
        PropertyInfo[] properties = src.GetType().GetProperties();
        
        foreach (PropertyInfo property in properties)
        {
            var value = property.GetValue(src);
            
            if ((property.GetType() != typeof(string)) && 
                (typeof(IEnumerable).IsAssignableFrom(property.PropertyType)))
            {
                var col = (IEnumerable)value;
                
                if (col != null)
                {
                    foreach (var item in col)
                    {
                        if (item.GetType().IsSubclassOf(typeof(BindableBase)))
                        {
                            (item as BindableBase).PropertyChanged += Recipe_PropertyChanged;
                        }
                    }
                }
            }
        }
    }




vendredi 19 août 2022

Is adding pre/post invocation logic to original method possible for C# properties using standard reflection libs?

Currently I'm working with a project on Unity3d engine and want to implement "Observer component" which will listen for property changing in other components.

The good idea is implement https://docs.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-implement-property-change-notification?view=netframeworkdesktop-4.8, but, I don't want to implement it in each component I want to "listen".

So, my original vision (if simplify it) is

  1. Get the "MonoBehaviour" via GameObject reference
  2. Get all properties via Reflection (GetType().GetProperties())
  3. Modify "set" method by adding to it "preInvocation/postInvocation" logic.

The second way is get the reference to the property, and check the value each "Update" method. But, this way (maybe?) is more slowly.

Also, I found the good library for adding listeners before/after methods https://harmony.pardeike.net/articles/intro.html, but, not sure, if I really need to use this library for only this case

Maybe, there is more easy way using standard c# functionality?

P.S. Sorry for my bad english





Runtime Reflection Library for c++ that allow serialization and deserialization of custom types

I'm looking for a library that allows to serialize and deserialize custom types in a few lines of code.

I've already tested this library RTTR, but unluckily it does not fit my purpose (also is poorly documented).

What I wish to achieve in pseudo-code is something like:

void serializeInstance(instance)
{
    for (property in instance)
    {
        serializeProperty("propertyName", property);
    }
}

void deserializeInstance()
{
    // Getting the type of the component from a string stored in a file
    type = getType(component["Type"]); 

    decltype(type) component;
    
    properties = getProperties(component["Properties"]);

    for (propertyName in properties)
    {
        // need to cast this to the right type
        component.property = getPropertyValue(propertyName["Value"]);
    }
}

To make it simple I'm trying to do something similar to what Unity does with the serialization of components.





find all java classes on classpath whose simple name matches some regex

I would like to search the runtime classpath to find all classes with a simple name that matches some regex.

Example:
Say I have Some.jar on my classpath and that jar contains a class called MyCoolClass.class. I would like some way of finding all classes that contains the word "Cool" like the one above and perhaps several others.

Also, I would like to get either the Class or the fully qualified class name (such that I can call Class.forName).





jeudi 18 août 2022

Prevent the reference to any mutable state in a delegate

For a little framework that will be used in C# 10 (or newer) projects I would like to build a processor that is optimized for executing CPU bound (CPU intensive) user code asynchronously and concurrently. The goal of this processor is that it makes it very hard (or even impossible) to access mutable state inside that user code, therefore helping the novice developer not shooting themselves in the foot by running into concurrency issues.

For that I have created a delegate like so:

// InputData and OutputData are guaranteed to be fully immutable
public delegate Task<OutputData> ProcessDelegate(InputData input, CancellationToken cancellationToken);

The processor has a method that can take an instance of the delegate:

public class Processor
{
    public Task<OutputData> ProcessAsync(
        ProcessDelegate process, InputData input, CancellationToken cancellationToken)
    {
        // the process delegate is queued and executed based on different strategies
    }
}

Now my question:

How can I make it hard (or even impossible?) for the novice user to use any reference to an object that contains mutable state inside the user code (body) of the delegate that is passed to the ProcessAsync method of the Processor class?

Maybe I could ship the framework with an analyzer that detects this and puts out a warning?

If detecting mutable state is too hard to achieve, is there a way to detect whether the delegate body uses any reference except the InputData and CancellationToken passed to it?

Please keep in mind that ProcessAsync can be called in many ways (lamda, local function, instance method, static method, anonymous delegate etc.)





I can't access custom attribute in dispatch proxy invoke method in .netcore6

I cannot access the custom attribute I wrote for the method within the invoke method.

Attribute class :

public class HttpTypeAttribute : Attribute
{
    public string Type { get; set; }
    public HttpTypeAttribute(string type)
    {
        Type = type;
    }
}

Web function:

 [HttpType("POST")]
    public ResponseDTO Run(RequestDTO requestDTO)
    {
        var result = ProxyManager<TestInterface>.CreateProxy(url).Run(requestDTO);
        return result;
    }

Invoke method:

protected override object Invoke(MethodInfo targetMethod, object[] args)
    {
          
        HttpTypeAttribute attr = (HttpTypeAttribute)targetMethod.GetCustomAttributes(typeof(HttpTypeAttribute), true).FirstOrDefault();  // attr is null
          
    }

Is there any way to do this? I would be glad if you help.





mercredi 17 août 2022

JavaParser to modify attributes and methods of a java class

I am trying to make a program that corrects me a certain Java class according to the input data type.

I was given a .java file that defines Animals, it has the following form:

Animals.java

public class Animal {
  Mammal mammal;
  Bird bird;
  Fish fish;
  ...
  
  class Mammal {
    Dog dog;
    Cat cat;
    Horse horse;
    ...

    class Dog {
      String name;
      String weight;

      void setWeight(String name){...}
      String getWeight() {...}
    }

    class Cat {
      String name;
      Double weight;

      void setWeight(Double name){...}
      Double getWeight() {...}
    }
    ...
  }
  class Bird {...}
  class Fish {...}
  ...
}

And text files containing:

a.getMammal().getDog().setWeight("50");
a.getMammal().getDog().setName("Fluffy");
a.getMammal().getCat().setWeight("25");
a.getMammal().getCat().setName("Kitty");
...
...
...
...

Since I have tons of text files with tons of lines in it, it is infeasible (manually) verifiying that the input parameter (always is a String) matches with the required datatype of the setter, and if not changing the class that matches the input parameter.

So I started searching for some tools to change a Java class (methods and attributes) programatically.

What I want to achive in pseudocode would be:

1) OPEN A TXT FILE
2) READ LINES
3) IF DATATYPE OF METHOD SIGNATURE != DATATYPE INPUT
4) THEN FIX .Java FILE
5) ELSE CONTINUE

I already have steps 1 - 3, I used Reflections library, but I don't know how to proceed to Step 4 (I don't even know if it is possible to modify a java file programmatically)

To clarify, an example:

lines.txt
----------------------------------------
1   a.getMammal().getDog().setWeight("50");
2   a.getMammal().getCat().setWeight("23");
----------------------------------------

open lines.txt

read line -> line = a.getMammal().getDog().setWeight("50");

get params type -> 
    methodType = String  (a.getMammal().getDog().setWeight(), the attribute weight in Dog is defined as String)
    inputType = String   ("50" is a String)

compare types -> Since both coincide, do nothing to Animals.java and read next line

read line -> a.getMammal().getCat().setWeight("23");

get params type -> 
    methodType = Double  (a.getMammal().getCat().setWeight(), the attribute weight in Cat is defined as Double)
    inputType = String   ("23" is a String)

compare types -> Since both  no coincide, fix and update Animals.java

end program

At the end of the execution, the file Animals.java would look like this:

Animals.java

public class Animal {
  Mammal mammal;
  Bird bird;
  Fish fish;
  ...
  
  class Mammal {
    Dog dog;
    Cat cat;
    Horse horse;
    ...

    class Dog {
      String name;
      String weight;

      void setWeight(String name){...}
      String getWeight() {...}
    }

    class Cat {
      String name;
      **String** weight;

      void setWeight(**String** name){...}
      **String** getWeight() {...}
    }
    ...
  }
  class Bird {...}
  class Fish {...}
  ...
}




mardi 16 août 2022

Using reflection class in PHP also unable to access private property

How to access private property values outside the class? I also tried using reflection in PHP.

<?php
namespace TDD;
class Receipt {

    public $user_id = 1;
    private $pending_amount = 45;   

    
    public function total(array $items = []){   
    $items[] = $this->pending_amount;
       return array_sum($items);
    }

    public function tax($amount,$tax){
        return $amount * $tax;
    }
    
    public function pending()
    {
        return $this->pending_amount = 45;
    }
    
    public function addTaxPending($tax){
        return $this->pending_amount * $tax;
    }
}


$class = new \ReflectionClass('TDD\Receipt');
$myProtectedProperty = $class->getProperty('pending_amount');
$myProtectedProperty->setAccessible(true);
$myInstance = new Receipt();
$myProtectedProperty->setValue($myInstance, 99);

echo $myInstance->pending_amount;


?>

Error: ` $ php src/Receipt.php PHP Fatal error: Uncaught Error: Cannot access private property TDD\Receipt::$pending_amount in C:\xampp\htdocs\all_scripts\PHPUnit_By_siddhu\src\Receipt.php:48 Stack trace: #0 {main} thrown in C:\xampp\htdocs\all_scripts\PHPUnit_By_siddhu\src\Receipt.php on line 48

Fatal error: Uncaught Error: Cannot access private property TDD\Receipt::$pending_amount in C:\xampp\htdocs\all_scripts\PHPUnit_By_siddhu\src\Receipt.php:48 Stack trace: #0 {main} thrown in C:\xampp\htdocs\all_scripts\PHPUnit_By_siddhu\src\Receipt.php on line 48 ` error screenshot

How can I solve it? Looking for your valuable solutions.





.Net Emit - Add Try Catch block to existing method in runtime

I use the PubSub mechanism the send events in my application, each event has a custom handler that use to handle it.

My problem is that in many places the handler suppled as the following:

SubscriberService.Subscribe(new SubscribeRequest<string>
{  
   Topic = TopicName,
   Action = async pubSubEvent => await DoSomthingAsync()
}

the return type of Action is void so behind the scenes this lambda translated to async void.

So when an exception occur I have no chance to catch it.

I wondered to myself if there is a way to create a method at runtime that warp the method body of the action with a try-catch block that catches the exception when they occur and write them to the log.

I saw some articles about the Emit.IlGenerator class could help but I have no idea where to start.

I would love to hear any suggestions to deal with these issues.

Thanks!





Assigning to type alias using reflection in Go

I have setup a type called Provider that aliases an integer:

type Provider int

func (enum *Provider) Scan(raw interface{}) error {
    *enum = Provider(int(raw))
}

If I create an object, Foo, with a Provider field, like this:

type Foo struct {
    Code Provider
    Value string
}

foo := &Foo {
    Code:  Provider(0),
    Value: "derp",
}

var scnr sql.Scanner
scannerType := reflect.TypeOf(&scnr).Elem()

tType := reflect.TypeOf(foo)
tField := tType.Field(0)
fmt.Printf("Field %s, of type %s, kind %s\n", 
    tField.Name, tField.Type, tField.Type.Kind())

When I run this code, I get that the field is of type Provider and its Kind is int. However, I cannot assign an int to a Provider using reflection because this will fail:

fValue := reflect.ValueOf(foo).Elem()
vField := fValue.Field(0)
vField.Set(reflect.ValueOf(1)) // panic: reflect.Set: value of type int is not assignable to type Provider

Is there a way I can make this work?





How to keep default constructor after declared another in java?

I want to access default constructor from a class, (after I create another constructors with any parameters), without declared him!

How can I access default constructor without declared him?





dimanche 14 août 2022

Is there a way to replace the mirror package for flutter?

this is flutter rsocket-dart code.

https://github.com/rsocket/rsocket-dart/blob/master/lib/route/reflection.dart

but, I cant't to use this library in flutter, because this package use 'dart:mirrors' packages.
So, I want to change this code.

but, I very very low level... I can't to understood this code...

import 'dart:mirrors';

import '../rsocket.dart';
import 'package:collection/collection.dart' show IterableExtension;

RSocketService? getRSocketServiceAnnotation(dynamic instance) {
  final DeclarationMirror clazzDeclaration = reflectClass(instance.runtimeType);
  final classMirror = reflectClass(RSocketService);
  final annotationInstanceMirror =
      clazzDeclaration.metadata.firstWhereOrNull((d) => d.type == classMirror);
  if (annotationInstanceMirror == null) {
    print('Annotation is not on this class');
    return null;
  }
  return annotationInstanceMirror.reflectee as RSocketService?;
}

How can I change this code to not use mirror?





vendredi 12 août 2022

How to access running program from dynamically loaded dll

So I'm trying to access a running program from which I've injected an external DLL at runtime. I have two projects: console app and class library.

Console app:

using System;
using System.Reflection;

namespace SharpConsole
{
    public class GameEvent
    {
        private bool _cancelled;

        public bool Cancelled { get => _cancelled; }

        public void SetCancelled(bool cancelled)
        {
            _cancelled = cancelled;
        }

        public override string ToString()
        {
            return $"Event (Cancelled={Cancelled})";
        }
    }

    public class API
    {
        public static void Print(string text)
        {
            Console.WriteLine($"[API] {text}");
        }
    }

    public class Program
    {
        public static string TestValue = "some initial test value";

        static void Main(string[] args)
        {
            var evt = new GameEvent();

            Console.WriteLine("[Console] " + evt.ToString());
            Console.WriteLine("[Console] Loading dll...");
            // var asm = Assembly.LoadFile(@"C:\Users\tinytengu\Desktop\SharpTest\SharpExternal\bin\Release\netcoreapp3.1\SharpExternal.dll");
            var asm = Assembly.LoadFile(@"C:\Users\tinytengu\SharpExternal\SharpExternal.dll");

            var classType = asm.GetType("SharpExternal.Class1");                                    
            Console.WriteLine("[Console] Invoking SharpExternal.Class1.Main method...");
            var methodInfo = classType.GetMethod("Main", BindingFlags.Static | BindingFlags.Public);
            methodInfo.Invoke(null, new object[] { evt });

            Console.WriteLine("[Console] After changes: " + evt.ToString());
            Console.WriteLine();

            methodInfo = classType.GetMethod("ShowTestValue", BindingFlags.Static | BindingFlags.Public);
            methodInfo.Invoke(null, null);

            Console.ReadLine();
        }
    }
}

And a class library:

using System;

namespace SharpExternal
{
    public class Class1
    {
        public static void Main(ref SharpConsole.GameEvent evt)
        {
            Console.WriteLine("[DLL] " + evt.ToString());
            Console.WriteLine("[DLL] Cancelling an event");
            evt.SetCancelled(true);   
        }

        public static void ShowTestValue()
        {
            SharpConsole.API.Print(SharpConsole.Program.TestValue);
        }
    }
}

What is going on:

  1. The console app creates GameEvent class instance
  2. It injects the ExternalSharp.dll
  3. ExternalSharp.Class1.Main gets called passing previously created GameEvent instance reference to it.
  4. ExternalSharp changes GameEvent's Cancelled state and SharpConsole outputs an instance of a GameEvent that has been successfully modified from ExternalSharp
  5. ExternalSharp's ShowTestValue gets called so it outputs a Console's TestValue field value.

The thing is, I can compile SharpExternal (which uses SharpConsole project as a dependency so it can use its classes. I can also compile SharpConsole and use its DLL file as a dependency, the result is the same) once and move its DLL file on the Desktop so it can't access any files, be recompiled and etc., i.e. in a completely empty folder. BUT I can change Console's TestValue at any moment, even from Console.ReadLine in runtime, then recompile only the Console app and the SharpExternal will output new value when the ShowTestValue method is called. I can add more static properties, methods, etc. before and after TestValue, change the file as I want, but unchanged from the first time SharpExternal.dll file which is still located on the Desktop manages to find TestValue (and other static fields, methods, ...) every time and output the correct value.

I'd like to know how this whole thing works, how ExternalSharp finds the correct TestValue address every time. I suppose it's because of the static modifier, but I haven't found any information beyond the fact that it allows type members to refer to the type itself, and not just to its instance, which I already knew.





Kotlin's reflection: Simple variable extraction out of String

I've read about reflection in both Kotlin and Java documentation & getattr in Python examples but they all seem to lack my use case:

I have boolean variables like repetitionOfElementsInNewExerciseAllowed in a ViewModel class (Android programming) that I need to update from a different class like HomeFragment. My unsexy approach was the following function in ViewModel:

    fun updateBoolElement (boolElementToUpdate:String, valueToUpdateWith:Boolean){
        when (boolElementToUpdate){
            "repetitionOfElementsInNewExerciseAllowed" -> repetitionOfElementsInNewExerciseAllowed=valueToUpdateWith
        }
    }

Instead of this I'm striving for a recursive approach to extract the variable's name whose value I want to change out of the string boolElementToUpdate like this (pseudo code):

    fun updateBoolElement (boolElementToUpdate:String, valueToUpdateWith:Boolean){
        getAttributeReferenceByName(boolElementToUpdate) = valueToUpdateWith
    }

Is reflection or any other structure in Kotlin capable of doing such wizardry? Thanks for any hint!





jeudi 11 août 2022

How to specify the generic type of a collection?

I want to define a function which can convert a kind of Set to another, like convert HashSet to LinkedHashSet. Here is the function declaration. The sp is sharedpreferences.

public Set<String> decodeStringSet(String key, @Nullable Set<String> defaultValue, Class<? extends Set> cls){
    Set<String> result = sp.getStringSet(key, defaultValue);
    if(result == null){
        return defaultValue;
    }
    else {
        String[] array = result.toArray(new String[0]);
        Set<String> a;
        try {
            a = cls.newInstance();
        } catch (IllegalAccessException | InstantiationException var7) {
            return defaultValue;
        }

        a.addAll(Arrays.asList(array));
        return a;
    }
}

However, the compiler remind me that "Unchecked assignment: '? extends java.util.Set' to 'java.util.Set<java.lang.String>'" on "a = cls.newInstance();". I don't know how to change cls to cls<java.lang.String>.





Go lang strong typed name of a field

I have a go struct that I use to serialize to bson and store in mongodb.

When I make queries, set up indexes, etc very often I need to refer to the field name or the bson tag of it.

Is there a compile time validatable way to do that?

Say if I have the struct:

type Foo struct {
    Bar string `bson:"bar"`
}

then

   query = fmt.SPrintf("%s = 'aaa'", Foo.Bar.GetTag("bson"))

Note I am aware that I can do

   query = fmt.SPrintf("%s = 'aaa'", refect.TypeOf(Foo{}).GetField("Bar").GetTag("bson"))

but that is not what I am looking for. In this last variant if I rename the field Bar to Baz I am not going to get compile time error, because I referred to the name as a string literal.





mercredi 10 août 2022

Python - Define class with one method and one attribute

I'm new to Python and trying create a program that defines a class called person that has one method called hello, and one attribute called name, which represents the name of the person. The hello method should print the following string to the screen:

‘My name is name attribute and I am a name of class

1)Instantiate an object of the class, 2)Run the hello method of the instantiated object (e.g., John.hello()), 3) Use sys.argv

Here is my code:

import sys

class person():
    def __init__(self,_name):
        self.name=_name
        _name = sys.argv[1]
    def hello(self):
        print (f"My name is {sys.argv[1]} I am a {self.__class__.__name__}")

p1 = person()
p1.hello()

def main():
    p = person()
    print (type(p))

if __name__ == "__main__":
    main()

Example expected output:

My name is Obi-Wan and I am a person
<class '__main__.person'>

Actual output:

  File "classname.py", line 10, in <module>
    p1 = person()
TypeError: __init__() missing 1 required positional argument: '_name'

I don't know what I am doing wrong. Please help!





Getting value type from event found via reflection

I'm trying to get values that were sent as payload with an event that is triggered outside the scope of my assembly. I'm finding an event via reflection.

var eventInfo = adCallbackType.GetEvent(eventInfoName);

Then subscribe my method to this event.

var eventDelegate = Delegate.CreateDelegate(eventInfo.EventHandlerType, adToBindTo, methodInfo);
eventData.EventInfo.AddEventHandler(adCallbackType, eventData.Delegate);

This is the method I'm subscribing to that event

public void OnAdReceivedReward(string adUnitId, object reward, object adInfo)
{
   Debug.Log($"id: {adUnitId}");
   Debug.Log($"reward: {reward}"); //this comes corrupted, prints only the Label value
   Debug.Log($"info: {adInfo}");
}

I'm not providing the complete code here.

The problem is that one of the events has these type parameters

public static event Action<string, AdSdkBase.Reward, AdSdkBase.AdInfo> OnAdReceivedRewardEvent

where Reward is a struct, for example

public struct Reward
{
   public string Label;
   public int Amount;

   public override string ToString()
   {
      return $"Reward: {Label}, {Amount}";
   }
}

So, when Reward is passed as a struct, then it comes corrupted in the callback. If I'd change Reward to be a class instead, then it works as I expected, but I can't change it, since it comes from 3rd party SDK. I did not do much with this type of stuff before. Does it has something to do with data marshaling or am I missing something when I'm searching for method and event via reflection? (like binding attributes)





lundi 8 août 2022

Iterate over the field of structs and modify the value [duplicate]

I am new to golang, but here is my structure:

type CellMetricsEntry struct {
    DRBUEThpDl             interface{}
    DRBUEThpUl             interface{}
    QosFlowPdcpPduVolumeUl interface{}
    QosFlowPdcpPduVolumeDl interface{}
}

In the above structure there are more than 100 variables, but here I have taken only 4.

in main function I somehow want to iterate over the field and want to modify it, as per my need.

The field values can either be an int32 or float64

How can i iterate over this structure field and modify the value.

I want to achieve something like

var metric CellMetricsEntry

for (int i=0;i< no_of_elements;i++)//this is pseudo code
{
metric[i]=value//setting  each field of struct in for loop
//the above value I will get from some other application and this may be //either int32 or float64


}

After setting all the field , I will push it to Time series database like influxdb

writecellMetrics_db(metric)




Why spark-shell throws NoSuchMethodException while calling newInstance via reflection

spark-shell throws NoSuchMethodException if I define a class in REPL and then call newInstance via reflection.

Spark context available as 'sc' (master = yarn, app id = application_1656488084960_0162).
Spark session available as 'spark'.
Welcome to
      ____              __
     / __/__  ___ _____/ /__
    _\ \/ _ \/ _ `/ __/  '_/
   /___/ .__/\_,_/_/ /_/\_\   version 3.0.3
      /_/
         
Using Scala version 2.12.10 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_141)
Type in expressions to have them evaluated.
Type :help for more information.

scala> class Demo {
     |   def demo(s: String): Unit = println(s)
     | }
defined class Demo

scala> classOf[Demo].newInstance().demo("OK")
java.lang.InstantiationException: Demo
  at java.lang.Class.newInstance(Class.java:427)
  ... 47 elided
Caused by: java.lang.NoSuchMethodException: Demo.<init>()
  at java.lang.Class.getConstructor0(Class.java:3082)
  at java.lang.Class.newInstance(Class.java:412)
  ... 47 more

But the same code works fine in native scala REPL:

Welcome to Scala 2.12.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_131).
Type in expressions for evaluation. Or try :help.

scala> class Demo {
     |   def demo(s: String): Unit = println(s)
     | }
defined class Demo

scala> classOf[Demo].newInstance().demo("OK")
OK

What's the difference between spark-shell REPL and native scala REPL?

I guess the Demo class might be treated as inner class in spark-shell REPL.

But ... how to solve the problem?





C# Get internal, but not private or protected methods of a type [duplicate]

I am trying to get some statistics about our C# library and how many internal methods we have. I have tried using System.Reflection for it, but I am struggling with filtering just internal methods and not private or protected ones. Here is my code:

private bool IsTypePublic(Type t)
{
    return
        t.IsVisible
        && t.IsPublic
        && !t.IsNotPublic
        && !t.IsNested
        && !t.IsNestedPublic
        && !t.IsNestedFamily
        && !t.IsNestedPrivate
        && !t.IsNestedAssembly
        && !t.IsNestedFamORAssem
        && !t.IsNestedFamANDAssem;
}

private bool IsTypeInternal(Type t)
{
    return
        !t.IsVisible
        && !t.IsPublic
        && t.IsNotPublic
        && !t.IsNested
        && !t.IsNestedPublic
        && !t.IsNestedFamily
        && !t.IsNestedPrivate
        && !t.IsNestedAssembly
        && !t.IsNestedFamORAssem
        && !t.IsNestedFamANDAssem;
}

private Dictionary<string, int> GetMethodCounts()
{
    var assembly = typeof(MyType).Assembly;
    var types = assembly.GetTypes();

    var result = new Dictionary<string, int>();
    var publicTypes = new HashSet<Type>();
    var internalTypes = new HashSet<Type>();

    foreach (var type in types)
    {
        if (IsTypePublic(type))
        {
            publicTypes.Add(type);
        }
        else if (IsTypeInternal(type))
        {
            internalTypes.Add(type);
        }
    }

    result.Add("PublicType.PublicMethod", 
        // Select all non-inherited public methods, both static and instance-bound
        publicTypes.SelectMany(x => x.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly))
            .Count(x => !x.IsSpecialName));

    result.Add("PublicType.InternalMethod",
        // This should select all non-inherited internal methods, both static and instance-bound
        // But it selects also private and protected methods, which I am not interested in
        publicTypes.SelectMany(x => x.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly))
            .Count(x => !x.IsSpecialName));

    // ... continue with constructors, properties, and the same for the internalTypes
}

Is there any way how to limit the scope to internal only (or possibly protected internal)?





vendredi 5 août 2022

How to load manual objects created via reflection into spring context

There are two application. Main Application and Utility Application where utility Application is packaged as jar in Main application. Both are spring boot application. In utility application I create an object of a class A which is present in Main Application using reflection API. Class A has one Autowired instance variable defined in it. Issue is when Utility Application tried to run some method one the same class A object, then that autowired variable results in null. I guess, since I am creating the object manually that is why it is not managed by Spring. Now my question is how can provide this object to spring context so that any Autowiring happening inside the class A actually gets autowired. Below is the code samples

under Main Application 
package m.main.application.A;
class A implements Action{    //Action interface coming from utility application

@Autowired
private Calculator calculator

@override
public void execute(){
    calculator.add(5+2);  //Here calculator is null. Autowire is not working
}
}
Utility Application packaged as Jar in Main Application

Class Util{
   
    public createObjectAndRun(){
      
      Class<?> class = Class.forName("com.main.application.A");
      Action newObject= (Action) class.getConstructor().newInstance();
      
      //executing execute
      newObjects.execute();  //This fails as calculator is not autowired

      
    }
}

I want to know if there is a way we can make calculator gets autowired properly.





How to dynamically query IQueryable array by each property using reflection?

I have search method with gets as parameter some DTO and make where filtering dynamically by DTO properties. The problem I get when using reflection is that I should explicitly cast to a property type that I am using. Is there a way to make it dynamic too so that the method that that make filtering can work without knowing type of a property. I am using Dynamic Ling Library.

CODE:

 public async Task<ServiceResponceWithData<List<SearchResponseDTO>>> SearchAsync(SearchDTO model)
    {
        var users = from user in _userManeger.Users
                    join ur in _context.UserRoles
                           on user.Id equals ur.UserId
                    select new SearchResponseDTO
                    {
                        UserName = user.UserName,
                        Email = user.Email,
                        PhoneNumber = user.PhoneNumber,
                        FirstName = user.FirstName,
                        LastName = user.LastName,
                        Roles = _roleManager.Roles
                                .Where(c => c.Id == ur.RoleId)
                                .Select(c => c.Name)
                                .ToList()
                    };

        var startResult = users;

        var props = typeof(SearchDTO).GetProperties();
        foreach (var prop in props)
        {
            if(prop.Name != "Role")
            {
                users = FilterWithWhereByStringTypeProperty(users, prop, model);
            }
            else
            {
                if (model.Role != null)
                {
                    var results = users.Where(c => c.Roles.Any(r => r == model.Role));
                    users = results.Any() ? results : users;
                }
            }
        }

        var endResultList =  startResult == users ? new List<SearchResponseDTO>() :await  users.ToListAsync();

        return new ServiceResponceWithData<List<SearchResponseDTO>>() { Data = endResultList, Success = true };
    }

    private IQueryable<SearchResponseDTO> FilterWithWhereByStringTypeProperty(IQueryable<SearchResponseDTO> collection,
                                                PropertyInfo property,SearchDTO model )
    {
        var propertyName = property.Name;
        var modelPropVal = property.GetValue(model);

        if (modelPropVal == null) return collection;

        string val = (string)modelPropVal;
        string condition = String.Format("{0} == \"{1}\"", propertyName, val);
        var fillteredColl = collection.Where(condition);
        return fillteredColl.Any() ? fillteredColl : collection;
    }
}




jeudi 4 août 2022

Instantiate a package variable using just the name

I am trying to add some simple validation code for some exported types in a package full of constants. I want to walk the package, figure out the exported consts (which are just strings) and verify their format.

Think of it like I have a flags package that exports consts FlagDoAThing = "do-a-thing". I want to walk that package and check out what those values are.


As an example I've got two files:

// main.go
func main() {
    cfg := &packages.Config{
        Mode: packages.NeedTypes,
    }
    pkgs, _ := packages.Load(cfg, "package-inspector/other")
    pkg := pkgs[0]

    scope := pkg.Types.Scope()
    for _, name := range scope.Names() {
        fmt.Println(name)
        obj := scope.Lookup(name)
        fmt.Println(obj)
        fmt.Println("\t", obj.Id(), obj.Type())
    }
}

Then in my other package I have

package other

const (
    ExportedOne = "exported_one"
    ExportedTwo = "exported_two"

    privateOne = "private_one"
)

When running locally (couldn't get the playground to like me) I am seeing

go run main.go
ExportedOne
const package-inspector/other.ExportedOne untyped string
         ExportedOne untyped string
ExportedTwo
const package-inspector/other.ExportedTwo untyped string
         ExportedTwo untyped string

What I'm trying to do is get a handle on the value of ExportedOne.





mercredi 3 août 2022

How to read service parameters in DI container with ASP.NET Core 6

For example I have configured a service

Builder.Services.AddRazorPages(Sub(options As RazorPagesOptions)
                 options.RootDirectory = "/"
                 options.Conventions.AuthorizeAreaFolder("Identity", "/User")
           End Sub)

Than I want to read these options RootDirectory and Conventions.

I try to read, but failed. I can receive only list of parameters, for example

Microsoft.AspNetCore.Mvc.Razor.RazorViewEngineOptions
0. ViewLocationExpanders : Of IList`1
1. ViewLocationFormats : Of IList`1
2. AreaViewLocationFormats : Of IList`1
3. PageViewLocationFormats : Of IList`1
4. AreaPageViewLocationFormats : Of IList`1

Microsoft.AspNetCore.Mvc.RazorPages.RazorPagesOptions
0. Conventions : Of PageConventionCollection
1. RootDirectory : Of String

But for reading value by reflection (GetValue) I need instance of parameters, I don't understand how receive instance of service parameters.

Reading parameters list is simple, for example

Dim OptionTypeList = Builder.Services.Where(Function(X) X.ServiceType.IsGenericType).Select(Function(X) X.ServiceType.GetGenericArguments()(0)).Distinct.ToList
OptionTypeList.ToList.ForEach(Sub(OneOptionType)
     Debug.Print($"{OneOptionType.FullName}")

     For J As Integer = 0 To OneOptionType.GetProperties.Count - 1
         Dim Prop As Reflection.PropertyInfo = DirectCast(OneOptionType, System.Reflection.TypeInfo).DeclaredProperties(J)

         If Prop IsNot Nothing Then
             Debug.Print($"{J}. {Prop.Name} : Of {Prop.PropertyType.Name}")
                                   '(0): {Microsoft.AspNetCore.Mvc.ApplicationModels.PageConventionCollection Conventions}
                                   '(1): {System.String RootDirectory}

But how to receive value of parameters? For example value of Conventions - where is the instance? Or reading parameters are possible without reflection GetValue?





Unable to cast reflection called method type IEnumerable

I have an error when I call a method in reflection, I can't cast the result to its base Type (IEnumerable<Tuple<SortingOrder, Expression>>) which seems strange.

I don't have this problem when I cast another method in Expression. I guess it's the IEnumerable or the Tuple that is the problem. Does anyone have any idea how to do this?

Error when I call the first method below:

public static IEnumerable<Tuple<SortingOrder, Expression>> ConvertOrderByToTupleExpression(Type entityType, string orderBy)
{
    return (IEnumerable<Tuple<SortingOrder, Expression>>)typeof(RepositoryReflectionHelper)
                .GetMethods()
                .First(x => x.Name == nameof(RepositoryReflectionHelper.ConvertOrderByToTupleExpression) && x.IsGenericMethod && x.GetParameters().Count() == 1)
                .MakeGenericMethod(new Type[] { entityType })
                .Invoke(null, new object[] { orderBy });
}

public static IEnumerable<Tuple<SortingOrder, Expression<Func<TEntity, object>>>> ConvertOrderByToTupleExpression<TEntity>(string orderBy)
{
    List<Tuple<SortingOrder, Expression<Func<TEntity, object>>>> orderByCriteriaTuple = new List<Tuple<SortingOrder, Expression<Func<TEntity, object>>>>();

    return orderByCriteriaTuple;
}

UPDATE:

Same Errors for "reverse" actions in the below code:

IEnumerable<Tuple<SortingOrder, Expression>> orderByExpression = RepositoryReflectionHelper.ConvertOrderByToTupleExpression(entityType, orderBy);

var calledFunction = GetManyPaging(orderByExpression);

public IEnumerable<TEntity> GetManyPaging(IEnumerable<System.Tuple<SortingOrder, Expression<Func<TEntity, object>>>> orderByCriteriaTuple)
{
    // Do something not significant
}



Thank for your times





Building a function from an arbitrary callable with a matching reflection in PHP

Lets say I have an arbitrary function taking some parameters and returning say an array (the return and what the method does doesn't matter)

$callable = fn (MyClass $myClass, string $id, bool $rec) => []

I would like to build a new function from this closure so that this new function takes the exact same parameters in a way that the Reflection of this function will return the same parameters as the original

What I mean:

$clonedCallable = someMagic($callable);
assertEquals(// Equal but not the same ref obviously
  (new ReflectionFunction($callable))->getParameters(),
  (new ReflectionFunction($clonedCallable))->getParameters()
);

Is there a way in PHP to build this kind of method without using some hackjob eval (which is the only idea I have right now) as Reflection doesn't have some kind of magic setParameters()?





mardi 2 août 2022

Invoking non static method from type with constructor with dependency injection parameters

I need to invoke a member function from a non-static type which has a contructor which receives parameters via dependency injection. I have to do this because I only receive the name of the object as a string via API call, I have several classes which have the same method but different names and I use the name of the object to invoke the correct method.

Normally I would call it like this:

var type = assembly.GetType($"{projectName}.{typeName}");

if (type == null)
{
    throw new ArgumentException($"{nameof(typeName)} not found");
}

var instance = new WhateverType(some arguments...)

await (Task)type.InvokeMember(methodName, BindingFlags.InvokeMethod |
    BindingFlags.Public | BindingFlags.Instance, null, null,
    args.Select(a => a.Value).ToArray(), null, instance, args.Select(a => a.Key).ToArray());

Where args is a dictionary which has a pair with parameter name and value.

The thing is, I don't think I want/can pass the instance of the object because those some arguments... are interfaces which are instantiated at startup and have themselves interface parameters, like for example:

builder.RegisterType<Service>()
    .As<IService>().InstancePerLifetimeScope();

Where builder is Autofac.ContainerBuilder.

And are used via dependency injection pattern, i.e.:

WhateverType(Iservice service)
{
    _service = service; 
} 

Where _service is a private member IService service and itself has interface parameters which themselves have interface parameters and so forth.

How could I do this? How do you instantiate a class that is normally instantiated by dependency injection at startup.





lundi 1 août 2022

How can I get a separate reference to each version/artifact of the same published java package, in one JVM (stack = sbt + scala)?

I am considering building a small tool for running different releases of the same project.

So far, i can import the project, and can even import both versions without compilation failures.

name := "diffing-tool"

val sparkVersion = "3.1.2"
resolvers += Resolver.publishMavenLocal
resolvers += Resolver.defaultLocal
libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % sparkVersion,
  "org.apache.spark" %% "spark-sql" % sparkVersion,
  "com.foo" %% "bar" % "1.0",
  "com.foo" %% "bar" % "1.1"

)

My code can compile and run the following code


object Hello extends App {
  println("Hello world")
  val fromJar1 = com.foo.bar.Run.main()
  val fromJar2 = com.foo.bar.Run.main()

  def diff(fromJar1: Any, fromJar2: Any) = {
    println("Hello world")
  }

  diff(fromJar1, fromJar2)
}

However, I do not know a good way to rename the packages/artifacts such that the code can refer to each version of the code separately.

Ideas of what this would look like include

  1. the use of shading in the build.sbt file (which is usually used for dependencies of dependencies, and I have not yet figured out what to do in my current use case -- also, i would like to avoid sbt assembly if possible which is coupled with shading if i am not mistaken). ill need detailed instructions on how to set this up.
  2. Another approach is, at runtime, to use reflection, the ClassLoader, or perhaps something from the sbt.librarymanagement package, to get a separate reference to each artifact. Will need detailed instructions on how to set this up.
  3. Other ideas are very welcome.




How can I check that incoming parameter is static

I have class, its constructor takes SemaphoreSlim and it must be static(if else I should throw an exception). How can I check that incoming "semaphore" parameter is static? I have tried to look through its Type, but there's no IsStatic field. The code is below

protected CacheService(SemaphoreSlim semaphore, IMemoryCache memoryCache)
{
    _semaphore = semaphore;
    _memoryCache = memoryCache;
}