mercredi 30 juin 2021

C# - Create Complete Dynamic Expression Trees from PropertyInfo [duplicate]

I have already been through the following links, but none of them seems to answer my question-

  1. Create Expression from PropertyInfo
  2. Dynamically Create Expression from PropertyInfo
  3. Creating dynamically Expression<Func<T,Y>>

Basically I asked this question earlier today and comment from abdusco help me solve it in the following manner-

protected override void OnModelCreating(ModelBuilder builder)
{
    //Remove pluralizing table name convention (Install package - Microsoft.EntityFrameworkCore.Relational)
    foreach (var entity in builder.Model.GetEntityTypes())
    {
        entity.SetTableName(entity.DisplayName());
    }

    // Following properties belongs to User.cs and are non-public (internal).
    builder.Entity<User>().Property(x => x.FirstName);
    builder.Entity<User>().Property(x => x.MiddleName);
    builder.Entity<User>().Property(x => x.LastName);
    builder.Entity<User>().Property(x => x.EmailId);
    builder.Entity<User>().Property(x => x.DateOfBirth);

    base.OnModelCreating(builder);
}

But I believe above-mentioned approach is going to be very cumbersome, as there will be several classes similar to User.cs in the namespace: Components.User.Persistance.Poco. I am now trying to achieve the above-mentioned solution as follows-

private void AddNonPublicPropertiesToTheModel()
{
    // I have hard-coded the namespace for now, but it will be supplied as a parameter.
    var types = GetAllMembersOfNamespaceOfExecutingAssembly("Components.User.Persistance.Poco");
    foreach (var type in types)
    {
        foreach (var propertyInfo in GetNonPublicInstancePropertyInfo(type))
        {
            var parameter = Expression.Parameter(type);
            var property = Expression.Property(parameter, propertyInfo);
            var conversion = Expression.Convert(property, typeof(object));
            //var lambda = Expression.Lambda<Func<, object>>
        }
    }
}

private static PropertyInfo[] GetNonPublicInstancePropertyInfo(Type type) =>
    type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);

private static Type[] GetAllMembersOfNamespaceOfExecutingAssembly(string namespaceName) =>
    GetAllMembersOfNamespace(namespaceName, Assembly.GetExecutingAssembly());

private static Type[] GetAllMembersOfNamespace(string namespaceName, Assembly assembly) =>
    assembly
        .GetTypes()
        .Where(type => string.Equals(type.Namespace, namespaceName, StringComparison.Ordinal))
        .ToArray();

Question- How do I generate - builder.Entity<User>().Property(x => x.FirstName);, using all this reflection? Or if you have a better approach altogether, please feel free to share.
NOTE:- Please go through the following question to get a broader view of what I am trying to achieve.





Parsing scala 3 code from a String into Scala 3 AST at runtime

My goal is to get Scala 3 code as a String and to parse it into Abstract Syntax Tree for Scala 3 at runtime. In the process if the code has compilation errors, I should get that as part of some exception. The larger goal is to end up with Expr[T] if the scala code is valid and execute it by splicing in the right bits(I have this part covered).

This was doable in Scala 2.* using scala-reflect here.

val source =
  """
    |object HelloWorld {
    |  def main(args: Array[String]): Unit = {
    |    println("Hello, world!")
    |  }
    |}
    |
    |HelloWorld.main(Array())
    |""".stripMargin
val tree = toolbox.parse(source)
val binary = toolbox.compile(tree)
binary()

But as far as I can surmise, in Scala 3, scala-reflect will not be ported. How could I achieve the same in Scala 3?

Some relevant links here and here





mardi 29 juin 2021

Call MethodByName in array of struct: panic: reflect: call of reflect.Value.Call on zero Value

I am trying to use reflection to make a dynamic function call of each element of an array:

var EsPersonList []EsEntry

func (this *EsEntry) FullName() string {
    return this.Wholename
}

func createStr(d interface{}) {
    items := reflect.ValueOf(d)

    if items.Kind() == reflect.Slice {
        for i := 0; i < items.Len(); i++ {
            item := items.Index(i)
            if item.Kind() == reflect.Struct {
                v := reflect.ValueOf(&item)
                return_values := v.MethodByName("FullName").Call([]reflect.Value{})
                fmt.Println(return_values)
            }
        }
    }
}

createStr(EsPersonList)

I get is a panic that looks like this: panic: reflect: call of reflect.Value.Call on zero Value

https://play.golang.org/p/vK2hUfVcMwr

How can I fix this?





Choosing which Enum to use dynamically in Java

I need to dynamically choose an Enum with some properties based on a parameter that will provide the suffix of the Enum name to use. I tried this but the "getCodigoAsString()" method doesn't work.

An Enum sample:

import lombok.AllArgsConstructor;
import lombok.Getter;

@AllArgsConstructor @Getter
public enum Chaves_35 {
    MODELO_DISPOSITIVO(1234,"TEXT","IN","Modelo Dispositivo"),
    DISPOSITIVO_SUPORTA_MULTI_TAREFA(4423,"TEXT","IN","Dispositivo Suporta Multi Tarefa"),
    NOME_DISPOSITIVO(7845,"TEXT","IN","Nome Dispositivo"),
    IDIOMA_DISPOSITIVO(3288,"TEXT","IN","Idioma Dispositivo"),
    ;

    private int codigo;
    private String tipo;
    private String fluxo;
    private String descricao;
  
    public String getCodigoAsString() {
        return String.valueOf(codigo);
    }
    
}

The Class that make the choice:

 public class ChavesCanal { 

    public static Enum<?>[] BuscaChavesCanal(int idCanal) {
        Enum<?>[] resp = null;

        switch (idCanal) {
            case 6:
                resp = Chaves_6.values();
                break;
            case 8:
                resp = Chaves_8.values();
                break;
            case 10:
                resp = Chaves_10.values();
                break;
            case 17:
                resp = Chaves_17.values();
                break;
            case 21:
                resp = Chaves_21.values();
                break;
            case 22:
                resp = Chaves_22.values();
                break;
            case 27:
                resp = Chaves_27.values();
                break;
            case 28:
                resp = Chaves_28.values();
                break;
            case 35:
                resp = Chaves_35.values();
                break;
            case 37:
                resp = Chaves_37.values();
                break;
            default:
                break;
        }

        return resp;
    }
}

This is the method that I'm trying to use the "ChavesCanal()" Class:

public static boolean VerificaChavesCanais_JSON(int codigoCanal) {
        if(codigoCanal <= 0) return false;
        
        try {           
            for (Enum<?> chaveId : ChavesCanal.BuscaChavesCanal(codigoCanal)) {
                if(!payloadJSON.has(chaveId.getCodigoAsString())) {
                    System.out.println("  .... chave '" + chaveId.getCodigoAsString() + "' não encontrada!!!");
                }
            }

            return true;

        } catch (Exception e) {
            System.out.println("ERRO em VerificaChavesCanais_JSON(): " + e.getMessage());
            return false;
        }
    }

Thanks folks!!!





C# How to clear handlers from custom events

I have a UserControl, named FormDesignerControl. FormDesignerControl has a number of public events on it, declared thus:

public event EventHandler LeftMouseClick;
public event EventHandler LeftMouseDownInControl;
public event EventHandler LeftMouseMoveInControl;
public event EventHandler LeftMouseUpInControl;

public event EventHandler LeftMouseDownInThumb;
public event EventHandler LeftMouseMoveInThumb;
public event EventHandler LeftMouseUpInThumb;

public event EventHandler RightMouseClick;
public event EventHandler RightMouseDownInControl;
public event EventHandler RightMouseMoveInControl;
public event EventHandler RightMouseUpInControl;

At one point, I pass an instance of FormDesignerControl from one place in my program to another and want to all the handlers. I do not have access to the original events. Basically, I need to clear the current settings of the event handlers. Ideally what I'd like to do is this:

FormDesignerControl oFDC = new FormDesignerControl();

// some code occurs manipulating oFDC and setting the events on it, and then at some point...

oFDC.LeftMouseClick.Clear(); // but this isn't facilitated
oFDC.LeftMouseClick += myNewEventCode;

It seems the only way to do this is to have access to the original events so as to be able to use the -= operator.

Is there a way to clear an arbitrary event from an arbitrary object, perhaps using System.Reflection even if I have to encapsulate it in a method? Something like this:

void ClearEvent(object obj, string eventName)




Parsing strings to arbitrary enums in Kotlin Multiplatform

I was wondering whether it's possible to implement a function such as the following in Kotlin Multiplatform:

inline fun <reified T : Enum<T>> parseToEnum(value: String): T {
    // ?
}

Basically, a function that takes the type of an Enum and a string and then returns the enum value of enum T that matches the passed string (value).

I know that it is possible in Java (and therefore in Kotlin/JVM) but I fear that there might not be a way to do this in common multiplatform code, because there's very little reflection data retained at runtime.

If there's a way to do this (or something similar in functionality), please let me know.

Using Kotlin 1.5.20 (or generally the newest version, I can update if necessary)





Use Reflection to Find Interface

I'm not sure if it's the angle brackets that are causing me problems, but I'm having trouble coming up with an answer within the Stack Overflow answers. If there's one already out there, I'd welcome you to point me in the right direction.

To summarize, I have an Interface and I can't get reflection to find it. Let's set the stage:

Interfaces

interface ICrew
{
    string Name { get; set; }
}

interface IDataService<T>
{
    IEnumerable<T> GetItems();
}

Classes

class Crew : ICrew
{
    public string Name { get; set; }
}

class CrewRepository : IDataService<ICrew>
{
    DbContext _context { get; }

    public CrewRepository(DbContext context)
    {
        _context = context;
    }


    public IEnumerable<ICrew> GetItems()
    {
        return _context.Crews;
    }
}

class DbContext
{
    public DbContext()
    {
        Crews = new List<Crew>();
    }
        
    public List<Crew> Crews;
}

Code

class Program
{
    private static DbContext _context;

    static void Main(string[] args)
    {
        _context = new DbContext();

        //I want to find CrewRepository (which is type of IDataService<ICrew>)
        var dataService = Get(typeof(ICrew));
    }

    private static object Get(Type T)
    {
        var types = typeof(CrewRepository).Assembly.GetTypes();

        var test = types.Where(t => t.IsAssignableFrom(T)); //Finds ICrew

        var test2 = types.Where(t => t.GetInterfaces().Contains(T)); //Finds Crew

        var test3 = types.Where(t => t.GetInterfaces().Contains(typeof(IDataService<>))); //Finds nothing

        var test4 = types.Where(t => t.IsAssignableFrom(typeof(IDataService<>))); //Finds interface IDataService

        var test5 = types.Where(t => typeof(IDataService<>).IsAssignableFrom(t)); //Finds interface IDataService

        var instance = types
            .Where(t => t.IsAssignableFrom(T))
            .FirstOrDefault();

        if (instance != null)
        {
            return Activator.CreateInstance(instance, _context);
        }

        return default;
    }

}

I can't figure out how to query the Assembly Types correctly to get IDataService<T>. My Get method doesn't know what type it's going to be asked for until runtime, and generics inside of angle brackets are only able to be used if I know the type at compile time. Can anyone help me figure out what I should be doing here to get Get to return the correct class Repository that I'm hoping for by using reflection?





Assembly remains after unloading appdomain

I have program, which creates AppDomain, loads assembly prelude within it and then unloads AppDomain. At the end program lists assemblies from default appdomain. It's simplified version of program. In next versions prelude.dll will be changed in runtime and continiously executed/unloaded with appdomain.

namespace appdomaintest
{

    class Program
    {
        static void log_assemblies(AppDomain domain)
        {
            foreach (var item in domain.GetAssemblies())
            {
                Console.WriteLine($"{domain.FriendlyName} : {item.FullName}");
            }
        }
        static void Main(string[] args)
        {
            {
                var prelude_domain = AppDomain.CreateDomain("PreludeDomain#1", null, null);
                var asm = prelude_domain.Load(new System.Reflection.AssemblyName("prelude"));
                var myint = prelude_domain.CreateInstanceAndUnwrap("prelude", "prelude.MyInt");
                myint.GetType().GetMethod("show").Invoke(myint, new object[0]);
                AppDomain.Unload(prelude_domain);
                Console.WriteLine("AppDomain was unloaded");
            }
            log_assemblies(AppDomain.CurrentDomain);
        }
    }
}  

Here is content of prelude.dll

public class MyInt : MarshalByRefObject
{
    public MyInt()
    {
        Console.WriteLine($"MyInt was constructed in {AppDomain.CurrentDomain.FriendlyName}");
    }
    public void show()
    {
        Console.WriteLine($"show in {AppDomain.CurrentDomain.FriendlyName}");
    }
}

Here is output of program:

MyInt was constructed in PreludeDomain#1
show in PreludeDomain#1
AppDomain was unloaded
appdomaintest.exe : mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
appdomaintest.exe : appdomaintest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
appdomaintest.exe : prelude, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

Unfortunately I discovered that my default appdomain contains prelude.dll assembly. As I understand it remains until end of execution of my program. Is there any way to prevent loading it to default appdomain? In future versions prelude.dll will be repeatedly loaded/unloaded (its metadata also will be modified). That's why that behaviour is not suitable for my purposes.

It seems like for me that creation proxy object may lead to loading metadata to default domain. But how can I unload them?





lundi 28 juin 2021

How can I implement code that parameterize or even instantiate what an actual C# Type variable actually refers to? [duplicate]

Let's just say that some other code in some other file already does the following:

SomeVehicleType = typeof(Car);

which is located in some other file.

Now, using the Type SomeVehicleType in the current code file that I'm implementing, I have the following code:

public int SomeBlahMethod(Type SomeVehicleType)
{
    dynamic actualSomeVehicleTypeInstance = Activator.CreateInstance(SomeVehicleType);
    List<actualSomeVehicleTypeInstance.GetType()>  blahVehicleList = new  List<actualSomeVehicleTypeInstance.GetType()>();

    // Or even the following line of code

    List<typeof(actualSomeVehicleTypeInstance)>  blahVehicleListSecond = new List<typeof(actualSomeVehicleTypeInstance)>();         
}

Both the aforementioned lines throw a bunch of syntax errors

Basically, how can I implement code that parameterize or even instantiate what an actual C# Type variable actually refers to?





How can I solve hidden method using java reflection.?

This is the code to invoke hidden method "getUserInfo" using java reflection, but it's not working. Can I use double reflection to call this method.? and if so. How can I apply it to the code?

Object getUserInfoMethods=null;
    Method method = null;
    try {
        method = getUserInfoMethods.getClass().getMethod("getUserInfo", null);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
            try {
                Object users = method.invoke(getUserInfoMethods, null);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
        this.mHelper = new AppRestrictionsHelper(getContext(), this.mUser);
        this.mPackageManager = getActivity().getPackageManager();
        this.mIPm = Stub.asInterface(ServiceManager.getService("package"));
        this.mUserManager = (UserManager) getActivity().getSystemService(Context.USER_SERVICE);
        this.mRestrictedProfile =
        this.mUserManager.getUserInfo(this.mUser.getIdentifier()).isRestricted();
        try {
    this.mSysPackageInfo = this.mPackageManager.getPackageInfo("android",
            PackageManager.GET_SIGNATURES);
        } catch (NameNotFoundException e) {
    }
}




how to add parameters Func<> [duplicate]

I am trying to create a class that represents a function how can such a thing be achieved ??

i try to use this

public class Function : Value
{
    Func<Value, Value> Fun;

    public Function(Func<Value, Value> fun)
    {
        Fun = fun;
    }

    public override Value Execute(IEnumerable<Value> args)
    {
        if(args.Count() == 1)
            Fun(args.First());
        return Number.Empty;
    }
}

but i realy need in the constructor some think like this

Func<...Args> Fun;

public Function(Func<...Args> fun)
{
    Fun = fun;
}




Modify collection items using reflection?

I'd like to use reflection to find a collection by name (MyAssembly.Constants.MyCollection), check its items (List<string>), and add an item if it doesn't already exist. So far I'm able to find the collection and see its items, but need help adding the missing value to the real collection. Here's what I have so far:

var assembly = Assembly.Load("MyAssembly");
var constants = assembly.GetType("MyAssembly.Constants");
var myCollection = constants.GetField("MyCollection").GetValue(null) as List<string>;

if (!myCollection.Contains("some_value"))
{
     //Add the missing item to MyAssembly.Constants.MyCollection
}




Find a type to its module and name in Golang

in Golang, I am wondering if there it is a way to find a type by its module and name? For example,

// we got a package "playground/types_demo"
package types_demo

type DemoStruct struct {} // <-- it can be found like "playground/type_demo.DemoStruct"
func DemoFunction() {}.   // <-- similarly "playground/type_demo.DemoFunction"

I am working on a project. it will be cool if it can be implemented in a "low code" way. Then, the framework user can define what struct or function will be used.





ML.NET Merge IDataViews in a genric way

I am creating a CLI tool for ML.NET and I need to make a merge function, to merge two datasets of the same type. But it needs to be as generic as possible because the tool contains different dataset types.

I managed to make a method that converts a IDataview to a generic IEnumerable with a given dataset type:

private IEnumerable<object> GetDataEnumerable(MLContext mlContext, IDataView dataView, Type dataViewType) {
        var createEnumerableMethod = typeof(DataOperationsCatalog).GetMethod(nameof(MLContext.Data.CreateEnumerable));
        var generic = createEnumerableMethod.MakeGenericMethod(dataViewType);
        return (IEnumerable<object>)generic.Invoke(mlContext.Data, new object[] { dataView, false, null, null });
    }




Error creating a page (XAML) at runtime from an assembly in WinUi (desktop)

I have two projects for WinUI 3 (Desktop). One project is a desktop app and the other project is a class library (for desktop app). In the library I would like to define a page in XAML and load it into the desktop app at runtime (plug-in concept). The library is called 'MyHome.dll'. A page is defined there in XAML. The class for the page is called 'MyHome'.

The code for loading the assembly:

var dir = System.AppDomain.CurrentDomain.BaseDirectory;
Assembly MyHomeAssembly = Assembly.LoadFile (dir + "/MyHome.dll");
var page = (Page) Assembly.CreateInstance ("MyHome.MyHome")

The assembly is loaded. With the debugger I can see that the class 'MyHome' is included. A XAML parsing error is generated. My question: How do I load a Page (XAML) and the code C #) from a class at runtime.





dimanche 27 juin 2021

How can I write an Existential version of a Universally quantified function?

I've got a Dependent Type problem I'm trying to solve, and I've shrunk it down to the following caricature, of removing an index from a sized vector:

TL;DR Given rmIx, how can I write someRmIx?

rmIx     :: forall ix n a. Vector (n+1) a -> Vector n a
someRmIx :: forall ix   a. SomeVector   a -> SomeVector a

In the someRmIx version, I need to get a witness of the constraints in the rmIx function, and, if I can't meet those constraints (eg you can't remove from Vector 0 a), then return the SomeVector unchanged.

module SomeVector where

import qualified Data.Vector.Sized as V
import Data.Vector.Sized
import GHC.TypeNats
import Data.Proxy
import Type.Reflection
import Data.Type.Equality
import Unsafe.Coerce (unsafeCoerce)
import Data.Data (eqT)

data SomeVector a = forall n. KnownNat n => SomeVector (Vector n a)

-- | Remove an index from an existentially sized 'Vector'.
someRmIx :: forall (ix :: Nat) a m. KnownNat ix => SomeVector a -> SomeVector a
someRmIx (SomeVector (v :: Vector n a)) =

  --------------------------------------------------
  --------------------------------------------------
  --------------------------------------------------
  -- WHAT DO I DO HERE???
  --------------------------------------------------
  --------------------------------------------------
  --------------------------------------------------
  case  ???????  of
    Nothing -> SomeVector v
    Just Refl -> SomeVector $ rmIx @ix v


-- | Remove an index of a 'Vector'.
rmIx :: forall (ix :: Nat) n a (m :: Nat).
  (ix <= n,  -- in my actual code I clean this up with GHC.TypeLits.Normalise
  KnownNat ix,
  (ix + m) ~ n,
  ((n - ix) + 1) ~ (1 + m),
  (n + 1) ~ (ix + (1 + m))
  )
  => Vector (n+1) a -> Vector n a
rmIx v = l  V.++ r
  where (l :: Vector ix a, r' :: Vector (n-ix+1) a) = V.splitAt' (Proxy @ix) v
        (r :: Vector m a) = V.drop' (Proxy @1) r'


----------
-- * Tests

myV :: Vector 5 Int
myV = let Just v = V.fromList [1,2,3,4,5]
      in v

test1 :: Vector 4 Int
test1 = rmIx @2 myV

test2 :: SomeVector Int
test2 = someRmIx @2 $ SomeVector myV

The necessary fanfare to compile the above:

{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}




Raytracing reflection incorrect

Hello I build a raytracer in java and everything works fine but if i set 3 spheres on the same z axis the reflection doesnt work and if I change the z axis from the spheres it will work fine. In the following you can see the picture. There you can see the one sphere does the reflection correctly if it is not on the same z axis.

[Raytracer] [1]: https://i.stack.imgur.com/MSeCp.png

In the following is my code for calculate the Intersection.

private float raySphereIntersect(float[] rayE, float[] rayV, RTFile scene) {
    float t = Float.MAX_VALUE;
    float t1, t2;
    I_Sphere sphere = (I_Sphere) scene;
    
    float rayEx = rayE[0];
    float rayEy = rayE[1];
    float rayEz = rayE[2];
    
    float rayVx = rayV[0];
    float rayVy = rayV[1];
    float rayVz = rayV[2];


    // ray intersection uses quadratic equation
    float a, b, c, d;
    

    // me = vector from sphere center to eye point
    float mex, mey, mez;

    mex = rayEx - sphere.center[0];
    mey = rayEy - sphere.center[1];
    mez = rayEz - sphere.center[2];

    
    a = rayVx * rayVx + rayVy * rayVy + rayVz * rayVz;
    
    b = 2.0f * (rayVx * mex + rayVy * mey + rayVz * mez);
    
    c = mex * mex + mey * mey + mez * mez - sphere.radius * sphere.radius;

    // -> d = Diskriminante:

    // positive discriminant determines intersection
    
    d = (float) (b * b - 4 * a * c);
    // no intersection point? => next object
    

    
    if (d > 0) {
        // from here: intersection takes place!

    // calculate first intersection point with sphere along the ray
        t1 = (float) ((-b - Math.sqrt(d)) / (2 * a));
        t2 = (float) ((-b + Math.sqrt(d)) / (2 * a));
        
            

            if(t2>t1&&t1>0) {
                
                
                t=t1;
            }
            
            
            if(t2>0&&t1<0) {
                
                t=t2;
                
            }else {
                
                t=t1;
            }
        
    }

    return t;
}

and the in the other method i do:

    if (scene instanceof I_Sphere) {
            t = raySphereIntersect(rayE, rayV, scene);
        } 

        
        if(t >= minT)
            continue;
        
        minT = t;

I cant understand why the reflection works fine and calculated everything right and only if its the same z axis it doesnt work. I will be really happy if somebody can help me :)





vendredi 25 juin 2021

How to get Method-Meta information within a Method Attribute?

How to get Method-Meta information within a Method Attribute ?

I wont to avoid having to write the Event-Name both in the attribute and in the parameters of the method.

For the name of one property, the nameof(Type) can be acceptable, but for other cross-cutting-concerns, its simple not enough.

There are a lot of cross-cutting-concerns that need this - this is just one example:

 // From
        [SubscribeToEvent(nameof(SomeEventType))]
        public async Task SomeEventTypeEndpoint(SomeEventType someEvent)
        { (...) }
 // To
        [SubscribeToEvent]
        public async Task SomeEventTypeEndpoint(SomeEventType someEvent)
        { (...) }
// From
    [AttributeUsage(AttributeTargets.Method)]
    public class SubscribeToEventAttribute : TopicAttribute
    {
        public SubscribeToEventAttribute(string eventName) 
        {
           // Do: log name, analytics, ect...
        }
    }
// To
    [AttributeUsage(AttributeTargets.Method)]
    public class SubscribeToEventAttribute : TopicAttribute
    {
        public SubscribeToEventAttribute() 
        {
           // Some reflection on what this attribute is applied to ?
           // Getting something like System.Reflection.ParameterInfo
           // Do: log name, analytics, ect...
        }
    }

Some people





How to correctly use alert with apply in JavaScript?

I wonder whether the JavaScript alert function in the browser needs the document as this parameter or not. So what is the correct call via apply?

/* Variant 1 */
alert.apply(null, ["Hello World!"])

/* Variant 2 */
alert.apply(window, ["Hello World!"])

An answer to the above question might also discuss bind and call, but I would be already happy if somebody could enlighten the apply case.

Edit 25.06.2021:
It seems that alert is not "normal", I get inside some fiddle:

/* Variant 3 */
alert.apply(document, ["Hello World!"]);
-->
Error: 'alert' called on an object that does not implement interface Window.




jeudi 24 juin 2021

If a class contain a list of another class's object then how to access the list element using reflection in C#?

I have the following 3 classes and I want to print all values of the list stdInfo from the Access class using reflection but I have faced trouble doing this. please, someone, help me to do this task:

public class Student
{
      public int ID { get; set; }
      public List<StudentInfo> stdInfo { get; set; }
      public Student()
      {

        }
        public Student(int Id, List<StudentInfo> info)
        {
            this.ID = Id;
            stdInfo = info;
        }
 }


public class StudentInfo
{
        public int ID { get; set; }
        public string Name { get; set; }
        public StudentInfo()
        {

        }
        public StudentInfo(int id,string name)
        {
            ID = id;
            Name = name;
        }
}


public class Access
{
     
}




Using System.Reflection.Emit in UWP (with .NET Native Tool Chain)

The app that I am working on requires ".NET Native Tool Chain" to be enabled in project settings, as it will be distributed via the Microsoft Store.

Part of the functionality of this app is that it will have calculations performed via a user-defined string (including variables in the string), for example: (5-#myVar#)+2

For this purpose, we are using an expression evaluator to resolve the user-defined calculation string. This library and all equivalent libraries (as far as I can tell) use System.Reflection.Emit to create a DynamicMethod to evaluate the expression.

The problem is with using a DynamicMethod when .NET Native Tool Chain is enabled - a runtime exception occurs: Dynamic code generation is not supported on this platform.

That error makes sense. However, in the app manifest, under "capabilities", there is an option to enable Code Generation. Unfortunately enabling this capability seems to have no effect whatsoever.

Is there something else required to enable code generation? Or is this tickbox a red herring?

And if code generation simply cannot be enabled at all - then is there a workaround for this that would avoid the use of System.Reflection.Emit?





mercredi 23 juin 2021

How to dynamically create an object for an abstract class without casting?

I have a abstract class in JAVA and few subclasses. I have a function that returns an instance of one of these subclasses. I don't want to check with few if...else to create an object based on the return type. need to do it dynamically at run time. this solution didn't help me

// Expression is abstract class, A is subclass\
    // this return me null because i did not make a new object for e1, I know a subclass of Expression
    Expression e1 = ReplaceExpression();

I can do it like this but i need cleaner solution:

if (ReplaceExpression().getClass().getSimpleName() == "A")
Expression e1 = new A();

So my question is: is there anyway I can instantiate a new subclass for my abstract class without hardcoding or casting? something like dynamically or reflection





How to mirror/reflect a vector relative to the last value

how can I reflect the vector relative to the last value, I don't know how to explain it in words, so I will show it with pictures enter image description here

enter image description here

I tried to do it myself, but my code only works with linear vector

x <- 1:10
y <- rev(cumsum(c(tail(x,1),diff(x))))

plot(rep(NA,20),t="l" , ylim = c(1,20))
lines(x,col=2,lwd=5)
lines(y,col=4,lty=5)

enter image description here

If you take an arbitrary vector, my code doesn't work

set.seed(123)
x <- cumsum(rnorm(10))  # real vector
y <- rev(cumsum(c(tail(x,1),diff(x))))

plot(rep(NA,20),t="l" , ylim = c(-5,10))
lines(x,col=2,lwd=5)
lines(y,col=4,lty=5)

enter image description here





Reflection and Invoking Method from Java to Kotlin

I'm trying to convert the following reflection into Kotlin. The following uses reflection to call an RFCOMMs function so it can take a port/channel as an input instead of UUID. I have all my program in Kotlin. Anyone know how to write this in Kotlin?

int bt_port_to_connect = 5;
BluetoothDevice device = mDevice;
BluetoothSocket deviceSocket = null;
...

// IMPORTANT: we create a reference to the 'createInsecureRfcommSocket' method
// and not(!) to the 'createInsecureRfcommSocketToServiceRecord' (which is what the 
// android SDK documentation publishes

Method m = device.getClass().getMethod("createInsecureRfcommSocket", new Class[] {int.class});

deviceSocket = (BluetoothSocket) m.invoke(device,bt_port_to_connect);




How to create a constant log with annotation?

I have a project that has a specific library that has its own LogFactoring where we save information and act as we want, but in all classes I need to define:

private static final MyLogger LOGGER = MyLoggerFactory.getLogger(MyCurrentClass.class);

I would like to create an annotation that already creates this LOGGER constant to be used. I did several searches and didn't find it.





How to get a list of variable names corresponding to properties used in a LambdaExpression?

I have a LambdaExpression which has a lambda body like x => x.FirstName == "Joe" And x.LastName == "Bloggs" (it can also contain more properties and it can also contain Or operators).

How do I get a List<string> of all the property names used in that lambda? So the list would look like below based on the lambda above.

FirstName
LastName 

There are other stackoverflow pages which somehow cast their Expression to MemberExpression, however this does not work for me because it won't cast properly.An example of what I'm trying to do is like this answer below but that is returning PropertyInfo rather than a list of strings

https://stackoverflow.com/a/672212/1389239





How to invoke a method via reflection that takes in a Func

I'm using SpecFlow, and I want to shove proxy in the service registrations from IServiceCollection so that ScenarioContext.ScenarioContainer can resolve them.

The strategy I'm trying to use is simply to register a factory for each of the types defined in the service collection so that the ScenarioContainer can resolve them. Unfortunately for me, there is no non-generic alternative to RegisterFactoryAs, so I'm trying to create a generic method and invoke it via reflection.

Where I'm hitting a wall is the arguments to MethodBase.Invoke: the first argument to RegisterFactoryAs is a Func<IObjectContainer, T>, and I'm encountering two problems with it:

  1. I cannot define it as Func<IObjectContainer, T> factory = _ => ... since I don't have an outer-scoped T.
  2. When attempting to use it as Func<IObjectContainer, object>, I the run-time exception "System.InvalidOperationException : Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true."
  3. When attempting to use the local function FactoryFunction, I see a compile error stating that I can't convert a method group into an object.

My best bet seems to be the local function, if I can somehow convert it into the required Func.

private void AddToObjectContainer2(IServiceCollection services)
{
    var sp = services.BuildServiceProvider();
    foreach (var sd in services)
    {
        var containerType = _scenarioContext.ScenarioContainer.GetType();
        var delegateType = typeof(Func<,>).MakeGenericType(typeof(IObjectContainer), sd.ServiceType);
        var methodInfo = containerType
            .GetMethod(nameof(IObjectContainer.RegisterFactoryAs),
                new[]
                {
                    delegateType,
                    typeof(string)
                });
        var registerFactoryAs = methodInfo
            !.MakeGenericMethod(new[]
            {
                sd.ServiceType
            });

        Func<IObjectContainer, T> factoryWithCompileError = _ =>
        {
            return sp.GetService(sd.ServiceType);
        };
        
        Func<IObjectContainer, object> factory = _ =>
        {
            return sp.GetService(sd.ServiceType);
        };

        T FactoryFunction<T>(IObjectContainer c)
        {
            return (T)sp.GetService(sd.ServiceType); 
        }
        
        // Throws System.InvalidOperationException : Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.
        registerFactoryAs.Invoke(_scenarioContext.ScenarioContainer,
            new object[]
            {
                factory , (string)null
            });
        
        // Compiler error: Cannot convert expression of type 'method group' to type 'object'
        registerFactoryAs.Invoke(_scenarioContext.ScenarioContainer,
            new object[]
            {
                FactoryFunction , (string)null
            });
    }
}

I tried to use https://github.com/solidtoken/SpecFlow.DependencyInjection, but it can't seem to handle one of the auto-registered types we're using that has an internal implementation in the Specflow library.

I tried https://github.com/AdCodicem/SpecFlowMicrosoftDependencyInjection, but apparently the signature of a method of one of its dependencies has been removed, and it's throwing a MethodNotFoundException at runtime.





Custom annotation processor VS processing annotation via reflection api

I want to write simple custom validation annotation and can't find proper info on difference between two ways, that i know, of processing them, which are:

  • Reflection API
  • Custom processor extending javax.annotation.processing.AbstractProcessor

Can please someone tell me the difference between these options and which is better for which scenario, any help would be appreciated





How to handle list dynamically Using reflection and cast returned data to list

When I add a list in instances value and return that list its provides always duplicate value. I wanna read data from the database table values. But its first iterations add a single row value, the second time its provides 2nd row value and replaces the 1st list values.

var instance = (T)Activator.CreateInstance(type);

        while (reader.Read())
        {
           type.GetProperties().ToList().ForEach(property =>
            {
                property.SetValue(instance,reader[property.Name]);
            });
            list.Add(instance);  
        }
        return list;




How to call a method at runtime based on a string value using springboot/ any java design?

Consider below example, I want to call appropriate produce method based on vehicle, where vehicle can be "car" or "bike" or "van"

Class Company {

public void manufacture(String vehicle) {

   //How to call appropriate **produce** method based on string(vehicle) passed as param in this method **without using if or switch condition here**?

}

}


Class AutoMob {

public void produce(Car c, ....){

}

public void produce(Bike b, ....){

}

public void produce(Van l, ....){

}

}

I dont want to use reflection or condition here and looking for design based approach or any idea using springboot?

Thanks in advance!!





C# PropertyInfo.GetValue returns the concrete type

I want to query the object information, put them in my internal data types, and do some object compare later (the first thing I do is to compare the type, but I don't care about its concrete type).

//Client side
Foo a = new Foo() { Numbers = new int[3] { 1, 2, 3 } };

var r = GetCurrentProperties(a, typeof(Foo));

List<PropertyEntity> GetCurrentProperties(object objectValue, Type type)
{
    //.....
    var property = type.GetProperties()[0]; //just an example that we know the first one is IList
    object value = property.GetValue(objectValue);

    //I'm expecting value to have type of IList<int>
    Assert.True(property.PropertyType == typeof(IList<int>));
    Assert.True(value.GetType() == typeof(IList<int>)); //Error. It's an int[]...

    //...
}

It's important to notice that Type is a runtime type from the client-side. Thus I don't know what it would be at compile time. Currently, I can only think of using Convert.ChangeType to the value, but this requires the object to implement IConvertible. Is there a more elegant way?





mardi 22 juin 2021

Is it possible to use EF Function Translation during an Add in Entity Framework 5?

Long story short, we have spent the past few days creating a translation to add decrypt/encrypt by key into Entity Framework.

The following select works (the hardcoded key "test" is just for a testing environment, this will be stored with keystores later) The EF.Functions.Decrypt triggers a translation expression that writes custom SQL for Entity Framework to utilize the internal decryption methods.

var filteredSet = Set.Include(x => x.Table2)
            .Where(x => x.Id == id)
            .Where(x => x.Table2.IsSomething)
            .Select(m => new Model
        {
            Id = m.Id,
            Decrypted = EF.Functions.Decrypt("test", m.Encrypted), //string
            Table2 = m.Table2,
            Encrypted = m.Encrypted //byte[]
        }).ToList();

The following (as I sort of expected going into it) does not.

public Model createNew(string Data)
    {
        Set.Add(
                new Model
                {
                    Encrypted = EF.Functions.Encrypt("test", Data)
                }
            );
        return new Model();
    }

When used in this manner it attempts to create a new model object using the EF Function and throws an InvalidOperationError. Is there a way to perform an Add in EF where it translates this function rather attempting the execute the code into a model?





Using the recursive function by making the type transformation in the generic method at run time

I have a list from AppLayerGroup class, within this list I have another list from AppLayer class. What I want to do is to translate each property of the list I send to the TranslateList method into a language of my choice. If the corresponding value of each property of the list exists in the view, I update it. If the property is a list, I try to send the new list back to the Translate method with the help of the recursive function. But type 'T' is not same as first time type, I need to convert it at runtime but I don't know how to do that.

    public class AppLayer : IEntity
    {
        public int Id { get; set; }
        public int AppLayerGroupId { get; set; }
        public string LayerName { get; set; }
    }

    public class AppLayerGroup : IEntity
    {
        public int Id { get; set; }
        public string GroupKey { get; set; }
        public virtual ICollection<AppLayer> AppLayer { get; set; }
    }
    public static IEnumerable<T> TranslateList<T>(this IEnumerable<T> data)
    {
        var _httpContextAccessor = (IHttpContextAccessor)ServiceTool.ServiceProvider.GetService(typeof(IHttpContextAccessor));
        var userId = _httpContextAccessor.HttpContext?.User.Claims.FirstOrDefault(x => x.Type.EndsWith("nameidentifier"))?.Value;
        var _cacheManager = (ICacheManager)ServiceTool.ServiceProvider.GetService(typeof(ICacheManager));

        short appLangId = Convert.ToInt16(_cacheManager.Get($"{CacheKeys.UserLang}={userId}"));

        Translate(data, appLangId);

        return data;
    }

    

    public static IEnumerable<T> Translate<T>(IEnumerable<T> data, short appLangId)
    {
        string classname = (data.FirstOrDefault() as Castle.DynamicProxy.IProxyTargetAccessor).DynProxyGetTarget().GetType().BaseType.Name;

        var _vAppLookupLanguageRepository = (IVAppLookupLanguageRepository)ServiceTool.ServiceProvider.GetService(typeof(IVAppLookupLanguageRepository));
        var langList = _vAppLookupLanguageRepository.GetList(a => a.EntityName == classname && a.AppLanguageId == appLangId);

        if (langList.IsAny() && data.IsAny())
        {
            foreach (var item in data )
            {
                foreach (PropertyInfo prop in item.GetType().GetProperties())
                {
                    if (prop.PropertyType.GetInterface("IEnumerable").Name == "IEnumerable")
                    {
                        var subList = (IEnumerable)prop.GetValue(item, null);

                        Translate((IEnumerable<T>)subList, 2); //I should submit the type of subList instead of 'T'
                    }
                    if (langList.Any(a => a.ColumnName == prop.Name))
                        prop.SetValue(item, langList.FirstOrDefault(a => a.UniqueValue == prop.GetValue(item).ToString()).LanguageValue, null);
                }
            }
        }

        return data;
    }

I did some research but couldn't find the right result.





lundi 21 juin 2021

How can I set value to readonly Httpcontex.request.HttpMethod?

I am trying to write testcases for a method and I want to set value to HTTPMethod, I am trying to use Reflection to do this but I'm getting object reference set to null, let me know how can I overcome this obstacle.

PFB Sample Code snippet.

HttpWorkerRequest httpWorkerRequest = new SimpleWorkerRequestHelper(false, "153.40.12.148", "/siteminderagent/forms/login.fcc", "Mozilla/4.0 (compatible; MSIE 7.0)")

HttpContext httpContext = new HttpContext(httpWorkerRequest);

typeof(HttpRequest).GetField("HttpMethod", BindingFlags.Instance).SetValue(httpContext, "POST");




Running fat jar vs sbt run

I am currently at a dead-end :)

So I have a project that I create a fat jar using sbt assembly. Then the intention is to run the jar using java -jar command. For testing purposes, I use sbt run which validates that everything works as expected. After that, I create a fat jar using sbt assembly. The problem is that the application crashes running the fat jar. sbt run works. java -jar app.jar fails. The error is not ClassNotFound or DefNotFound issue. Maybe it is not packaging a dependency correctly? I have investigated the issue various way and I even remote debugged the application to find out exact place the code fails on.

I have pasted the error for reference below.

Caused by: org.apache.kafka.common.config.ConfigException: HttpCredentialProvider not found for BASIC
    at io.confluent.security.auth.client.provider.BuiltInAuthProviders.loadHttpCredentialProviders(BuiltInAuthProviders.java:56)
    at io.confluent.security.auth.client.rest.RestClient.<init>(RestClient.java:117)
    at io.confluent.security.auth.client.rest.RestClient.<init>(RestClient.java:95)
    at io.confluent.kafka.clients.plugins.auth.token.TokenUserLoginCallbackHandler.configure(TokenUserLoginCallbackHandler.java:67)
    at io.confluent.kafka.clients.plugins.auth.token.AbstractTokenLoginCallbackHandler.configure(AbstractTokenLoginCallbackHandler.java:86)
    at org.apache.kafka.common.security.authenticator.LoginManager.<init>(LoginManager.java:60)
    at org.apache.kafka.common.security.authenticator.LoginManager.acquireLoginManager(LoginManager.java:105)
    at org.apache.kafka.common.network.SaslChannelBuilder.configure(SaslChannelBuilder.java:161)

After remote debugging and stepping into the code for a bit I found out that the code uses reflection.

        return new ServiceLoader<>(Reflection.getCallerClass(), service, loader);

The code is supposed to find BasicAuthCredentialProvider class. The jar tf -app.jar tells me that the jar contains that file. So this tells me that it is perhaps not a dependency issue. maybe I am wrong?

I then switched my Java versions from 8 to 11. No luck there either. I am running out of ideas. Does anyone have some other idea I could investigate?

enter image description here

enter image description here





How do I compile a delegate [duplicate]

I wish to compile a reflected delegate, but I fail miserably with the following exception:

System.ArgumentException: Cannot bind to the target method because its signature is not compatible with that of the delegate type.
   at System.Delegate.CreateDelegate(Type type, MethodInfo method, Boolean throwOnBindFailure)
   at wergwg.Program.Main(String[] args) in

This exception implies that the signature of the MethodInfo provided differs from the delegate I wish to compile it as (Func<TimeSpan, Int64>. Which just is not the case, I invite you all to hop into the debugger and validate, that the property getter of TimeSpan.Ticks indeed consumes a TimeSpan and returns a Int64 or long. Which in Func syntax is equal to Func<TimeSpan, Int64> yet the following code throws a runtime-exception.

TimeSpan ts = TimeSpan.FromMinutes(5);

PropertyInfo ticksProperty = typeof(TimeSpan).GetProperty(nameof(TimeSpan.Ticks));
MethodInfo getTicksMethod = ticksProperty.GetGetMethod(false);
Console.WriteLine(getTicksMethod.Invoke(ts, Array.Empty<object>()));
Func<TimeSpan, Int64> getTicks = (Func<TimeSpan, Int64>)Delegate.CreateDelegate(typeof(Func<TimeSpan, Int64>), getTicksMethod, true);
Console.WriteLine(getTicks(ts));

here is a dotnetfiddle link.


I face the same issue with all instances where I try to compile a reflected delegate, be it from a property, or a method. So I conclude that I am doing something wrong, please educate me in what exactly I am missing and how to "fix" the code above.

Thank you for your time, cheers.





how to pass a generic type parameter in method

I have a generic class and have some method. The methods work is Insert, update ,delete in database using reflection. But my problem is I cannot insert pass values in Insert Method

that's the main class when I called my insert method, I can not pass values

MyORM class

public class MyORM<T> where T:IData
{
    private SqlConnection _sqlConnection;

    public MyORM(SqlConnection sqlConnection)
    {
        _sqlConnection = sqlConnection;
    }

    public MyORM(string connectionString)
        : this(new SqlConnection(connectionString))
    {

    }

    public void Insert(T item)
    {
        var sql = new StringBuilder("insert into ");
        var type = item.GetType();
        var properties = type.GetProperties();

        sql.Append(type.Name);
        sql.Append("( ");

        foreach(var property in properties)
        {
            sql.Append(property.Name);
            sql.Append(",");
        }

        sql.Remove(sql.Length - 1, 1);

        sql.Append(" ) values (");

        foreach(var property in properties)
        {
            sql.Append("@");
            sql.Append(property.Name);
            sql.Append(",");
        }
        sql.Remove(sql.Length - 1, 1);
        sql.Append(");");

        var query = sql.ToString();

        var command = new SqlCommand(query,_sqlConnection);

        foreach(var property in properties)
        {
            command.Parameters.Add(property.GetValue(item));
        }


    }
} 

static void Main(string[] args)
{
     var orm = new MyORM<StudentInfo>(DbConnection.connectionString);
        orm.Insert();
}




Object with type "RibbonForm" cannot be converted to type "RibbonForm&" when calling a method via reflection

Due to certain circumstances I have to call a function from Project A in Project B via reflection.

The signature of the method to be called looks like this:

public function Copy(ByRef MainForm as RibbonForm, ID_Source as INT, BYREF ID_new as int) AS BOOLEAN

...

END FUNCTION

The call in Project B to this function is as following:

Private Sub F_Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim ID_VERTRAG_SOURCE As Integer = 2101
    Dim ID_VERTRAG_DEST As Integer = 0
    Dim RibbonForm As RibbonForm

    'V2
    Dim Assembly As Assembly = Assembly.LoadFrom("*PATH TO EXE*")
    AppDomain.CurrentDomain.Load(Assembly.GetName())
    Dim t As Type = Assembly.GetType("*CLASS NAME*")
    Dim dynamicInstance As Object = Activator.CreateInstance(t)

    RibbonForm = New RibbonForm


    Dim classInstance As Object = Activator.CreateInstance(t)

    Dim p As Object() = {RibbonForm, ID_VERTRAG_SOURCE, ID_VERTRAG_DEST}
    Dim methodInfo As MethodInfo = t.GetMethod("Copy")
    Dim result = methodInfo.Invoke(classInstance, p)
    End Sub

When trying to invoke the method i get the following exception:

The Object of Type "DevExpress.XtraBars.Ribbon.RibbonForm" cannot be converted to type "DevExpress.XtraBars.Ribbon.RibbonForm&". bei System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast) bei System.RuntimeType.CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr) bei System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig) bei System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) bei System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
bei System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) bei LNG_Indexanpassung_addon.Form1.F_Main_Load(Object sender, EventArgs e) in *****\Form1.vb:Zeile 25. bei System.EventHandler.Invoke(Object sender, EventArgs e) bei System.Windows.Forms.Form.OnLoad(EventArgs e) bei System.Windows.Forms.Form.OnCreateControl() bei System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
bei System.Windows.Forms.Control.CreateControl() bei System.Windows.Forms.Control.WmShowWindow(Message& m) bei System.Windows.Forms.Control.WndProc(Message& m) bei System.Windows.Forms.ScrollableControl.WndProc(Message& m) bei System.Windows.Forms.Form.WmShowWindow(Message& m) bei System.Windows.Forms.Form.WndProc(Message& m) bei System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) bei System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) bei System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)





dimanche 20 juin 2021

Map enum values to corresponding types with templates at compile time?

I have an idea of mapping enum values to corresponding data types, at compile time with templates. How can i do this?

e.g.


enum DataType {
  UNSINGED_INT; // uint32_t
  INT; // int32_t
  UNSIGNED_CHAR; // uint8_t
  CHAR; // int8_t
}

auto type = MapToDataType<DataType::UNSIGNED_CHAR>; // type will be uint8_t in this case





How to get all methods and their return values in .NET Core? [duplicate]

I have a static class like this

public static partial class PublicWidgetZones
{
    public static string AccountNavigationAfter => "account_navigation_after";
    public static string AccountNavigationBefore => "account_navigation_before";
    public static string AdminHeaderLinksAfter => "admin_header_links_after";
}

I want to write a dynamic program that returns a Dictionary<string, string> that has these values:

      Key                                          Value
------------------------------------------------------------------------
"AccountNavigationAfter"                    "account_navigation_after"
"AccountNavigationBefore"                    "account_navigation_before"
"AdminHeaderLinksAfter "                     "admin_header_links_after"

N.B: I have a program that return only methods name

    public static List<string> GetWidgetZoneNames(Type type)
    {
        List<string> names = new List<string>();
        foreach (var method in type.GetMethods())
                    {    
                        string[] splitedMethodName = method.Name.Split(new string[] { "get_" }, StringSplitOptions.None);
                        if (splitedMethodName.Length > 1)
                        {
                            names.Add(splitedMethodName[1]);
                        }
                    }

           return names;
    }




EventBus Xamaring. Custom method of activity not found using reflection

I've added EventBus as a binding library in my Xamarin Android project. I can compile without errors but when I'm trying to register, I get the following error:

enter image description here

Here is the code for the activity

[Activity(Icon = "@mipmap/ic_launcher"]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Forms.Init(this, savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        CrossCurrentActivity.Current.Init(this, savedInstanceState);
        LoadApplication(new App());
        

        EventBus.Default.Register(this);
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
        EventBus.Default.Unregister(this);
    }

    [Subscribe]
    public void onEvent(DeviceConnectionEvent my_event)
    {
        throw new NotImplementedException();
    }

    protected override void OnActivityResult(int requestCode, Result resultVal, Intent data)
    {

        if (requestCode == 1)
        {
            wifiManagerInstance.onNetworkDataReceived();
        }

        base.OnActivityResult(requestCode, resultVal, data);

    }
}

It looks like my method is not being detected when eventbus uses reflection

methods = findState.clazz.getDeclaredMethods();

Other methods of the activity are detected as can be seen in the following picture.

enter image description here

Is there anything I can do?

Thanks in advance.





samedi 19 juin 2021

Java Deserialization gadget - Why is this ysoserial payload using reflection to set the TiedMapEntry?

I started studying Java deserialization gadgets. I started with the famous Apache Common Collections gadget and was looking at @matthias_kaiser's gadget chain.

https://github.com/frohoff/ysoserial/blob/master/src/main/java/ysoserial/payloads/CommonsCollections6.java#L65-L100

Could someone please explain the following?

  1. Why is the TiedMapEntry set via Java reflection vs just using the HashSet#add() method? For example,

    HashSet hashSet = new HashSet();
    hashSet.add(tiedMapEntry);
    
  2. I tried the above and I got a Caused by: java.io.NotSerializableException: java.lang.ProcessImpl exception which is leading me to believe that something might be going wrong during serialization.

  3. Is there some way to find out what might be wrong? Any tips on debugging and where to look at?

  4. Any ideas on how Matthias might have figured out the reflection "hack" or perhaps his thought process? (I will also try to contact him and others).

If there are additional tips (particularly in debugging), please share because this would help me greatly in understanding this and other vulnerabilities.





Is there any way to use type variables with generic methods? [duplicate]

I found some information about instatiating generic classes using dynamic types, but what about methods?

How would I go about doing something like this:

var type = typeof(Foo);
someObject.Bar<Type>();




Getting all assembly names related to a namespace

How can I get all the assemblies related to a namespace?

For example, if I have "using System" in my project, then I want to have an array of the assemblies "System.Console, System.Private.CoreLib ...".





Parse Java reflection class

Let's say I have a method called Class<?> classInstance = createInstance("Page", map, factory) which creates an instance of "Page" with java reflection and does some stuff with it. For demonstration purposes I've called it "Page", but it could be any of my classes.

Now I want to add this object to a List<Page>. To call list.add(classInstance) and add it to the list I need to parse it to "Page". Is there a way to do it, given the only information I have is the string containing the class name? So instead of doing (Page) classInstance I need to do something like (Class.forName("Page")) classInstance.

I can not modify the List or the way it is added to the list.

Thank you.





Duplicate 'System.Reflection.AssemblyCompanyAttribute' attribute (CS0579)

I am creating a .Net core project using VS Community V 8.10.2 on my Macbook air.

I created a parent .Net Core MVC project and created multiple class library projects in the same solution.

Now when I try to build my solution, I see my parent project having created folders for each of the Child projects. I am also getting build errors as shown below.enter image description here

How can i get rid of these errors and get my project working?





Print function contents as string but also be able to run it as code

I would like to make a function that can print the contents of another function without breaking the functionality of the copied function.

For example:

int functionToCopy()
{
    int a{ 5 };
    int b{ 6 };
    
    return a + b;
}

void printCopiedFunction()
{
    some magical code to print the contents of the first function;
}

int main()
{
    std::cout << functionToCopy() << '\n';
    std::cout << printCopiedFunction() << '\n';

    return 0;
}

Output:

11

int functionToCopy()
{
    int a{ 5 };
    int b{ 6 };
    
    return a + b;
}

I'm only a beginner and C++ is my first language. I've done a lot searching and thinking but the only way I could think of is just literally copying the function and making a 2nd function a string, which would double my code and I'd rather avoid that. The program I'd like to do this with currently has 26 functions that would need copying like that so a single function that can be reused would be much preferred.

std::string copiedFunction()
{
    std::string str{ R"(
    int functionToCopy()
    {
    int a { 5 };
    inb b { 6 };

    return a + b;
    })" 
return str;
};

Any help is much appreciated! This is the only time I've ever asked for help like this on a forum but I think this is just beyond my abilities at this point. I understand this may not be possible or it may be very complex and just beyond my scope at this time. Thank you in advance!





vendredi 18 juin 2021

Access a list using reflection?

   class House {
      public int Id { get; set; }
      public List<Room> Rooms { get; set; }
}

class Room {
      public int Id { get; set; }
      public double Rent { get; set; }
}

I have an object of House. How can I Read the list of Rooms using Reflection?





Dynamically generate Java test classes from given YAML

I need to generate Java test files from given YAML files. These YAML files will contain given and expected values.

Let's assume I have a generate-test.yaml file that looks like this:

tests:
  - name: StudentPassingGrade
    inputs:
      - input: 
          grade:
            type: exam #assume that this is enum and can take values like exam, quiz, etc.
            point: 60
            outOf: 100
            date: 2021-01-01
            notes:
              - note: "First exam of fall semester"
      - input: 
          grade:
            type: quiz #assume that this is enum and can take values like exam, quiz, etc.
            point: 4
            outOf: 10
            date: 2021-02-05
            notes:
              - note: "Pop quiz"
      - input: 
          grade:
            type: exam #assume that this is enum and can take values like exam, quiz, etc.
            point: 80
            outOf: 100
            date: 2021-03-10
            notes:
              - note: "Second exam of fall semester"
    results:
      - result:
          name: StudentWeighedGrade
          numOfGrades: 3
          numOfExamGrades: 2
          numOfQuizGrades: 1
          averageOfExamGradesWithPercentile: 70%
          averageOfQuizGradesWithPercentile: 40%
          weighedGradeWithPercentile: 64%
          passing: true 

From such a YAML file, I need to generate a Java test class, set it up with the values given in the input entry in the YAML file, define the assertion cases given in the results entry in the YAML file, and actually run the tests.

Such Java test file could look like this:

public class GeneratedTestClass1 extends SomeAbstractTestClass {
    
    @Test
    public void testStudentPassingGrade() { # name is taken from the given YAML file
        
        {
            Student student = new Student();

            Grade grade1 = new Grade();
            grade1.setType(Type.exam);
            grade1.setPoint(60);
            grade1.setPointsOutOf(100);
            grade1.setDate(LocalDate.of(2021,1,1));
            grade1.setNotes(new Note("First exam of fall semester"));

            Grade grade2 = new Grade();
            grade2.setType(Type.quiz);
            grade2.setPoint(4);
            grade2.setPointsOutOf(10);
            grade2.setDate(LocalDate.of(2021,2,5));
            grade2.setNotes(new Note("Pop quiz"));

            Grade grade3 = new Grade();
            grade3.setType(Type.exam);
            grade3.setPoint(80);
            grade3.setPointsOutOf(100);
            grade3.setDate(LocalDate.of(2021,3,10));
            grade3.setNotes(new Note("Second exam of fall semester"));

            student.setGrade(grade1);
            student.setGrade(grade2);
            student.setGrade(grade3);
        }
        {
            Assertions.assertEquals(student.getNumberOfGrades, 3) # value 3 from the given YAML
            Assertions.assertEquals(student.getNumberOfExamGrades, 2) # same as above
            Assertions.assertEquals(student.getNumberOfQuizGrades, 1) # same as above

            float weighedGrade = student.calculateWeighedGrade();
            Assertions.assertEquals(weighedGrade, 64);

            Assertions.assertEquals(student.isPassing(), true); # again, taken from YAML
        }
    }
}

Any tips on how to achieve this task? I googled around, found that maybe I can use Java Reflection API or Cucumber (though I am not sure about this one). But I am not sure how to start. Any help is appreciated!





How to get properties of type T in Task

I am trying to get the properties of a return type of a method using reflection.

I am getting the return type of the method using MethodInfo.ReturnType, which yields my a type of Task<T> since my method is async. Using GetProperties on this type yields me with the properties belonging to Task: Result, Exception, AsyncState. However, I want to get the properties of the underlying type T.

var myMethodInfo = MyType.GetMethod("MyMethod");
var returnType = myMethodInfo.ReturnType;
var myProperties = returnType.GetProperties(); // [Result, Exception, AsyncState]

How can I get the properties of the underlying type T in Task in stead of the properties of Task?





jeudi 17 juin 2021

How to load a java class outside the classpath?

I have a program where I want the user to be able to choose a .java class file from the file system, and then have that class loaded into the program.

I'm using a JFileChooser to allow the user to select a file. Then, I tried converting that file to a URL, and using a URLClassLoader to load the class (as suggested by these answers).

The problem is that, when I want to use the loadClass() method, I don't know the "full class name" of the class (e.g. java.lang.String). So, I don't know how to make this method work. Is there a way to get this class name? Or is there another way to do this?

Here is a sample of my code:

// Open the file chooser
JFileChooser fileChooser = new JFileChooser();
fileChooser.showOpenDialog(null);
File obtainedFile = fileChooser.getSelectedFile();

// Create the class loader from the file
URL classPath = obtainedFile.toURI().toURL();
URLClassLoader loader = new URLClassLoader(new URL[] {classPath});

// Get the class from the loader
Class<?> theClassIWant = loader.loadClass("the file name");    // What do I put here??




mercredi 16 juin 2021

Use an arbitrary object type to parse a MySql query (learning C# Reflection)

I'm trying to gain a better understanding of Generics and Reflection on C#. As an exercise, I'm executing a MySql query and trying to parse its results as predefined Objects:

//FOR TABLE A 
public class ObjectType1
    {
        public int id { get; set; }
        public String name { get; set; }
    }

 //FOR TABLE B
public class ObjectType2
    {
        public int id { get; set; }
        public timestamp expirationDate  { get; set; }    
    }

 //FOR TABLE C 
public class ObjectType3
    {
        public int id { get; set; }
        public BigDecimal price  { get; set; }
    
    }

My goal would look like this:

List<ObjectType1> listObjectsA =  selectAndCast(tableNameA, ObjectType1)
List<ObjectType2> listObjectsB =  selectAndCast(tableNameB, ObjectType2)
List<ObjectType3> listObjectsC =  selectAndCast(tableNameC, ObjectType3)

My question is, how could I specify the desired object type as a parameter? (Already checked the similar questions here at S.O., but got compilation errors).

Here's my code. Please note that some fake lines are added for clarification.

public List<Object> selectAndCast(String tableName, Object argExampleObject)
            {
    
                string connStr = "My connection parameters";
                String query = "Select * from " + tableName;
           
                MySqlConnection conn = new MySqlConnection(connStr);
    
                MySqlDataReader rdr = null;

 //  Prepares a list to store the future generated objects (fake code)

        

List <argExampleObject.GetType()> listaSalida = new List<argExampleObject.GetType() > ();

        try
        {
            conn.Open();

            MySqlCommand cmd = new MySqlCommand(query, conn);                            

            rdr = cmd.ExecuteReader();

 //  Create a dictionary that contains each column name and a consecutive number. That number will be used to locate the column by its name later
           

 Dictionary<String, int> dictionaryColumnNameVsIndex = new Dictionary<String, int>();

            for (int i = 0; i < rdr.FieldCount; i++)
            {
                String nombreColumna = rdr.GetName(i);
                dictionaryColumnNameVsIndex.Add(nombreColumna, i);
            }

            while (rdr.Read())
            {

//  For each row obtained from the query execution, create a new instance of the Example Object (fake code)

    Object <argExampleObject.GetType() > destinationObject = new Object<argExampleObject.GetType() > ();

 //  Take each column name of the row

               

 for (int i = 0; i < rdr.FieldCount; i++)
                {
                    PropertyInfo[] properties = argExampleObject.GetType().GetProperties();

                    foreach (PropertyInfo property in properties)
                    {

 //  Check if the destination object contains a property with the same name.
                       

 if (dictionaryColumnNameVsIndex.ContainsKey(property.Name))
                        {

 //  If it does, assign the value to said property.

    PropertyInfo propertyToBeChanged = destinationObject.GetProperty(property.Name));
                                    propertyToBeChanged.SetValue(rdr[dictionaryColumnNameVsIndex[property.Name]]);
                                }
                            }
                        }

 //  After all rows have been processed, return the object list
            

 listaSalida.Add(objeto);

            }

            return listaSalida;
        }
        catch (Exception ex)
        {

 //  Exception handling
        

    }
            finally
            {
                if (rdr != null)
                {
                    rdr.Close();
                    conn.Close();
                }
            }
        }




C# Generic expression tree that targets a method on a class?

I'm trying to make some syntax sugar method that returns a MethodInfo when provided with a Method reference. (My actual goal is fetching custom attributes from some controller actions)

The "vanilla" way to get a method info is:

MethodInfo m = typeof(Foo.API.Controllers.CountryController)
            .GetMethod(nameof(Foo.API.Controllers.CountryController.List)

I want something so I do not have to specify the entire namespace twice. Seriously, if I could use...

MethodInfoOf(Foo.API.Controllers.CountryController.List)

it would be amazing.





Locate CommandHandler from Command

I have 2 command interfaces:

public interface ICommand {}
public interface ICommand<TResult> {}

I have 2 command handler interfaces:

public interface ICommandHandler<in TCommand> where TCommand : ICommand
{
    Task HandleAsync(TCommand);
}
public interface ICommandHandler<in TCommand, TResult> where TCommand : ICommand<TResult>
{
    Task<TResult> HandleAsync(TCommand);
}

I have 2 command implementations

public class CreateWidgetCommand : ICommand<Guid>
{
    public string Name { get; set; }
}

public class DeleteWidgetCommand : ICommand
{
    public Guid Id { get; set; }
}

I have 2 command handler implementations

public class CreateWidgetCommandHandler : ICommandHandler<CreateWidgetCommand, Guid>
{
    public Task<Guid> HandleAsync(CreateWidgetCommand command)
    {
        // Save the widget
        // Return the Guid Id
    }
}
public class DeleteWidgetCommandHandler : ICommandHandler<DeleteWidgerCommand>
{
    public Task HandleAsync(DeleteWidgetCommand command)
    {
        // Delete the widget
    }
}

I now have root module object

public class WidgetModule
{
    public async Task<TResult> ExecuteCommandAsync<TResult>(ICommand<TResult> command)
    {
        // NEED TO FIND THE HANDLER THAT IMPLEMENTS ...
        // ... ICommandHandler<command type, TResult>
        // AND THEN CONSTRUCT IT AND EXECUTE

        // MY BEST EFFORT SO FAR:

        // Create the interface that must be implemented by the CommandHandler
        Type commandType = command.GetType();
        Type handlerType = typeof(ICommandHandler<,>);
        Type[] handlerArgs = { commandType, typeof(TResult) };
        Type handlerInterfaceConstructed = handlerType.MakeGenericType(handlerArgs);

        // Find the concrete type that implements this interface
        Type concreteHandlerType = System.Reflection.Assembly
            .GetExecutingAssembly()
            .GetTypes()
            .Single(type => !type.IsInterface
                        && handlerInterfaceConstructed.IsAssignableFrom(type))

        // Construct the concrete type
        ... argh ... stuck!
        
            
    }
    public async Task ExecuteCommandAsync(ICommand command)
    {
        // NEED TO FIND THE HANDLER THAT IMPLEMENTS ...
        // ... ICommandHandler<command type>
    }
}

How can I create an instance of the command handler that processes the command provided?





Java reflection - Get values from class instance field

I am trying to create an some cheat for Minecraft. For this I decided to use reflection and agents. At the first stage, a question arose. I have Minecraft.class class. This class has getMinecraft() method that returns the instance of Minecraft. And this instance has player field. From this field, i need to get posX variable. I think I did not explain very clearly, so here is an example code of what I want to do:

final net.minecraft.client.Minecraft mc = net.minecraft.client.Minecraft.getMinecraft();
System.out.println(mc.player.posX);

And now, is it possible to somehow implement this through reflection?





How to make generic method using reflection on classes within the same project

Refer to the code below.

dbConn.Open();
                    List<MigrateAnnex> list13 = dbConn.ReadAll<MigrateAnnex>(parameter.SQLQuery);
                    dbConn.Close();
                    //convert to csv
                    using (var writer = new StreamWriter(parameter.FullPath))
                    using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
                    {
                        csv.Context.RegisterClassMap<MigrateAnnexMap>();
                        csv.WriteRecords(list13);
                    }
                    break;

I have this snippet of code and what I want to achieve is I need to make a method that will call this line of code and make the type as the parameter. I'm aware of generics and reflection but I don't want to have a line of code that will call the generic method and pass the parameter but instead, I just want to load all the possible classes that I have in my project then using reflection I can inject the type to call the generic method.

enter image description here

I have these classes within the main project and these classes are the parameters that I need to pass on the generic method. The question is how can I do that, I already used Assembly.LoadFrom where I can load directly the dll but I don't want to make another class library. I just want to stay my classes on the same project for simplicity sake. I don't know if there are other option to use Assembly.LoadFrom or a much better approach to solve my issue.





mardi 15 juin 2021

Shorter Parameter List with Defaults

Is their a way I can tidy this up

public Task<List<Categories>> GetAllCatgoriesViewModelAsyncByStoreId(Guid StoreId,Guid TennantId)
{
  return _context.Categories.Where(w => w.StoreId == StoreId && w.TennantId == TennantId).ToListAsync();
}

I know for where clauses I can do this.

modelBuilder.Entity<SalesOrder>().HasQueryFilter(q => q.isDeleted == false && q.isActive == true);           
modelBuilder.Entity<SalesOrderItem>().HasQueryFilter(q => q.isDeleted == false && q.isActive == true);

But it still means I have to do this every time (Guid StoreId,Guid TennantId) as below is their anyway to have a cleaner parameter List?

GetAllCatgoriesViewModelAsyncByStoreId(Guid StoreId,Guid TennantId)
 

//This version would still apply the above parameters but not having to create them each time both in the method signature and where clause

Something like .HasStoreTennantId

 public Task<List<Categories>> GetAllCatgoriesViewModelAsyncByStoreId()
 {
        return _context.Categories.HasStoreTennantId().ToListAsync();
 }




Why there is no Binding redirection concept in .NET Core?

Context:

I have been working lately on a tool that perform analysis on a given binary(resulting assembly from compilation process). the objective of the analysis is to alert developer about missing dependencies that will be used at runtime.

Using reflection, I am able to get the needed dependencies, for .NET Framework i am also reading .config files to get binding redirection and take them into account.

My questions are:

Is there any support for binding redirection or similar concept in .NET Core ? If yes is there any alternative to that ? I know that there is .deps file but i think it's not meant to be manually modified?

N.B. I have tried to modify .deps file manually to redirect Newtonsoft.Json to a specific version and it always fails to found the dependency, i found that somehow strange because CoreCLR parses the .deps file to get the dependencies as mentioned here.

I have seen this questions but without no specific answer for .NET Core





Is there a way to get all Memberclasses of a class and loop over them to excecute methods?

I have an ManagerCLass, which includes many other Objects. Here are methodes, that takes thes Objects and call an method on theses Objects.. Example:

public class Manager extends BaseManager {



ClassA classA = new ClassA();
ClassB classB = new ClassB();
ClassC classC = new ClassC();
ClassD classD = new ClassD();
ClassE classE = new ClassE();


public void callMethodsOnObjects() {
    classA.printResult();
    classB.printResult();
    classC.printResult();
    classD.printResult();
    classE.printResult();
}

}

These classes have all the same Superclass. Now my Question is, is there a way to automate the callMethodsOnObjects()-method?

My Idea was to get all declaredClasses of the Managerclass. Then to Loop of the array an excecute the printResult()-methode on each Object.

Class<?>[] classes = Manager.class.getDeclaredClasses();

    for (int i = 0; i < classes.length; i++) {
        ....
    }

But this don´t work. The Array is Empty.

So do you have an Idea if this a way to automate this? There are still more methods that are structured this way. I'm not getting anywhere here. Does it make sense to do it this way, as I imagined it?





lundi 14 juin 2021

Array of objects: how to get names of objects inside array?

For example, I have such method:

public void ExecuteExampleMethod()
{
    var exampleId1 = 1;
    var exampleId2 = 2
    ExampleMethod(0, exampleId1, exampleId2)
}

public void ExampleMethod(int exampleId, params object[] parameters)
{
   foreach(var parameter in parameters)
   {
     Console.WriteLine($"{parameter.Name} {parameter.Value}")
   }
   
}
  

So, I need to output like this:

"exampleId1 1"
"exampleId2 2"

How can I do it? I tried reflection = parameter.GetType() - but didn't find anything useful.





How to get the value of a constant field of a static class using the name of that class? [duplicate]

Elements.cs

namespace Tutorials
{
    public static class Elements
    {
        public const string element1 = "asd";
        public const string element2 = "qwe";
        public const string element3 = "zxc";
    }
}

Program.cs

namespace Tutorials
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            string FindThisField = "element1";
            string FromThisStaticClass = "Elements";

            string result = GetFieldFromStaticClass(FromThisStaticClass, FindThisField);
            Console.WriteLine(result);
        }

        public static string GetFieldFromStaticClass(string typeName, string fieldName)
        {
            Type t = Type.GetType(typeName);

            FieldInfo[] fields = t.GetFields(BindingFlags.Static | BindingFlags.Public);
            string value;
            foreach (FieldInfo fi in fields)
            {
                if (fi.Name == fieldName)
                {
                    value = fi.GetValue(null).ToString();
                    return value;
                }
            }
            return null;
        }
    }
}

I can get the constants without any problems, but I also want to be able to get the Type t from a string.

Type t = Type.GetType(typeName);

Is there any better way to do it?

Edit:

I solved the problem by making the following change:

FromThisStaticClass = "Tutorials.Elements";




C# Expression tree: object array to Expression.New() parameters

I'd like to use expression trees to improve performance of some object-relational mapping code. The old code looks something like this:

public List<T> SqlToResults<T>(string query)
{
    // Do SQL stuff, get matching constructor for type T ...
    // ...

    List<T> results = new List<T>();

    // Create buffer for constructor parameters
    object[] constructorParams = new object[reader.FieldCount];
    
    while (reader.Read())
    {
        for (int i = 0; i < reader.FieldCount; i++)
        {
            // simplefied (there'd be some mapping to match correct order of parameters)
            constructorParams[i] = reader[i];
        }
        
        // create new instance of T with our data
        T result = (T)constructorInfoOfT.Invoke(constructorParams);
        
        // add new result to list of results
        results.Add(result);
    }
    return results;
}

The performance bottle neck in above code is the call to ConstructorInfo.Invoke() which I'd like to replace with an expression tree and a call to Expression.New() similar to the code in this answer. However at compile time I don't know the number of parameters and their types it seems to be a bit more complicated. Expression.New() takes an array of Expressions as the argument to the constructor but I only have an array of objects (which would be a single ParameterExpression). So I'd somehow have to loop over the content of the ParameterExpression to then map every element to it's own Expression which then can be passed as an Expression[] to Expression.New().

The code I have in mind would look something like this:

internal delegate TInstance Constructor<TInstance>(object[] parameters);

internal Constructor<T> BuildConstructerFrom<T>(ConstructorInfo constructorInfo)
{
    ParameterExpression constructorParameters = Expression.Parameter(typeof(object[]));

    Expression[] parameterExpressions;

    // ???
    // somehow map entries in constructorParameters to entries in parameterExpressions 
    // ???

    NewExpression constructorCall = Expression.New(constructorInfo, parameterExpressions);

    Constructor<T> ctor = (Constructor<T>)Expression.Lambda<Constructor<T>>(constructorCall, constructorParameters).Compile();
    return ctor;
}

I have taken a look at similar questions like foreach loop using expression trees and issue while building dynamic expression tree but I'm still unsure as to how to use these loops in my use case.





dimanche 13 juin 2021

Could not load file or assembly DevExpress.Persistent.BaseImpl.EF.v20.2

When I run my Winforms XAF Entity Framework application in VS 2019 IDE

Given I have System.IO.FileNotFound exception enabled in Common Language Runtime Exceptions.

I get this run time error.

System.IO.FileNotFoundException: 'Could not load file or assembly 'DevExpress.Persistent.BaseImpl.EF.v20.2, Version=20.2.5.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a' or one of its dependencies. The system cannot find the file specified.'

The call stack is

mscorlib.dll!System.Reflection.RuntimeAssembly.LoadWithPartialNameInternal(System.Reflection.AssemblyName an, System.Security.Policy.Evidence securityEvidence, ref System.Threading.StackCrawlMark stackMark)
mscorlib.dll!System.Reflection.Assembly.LoadWithPartialName(string partialName)
DevExpress.Data.v21.1.dll!DevExpress.Data.Utils.Helpers.LoadWithPartialName(string partialName)
DevExpress.Data.v21.1.dll!DevExpress.Data.Utils.AssemblyCache.LoadWithPartialName(string partialName)
DevExpress.Data.v21.1.dll!DevExpress.Utils.Design.DXAssemblyResolverEx.OnAssemblyResolve(object sender, System.ResolveEventArgs e)
mscorlib.dll!System.AppDomain.OnAssemblyResolveEvent(System.Reflection.RuntimeAssembly assembly, string assemblyFullName)
[Native to Managed Transition]
[Managed to Native Transition]
mscorlib.dll!System.RuntimeTypeHandle.GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref System.Threading.StackCrawlMark stackMark, System.IntPtr pPrivHostBinder, bool loadTypeFromPartialName)
mscorlib.dll!System.Type.GetType(string typeName, bool throwOnError)
EntityFramework.dll!System.Data.Entity.Infrastructure.DependencyResolution.ClrTypeAnnotationSerializer.Deserialize(string name, string value)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.SchemaElement.CreateMetadataPropertyFromXmlAttribute(string xmlNamespaceUri, string attributeName, string value)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.SchemaElement.AddOtherContent(System.Xml.XmlReader reader)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.SchemaElement.ParseAttribute(System.Xml.XmlReader reader)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.SchemaElement.Parse(System.Xml.XmlReader reader)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.Schema.HandleEntityTypeElement(System.Xml.XmlReader reader)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.Schema.HandleElement(System.Xml.XmlReader reader)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.SchemaElement.ParseElement(System.Xml.XmlReader reader)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.SchemaElement.Parse(System.Xml.XmlReader reader)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.Schema.HandleTopLevelSchemaElement(System.Xml.XmlReader reader)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.Schema.InternalParse(System.Xml.XmlReader sourceReader, string sourceLocation)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.Schema.Parse(System.Xml.XmlReader sourceReader, string sourceLocation)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.SchemaManager.ParseAndValidate(System.Collections.Generic.IEnumerable<System.Xml.XmlReader> xmlReaders, System.Collections.Generic.IEnumerable<string> sourceFilePaths, System.Data.Entity.Core.SchemaObjectModel.SchemaDataModelOption dataModel, System.Data.Entity.Core.SchemaObjectModel.AttributeValueNotification providerNotification, System.Data.Entity.Core.SchemaObjectModel.AttributeValueNotification providerManifestTokenNotification, System.Data.Entity.Core.SchemaObjectModel.ProviderManifestNeeded providerManifestNeeded, out System.Collections.Generic.IList<System.Data.Entity.Core.SchemaObjectModel.Schema> schemaCollection)
EntityFramework.dll!System.Data.Entity.Core.SchemaObjectModel.SchemaManager.ParseAndValidate(System.Collections.Generic.IEnumerable<System.Xml.XmlReader> xmlReaders, System.Collections.Generic.IEnumerable<string> sourceFilePaths, System.Data.Entity.Core.SchemaObjectModel.SchemaDataModelOption dataModel, System.Data.Entity.Core.Common.DbProviderManifest providerManifest, out System.Collections.Generic.IList<System.Data.Entity.Core.SchemaObjectModel.Schema> schemaCollection)
EntityFramework.dll!System.Data.Entity.Core.Metadata.Edm.EdmItemCollection.LoadItems(System.Collections.Generic.IEnumerable<System.Xml.XmlReader> xmlReaders, System.Collections.Generic.IEnumerable<string> sourceFilePaths, System.Data.Entity.Core.SchemaObjectModel.SchemaDataModelOption dataModelOption, System.Data.Entity.Core.Common.DbProviderManifest providerManifest, System.Data.Entity.Core.Metadata.Edm.ItemCollection itemCollection, bool throwOnError)
EntityFramework.dll!System.Data.Entity.Core.Metadata.Edm.EdmItemCollection.Init(System.Collections.Generic.IEnumerable<System.Xml.XmlReader> xmlReaders, System.Collections.Generic.IEnumerable<string> filePaths, bool throwOnError)
EntityFramework.dll!System.Data.Entity.Core.Metadata.Edm.EdmItemCollection.EdmItemCollection(System.Collections.Generic.IEnumerable<System.Xml.XmlReader> xmlReaders)
EntityFramework.dll!System.Data.Entity.Utilities.XDocumentExtensions.GetStorageMappingItemCollection(System.Xml.Linq.XDocument model, out System.Data.Entity.Infrastructure.DbProviderInfo providerInfo)
EntityFramework.dll!System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(System.Xml.Linq.XDocument sourceModel, System.Xml.Linq.XDocument targetModel, System.Lazy<System.Data.Entity.Migrations.Infrastructure.ModificationCommandTreeGenerator> modificationCommandTreeGenerator, System.Data.Entity.Migrations.Sql.MigrationSqlGenerator migrationSqlGenerator, string sourceModelVersion, string targetModelVersion)
EntityFramework.dll!System.Data.Entity.Internal.InternalContext.ModelMatches(System.Data.Entity.Migrations.Infrastructure.VersionedModel model)
EntityFramework.dll!System.Data.Entity.Internal.ModelCompatibilityChecker.CompatibleWithModel(System.Data.Entity.Internal.InternalContext internalContext, System.Data.Entity.Internal.ModelHashCalculator modelHashCalculator, bool throwIfNoMetadata, System.Data.Entity.Internal.DatabaseExistenceState existenceState)
EntityFramework.dll!System.Data.Entity.Internal.InternalContext.CompatibleWithModel(bool throwIfNoMetadata, System.Data.Entity.Internal.DatabaseExistenceState existenceState)
EntityFramework.dll!System.Data.Entity.Database.CompatibleWithModel(bool throwIfNoMetadata, System.Data.Entity.Internal.DatabaseExistenceState existenceState)
EntityFramework.dll!System.Data.Entity.Database.CompatibleWithModel(bool throwIfNoMetadata)
VIV.MyApp2.Win.exe!MyApp2.Win.Program.CheckMigrationVersionAndAskToUpgradeIfNeeded() Line 98
    at D:\dev\Viv.MyApp2\MyApp2.Win\Program.cs(98)
VIV.MyApp2.Win.exe!MyApp2.Win.Program.Main() Line 45
    at D:\dev\Viv.MyApp2\MyApp2.Win\Program.cs(45)

I have encountered this error before and reported to Dev Express here but the issue went away.

The source code is

    private static bool CheckMigrationVersionAndAskToUpgradeIfNeeded()
    {
        try
        {
            using (var db = new MigrationDbContext())
            {
                var compatible = db.Database.CompatibleWithModel(false);
                if (!compatible) compatible = RunMigrationsIfPresent(db);
                return compatible;
            }
        }
        catch (Exception ex)
        {
            var s = string.Format("Problem in MigrateIfNeeded \r\n" + ex);
            MessageBox.Show(s);
            return false;
        }
    }

Entity Framework is v6.4.4

Target framework is .Net Framework 4.7.2

Error line

From the call stack it seems that GetTypeByName is resolving to the wrong type. How do I fix that?





Android R.raw.class.getFields() returns no fields on release

I have following code (located in static method in public class, called on app start from MainActivity.onPostCreate):

Field[] fields = R.raw.class.getFields();
StringBuilder allFields = new StringBuilder();

for (int i = 0; i < fields.length; i++) {
    Field field = fields[i];
    allFields.append(field.getName() + " - " + field.getModifiers());
}

(this code is part of functionality for checking if resources are intact)

I had this mechanism for some time, but now (after updating code to new API-Level 30) it stopped working. When I run application from Android Studio then fields are found and I can list them.

But when I build app and run .apk it on the same device then fields array is empty. App works normally and all resources are available for normal usage.

I tried unpacking .apk file and I found expected keys in apk/res/values/public.xml. I also inspected project and fixed all errors.

Was there some change in privacy for this fields (in API 29 or 30)? Why I cannot access this data?