lundi 31 octobre 2016

Unity : How to save GameObject with reflection probe as texture or project to plane

About the GameObject having Reflection Probe, I want to export it in realtime as material or texture for mapping to other gameobject. Or could I get the material as a texture like camera target texture?

Thank you:)





Casting List Type at Runtime C# Reflection

I've been working on using reflection but its very new to me still. So the line below works. It returns a list of myType

var data = (List<Mytype>)getData();

But I don't know myType until run time. So my thoughts were the below code to get the type from the object returned and cast that type as a list of myType.

var data = getData(); // returns object, at runtime
Type thisType = data.GetType().GetGenericArguments().Single(); // gets myType
var dataList = (List<thisType>)getData(); // need to return a List of myType

I'm confusing the class Type and the type used in list. Can someone point me in the right direction to get a type at run time and set that as my type for a list?





C# Creating AutoMapper mapping using refelction

I need to create a maping (using AutoMapper) from n classes all being derived from one abstract class to a contract class

So for example:

public abstract class bar
{
   public string Field1 {get; set;}       
   public someClass Field2 {get; set;}
}

public class foo1bar: bar
{
 // members
}

public class foo2bar: bar
{
 // members
}

public class barContract
{
  public string Field1 {get; set;}

  // this will use existing someClass.Description field
  public string Field2Description {get; set;} 
}

implementations of bar class are multiple, and also are likely to change (more will be added) As Automapper cannot map to abstract class (so the construct mapperConfiguration.CreateMap<bar, barContract>() is incorrect), I was wondering will it be possible to use reflection to find all classes 'implementing' bar class and map them 'automatically'

 var type = typeof(bar);
            var types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(s => s.GetTypes())
                .Where(p => type.IsAssignableFrom(p));

I've got the Types, and I'm trying to invoke CreateMap. As the type is now a variable, im creating a generic method once again using refelction:

foreach (Type t in types)
            {
mapperConfiguration.GetType().GetMethod("CreateMap")
              .MakeGenericMethod(t, typeof(barContract))
              .Invoke(mapperConfiguration, null);
}

the problem is that CreateMap is not a member of type that is extracted from mapperconfiguration instance - when im tryng to extract the method by name i get null. I see its defined in IProfileExpression, so I'm trying to extract the method from the interface: typeof(IProfileExpression).GetMethod("CreateMap") and i get System.Reflection.AmbiguousMatchException - what is kind of ok, but using System.Reflection.BindingFlags in GetMethod to be more specyfic I'm again getting nulls.

What am I doing wrong, or how to get around that mapping problem ?





Call ToString() on a dynamically build expression

I'm trying to build an dynamic expression from a string of property-names (given by the user) on an IQueryable named source. This is what I have so far:

var parameter = Expression.Parameter(source.ElementType, "x");
var member = propertyChain.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField);
var selector = Expression.Lambda(member, parameter);

which will give me something like x => x.MainProperty.SubProperty when the input would be MainProperty.SubProperty.

I now need to add ToString() to the expression selector so it will produce the expression x => x.MainProperty.SubProperty.ToString() which then can be passed into other methods.

How can this be done?

Edit 1

I'm trying to build a dynamic GroupBy where the type of the key doesn't matter. But the property to group by can be of type Guid, int or something else. That's why I need to call ToString().

public static IEnumerable<IGrouping<T, string>>(IQueryable<T> source, string propertyChain)
{
    var parameter = Expression.Parameter(source.ElementType, "x");
    var member = propertyChain.Split('.').Aggregate((Expression)parameter, Expression.PropertyOrField);
    var selector = Expression.Lambda(member, parameter);

    // currently here I have x => x.MainProperty.SubProperty
    // here I would Invoke the GroupBy of IQueryable with T and string via reflection
}





dimanche 30 octobre 2016

Java Reflection with Client Written in Java

this might be a little too specific but I'd figure I'd ask anyway.

I'm aware of how to use reflection in a pretty general sense. I'm also aware of people being able to use reflection to get classes from a client and then pull values from them.

My goal is to be able to pull classes and player data from the Old School Runescape client. Most people do this to make bots, others to make clients to play in. My goal is to just learn about it and possibly make a client to play in, but mostly just curiosity and to learn.

I've tried looking for results on how people use reflection to create bots or interact with the runescape client in any way, but all I have found have not been helpful.

The biggest challenge I face (and maybe this is super simple), is how to even grab the classes from the client. How would one go about even just loading a window via Java, and being able to play the game inside that window? This is the least of my problems but I guess it's a starting point. (I haven't looked this up since it seems like it will probably be trivial).

In all, I'm really just looking for a pretty basic way to grab the classes from the client. I believe that if I got this far I could then start getting other information, but since I don't even have this basic ability down, I feel as though I'm completely lost and can't even start!

I've seen reflection code that loads a java class, but I don't even know where I would find the OSRS java class to use, or how I would hook up my program to read this class from the existing OSRS client.

Appreciate any help.





The AnnotatedType seems not work with ExistentialType in the scala runtime reflection

package noddle.test

object Entice with App {
  import scala.reflect.runtime.universe
  import scala.reflect.runtime.universe._

  val mir = universe.runtimeMirror(getClass.getClassLoader)
  val bootModule = mir.staticModule("noddle.test.Entice")

  def normal(x: (List[T] forSome { type T }) @SerialVersionUID(123456) with Int {def y: Int} ) = ???
  println(bootModule.info.member(TermName("normal")).info.paramLists.head.head.info.asInstanceOf[RefinedType].parents.head.getClass)

}

The output is class scala.reflect.internal.Types$ExistentialType, But If i change the normal method like this:

def normal(x: (List[Int] {def noway: String}) @SerialVersionUID(123456) with Int {def y: Int}) = ???

The output is class scala.reflect.internal.Types$AnnotatedType.

I can't understand why the output is ExistentialType in the fisrt code snippet, who can tell why?





Are there any existing libraries for side-by-side testing of java methods? [on hold]

I'm refactoring an old utility class, and I want to make sure I haven't broken the method contract at all. To that end, I'm trying to call both methods with identical inputs (generated by QuickCheck) and compare both the resulting output, but any side-effects applied to the input, or exceptions thrown.

The code to do this for each method would be quite a bit to copy-paste, and I'm sure it can be done "better" with a reflection-based utility utilising mocks and/or spies.

import java.util.Date;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

...

@Property
public void testDateAdd(
        Date date,
        Integer amount,
        @InRange(minInt = 0, maxInt = 15) Integer field

) throws Exception {

    final Date date1 = new Date(date.getTime());
    final Integer amount1 = new Integer(amount);
    final Integer field1 = new Integer(field1);
    Date result1 = null;
    Exception error1 = null;

    try {
        result1 = DateFunctionsOriginal.dateAdd(date1, amount1, field1);

    } catch (Exception error) {
        error1 = error;
    }

    final Date date2 = new Date(date.getTime());
    final Integer amount2 = new Integer(amount);
    final Integer field2 = new Integer(field1);
    Date result2 = null;
    Exception error2 = null;

    try {
        result2 = DateFunctions.dateAdd(date2, amount2, field2);

    } catch (Exception error) {
        error2 = error;
    }

    assertThat(date1, is(equalTo(date2)));
    assertThat(amount1, is(equalTo(amount2)));
    assertThat(field1, is(equalTo(field2)));
    assertThat(error1, error2 == null ? is(nullValue()) : isA(error2.getClass()));
    assertThat(result1, is(equalTo(result2)));

}

Not perfect, but that's what I'm looking at for all 200 or so methods, and while I love a good challenge, I'd like to avoid 'rolling my own' if I can help it.





PHP. Can i make Reflection use autoload?

Now I need to instantiate a lot of classes with Reflection. There are different namespaces with a special classes with same names but different parameters. Each namespace contain Super class which run other special classes with the same way - reflection. I can add param to the super class what namespace I should use, but it would be more comfortable if I include in use section of my file all classes I want use in Reflection.

Any ideas?





Get class from Object in the run time in scala

import org.apache.spark.sql.types.StructField
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.types.StringType
import org.apache.spark.sql.type.NumericType
import org.apache.spark.sql.type.BooleanType
   ....
   ....
val TableSchema = Array(
      ("ID", IntegerType),
      ("Name", StringType),
      ("TNum", integerType),
      ("Handled", BooleanType),
      ("Value", StringType)
      )

I have an array of schema information of a table and I am attempting to map it to a struct that can be used in the spark dataframe creation. The array after transformation should be as below:

val struct = Array(
 StructField("ID", NumericType),
 StructField("Name", BooleanType),
 StructField("TNum", NumericType),
 StructField("Handled", BooleanType),
 StructField("Value", StringType))

So I am trying to write a method that convert each element to a StructField. This is my attempt:

    def mapToStruct(arr:Array[(String, String, Object)])={
     val newArr = arr.map(ele => StructField(ele._1, ele._2))
     newArr
   }

In this situation, I cannot get the class of StringType, BooleanType or IntegerType from the third parameter of method mapToStruct. Exception I got is type mismatch; found : Object required: org.apache.spark.sql.types.DataType. But if I change the parameter type to Array[(String, String, DataType)], it does not match the variable type.

My question is what datatype I should choose for the third parameter of method mapToStruct and then I can get the class of this object at run time.
thanks in advance.





Best way to use reflection

My application pays a performance penalty because I'm using reflection, specifically to get attributes for classes and properties.

In order to optimize my application I want to generate a library that is based on the reflection but replacing it at runtime.

Today I use something like:

MyAttribute[] attributes = (MyAttribute[])Attribute.GetCustomAttributes(typeof(CurrentNamespace.MyClass), typeof(MyAttribute));
var x = GetX(attributes);

I can generate a class with the same class name in a different namespace and call it statically.

MyReflectingClassInterface reflectingClass = getClassFromAssembly("ReflectingNamespace.MyClass");
var x = reflectingClass.getX(); // can't be static if I want to use interface.

Or, Maybe the best way is to use one static switch:

static public X getX(Type type){
    if(type == typeof(CurrentNamespace.MyClass))
        return new X(5); // hard coded answer
}





How to get a byte pointer to a value of any data type in Golang?

I've managed to get the following function working in Go. But I want to optimize/generalize the code such that this function would return me a pointer to the first byte of any value I pass into the function. Currently it will only work for []uint32, but I want to use it to get the starting memory address as a *byte for many other types (i.e. byte[], int[], string, etc).

Is there a more generic way to do this rather than catching every single type I need to address as case statements?

Go Playground Link for below code: http://ift.tt/2f5Br0G

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

func ToBytePointer(data interface{}) *byte {
    fmt.Println("Received type is", reflect.TypeOf(data))

    switch data.(type) {
    case []uint32:
        typedData := data.([]uint32)
        return (*byte)(unsafe.Pointer(&typedData[0]))
    default:
        return nil
    }
}

func main() {
    var data = []uint32{1, 2, 3}
    var dataBytePointer = (*byte)(unsafe.Pointer(&data[0]))

    fmt.Println(dataBytePointer, ToBytePointer(data))
}





Change @PropertySource value in run time

How can I change the value of @PropertySource in run time when the junit test class runs. For example,

I want to replace the value of below,

@PropertySource(value = "file:${app.deploy.env}/sample/mine.properties", ignoreResourceNotFound = true)

with

value = "classpath:sample/mine.properties"

when junit test runs.





samedi 29 octobre 2016

Getting class name from Field's name,Java relfection [duplicate]

This question already has an answer here:

Is there a way to get Class name if i only have field's name. I am using java reflection. Please think before marking as duplicate, i only have String type name of field nothing else.





C# how to load assembly with reflection

I am trying to load an assembly, System.Speech, via reflection, so that I can use the SpeakAsync method to read aloud some text.

I wrote this:

System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom("System.Speech.dll");
System.Type type = assembly.GetType("System.Speech.SpeechSynthesizer");
var methodinfo = type.GetMethod("SpeakAsync", new System.Type[] {typeof(string)} );
if (methodinfo == null) throw new System.Exception("No methodinfo.");

object[] speechparameters = new object[1];
speechparameters[0] = GetVerbatim(text); // returns something like "+100"

var o = System.Activator.CreateInstance(type);
methodinfo.Invoke(o, speechparameters);

But get the error

System.NullReferenceException: Object reference not set to an instance of an object





How to access a value of a private variable of a class1 when the class1 object is privately declared in another class2?

I am trying to access private field of department after passing course as an object to function. Department is a private variable in course. The solution needs to be generic as this is a reflection exercise. this is department class:

public class Department{
private String departmentName;
private Teacher departmentHOD;
}

this is Course class:

public class Course {
private String courseNumber;
private String semesterName;
private String courseName;
private Department offeringDepartment;
private Teacher[] courseInstructors;
private int sectionNumbers;
}

in main I pass course in a function void storeObject(Object o):

void storeObject(Object o)
{
 //in this function i need to extract all possible primitive datatype objects and save them in a data base
Class classForStorage = o.getClass();
Field[] publicFields = classForStorage.getDeclaredFields();//.getFields()
    for (int i = 0; i < publicFields.length; i++) 
    {   //  making private ones accessible
        publicFields[i].setAccessible(true);
        //Getting name and type of all attributes in the class one by one
        String fieldName = publicFields[i].getName();
        Class typeClass = publicFields[i].getType();
        String fieldType = typeClass.getName();
       ......//after this i access values by datatype and store in sql
       //but it only works for primitive data types
    }

I cant access departname using something like:

  publicFields[i].getType().getDeclaredFields()[0].setAccessible(true);
  value =(String)publicFields[i].getType().getDeclaredFields()[0].get(obj); 

this gives me illegal access exception

On a side note how can get values from the courseInstructor array.





vendredi 28 octobre 2016

Reflexil is unable to save this assembly

I am trying to understand the .NET Reflector. whenever i modify my Console application code and save the assembly it throws the exception Reflexil is unable to save this assembly: Object Reference not set to an instance of an object.
Please let me know what am I doing wrong. Thanks in Advance!





is type derived from DataContext?

Given:

private T SomeFunction<T>(T obj)

Is it possible to test if the passed object type T is derived from a DataContext?

EG this returned object would test for True:

using(var db = new DBContext())
{
    return db.Table.First();
}





How to set nested property value using FastMember

I get an exception when I try to set a nested member Property using FastMember. For example when having these classes

public class A
{
    public B First {get; set;}
}

public class B
{
    public string Second {get; set;}
}

and I want to set First.Second of an instance to "hello".

var b = new B{ Second = "some value here" }; var a = new A{ First = b };

var accessor = ObjectAccessor.Create(a); accessor["First.Second"] = value; // this does not work and gives ArgumentOutOfRangeException

I can't split it up into ["First"]["Second"] because I don't know the depth at this point. Is there a magical access for nested properties or do I have to split the hierarchy myself?





Force AssemblyResolve

I set my AppDomain.CurrentDomain.AssemblyResolve handler but this event doesn't fire if the assembly that was intended to be loaded exists in the current directory. This is expected.

I am aware that if I remove the assembly from the current directory my event will be fired - expected as well. But I don't want to remove the file. How can I programmatically force this event to be fired without touching the existing assembly file?

Or, in other words: how can I load the assembly that I want without deleting the existing other assembly file, without installing stuff in the gac and without adding an XML file with redirection? (but if something like that can be done programmatically that's ok)





How to access internal telephony functionality of android 6.0 using java reflection?

I am trying to access some internal telephony methods.

TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    try {
        Class telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
        Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
        getITelephonyMethod.setAccessible(true);


        Class ITelephonyClass = Class.forName(getITelephonyMethod.invoke(telephonyManager).getClass().getName());
        Method[] methods = ITelephonyClass.getDeclaredMethods();
        for (Method method : methods) {
            Log.i("Method", "Method name is: "+method.getName());
        }
        //ITelephonyClass.getMethod("isVolteAvailable",void.class).invoke(null,"");
        Method getInstanceMethod = ITelephonyClass.getDeclaredMethod("isVolteAvailable");
        getInstanceMethod.setAccessible(true);
        Object res = getInstanceMethod.invoke(null);
        boolean result = ((Boolean) res).booleanValue();

    }catch (Exception e){
        //newtext.setText(e.getMessage());
        Log.i("Exception", "Exception: "+e.getMessage());
        e.printStackTrace();
    }

Above code snippet is from Activity class. And permissions are given bellow

<uses-permission android:name="android.permission.MODIFY_PHONE_STATE"/>

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

But code is not giving the expected output.





How to assign a value to a nullable through reflection

How do I set a Nullable<T> value through reflection? I was able to set values that are not Nullable<T> and detect if a type is of type Nullable<T> but I don't find a way how to set this value properly.

This is the current snippet:

public bool SetProperty(string propertyLambdaString, object value)
{
    try
    {
        ParameterExpression paramParty = Expression.Parameter(typeof(TModel), "model");
        MemberExpression property = BuildPropertyExpression(paramParty, propertyLambdaString);
        ParameterExpression paramValue = Expression.Parameter(value.GetType(), "value");

        if (Nullable.GetUnderlyingType(property.Type) != null)
        {
            // TODO: Question: How to assign a value to a nullable? Assign throws exception.
            //Expression assignmentExp = Expression.Assign(property, paramValue);
            //LambdaExpression lambda = Expression.Lambda(
            //  assignmentExp,
            //  new List<ParameterExpression> { paramParty, paramValue });
            //lambda.Compile().DynamicInvoke(this.model, value);

            return false;
        }

        // TODO: Question: How to set a value to null?
        Expression assignmentExp = Expression.Assign(property, paramValue);
        LambdaExpression lambda = Expression.Lambda(
            assignmentExp,
            new List<ParameterExpression> { paramParty, paramValue });
        lambda.Compile().DynamicInvoke(this.model, value);
    }
    catch (Exception exception)
    {
        Logger.Error(exception);
        return false;
    }

    return true;
}

private static MemberExpression BuildPropertyExpression(Expression param, string propertyLambdaString)
{
    int firstDelim = propertyLambdaString.IndexOf('.');
    if (firstDelim < 0)
    {
        return Expression.Property(param, propertyLambdaString);
    }

    string head = propertyLambdaString.Substring(0, firstDelim);
    string tail = propertyLambdaString.Substring(firstDelim + 1);
    MemberExpression expr = BuildPropertyExpression(param, head);
    return BuildPropertyExpression(expr, tail);
}





jeudi 27 octobre 2016

TypeScirpt: Class generics - something like Java's Class

I have a TypeScript code that processes classes (OGM framework).

There is a base class for models/entities, say, BaseModel. However, I would like to support several different base models, e.g. ProxiedBaseModel and DecoratedBaseModel.

The issue is:

export abstract class DiscriminatorMapping<BaseModelT>
{
    public static getMapping() : 
        { [key: string]: typeof BaseModelT } 
    { ... }

This is a simple dictionary-like class.
It needs a map of string <-> class.
And typeof BaseModelT obviously doesn't work as TypeScript can't know what type will come in.

How should I express that the class type parameter takes something that is a class?
I already know how to represent the type of any class, that's { new (): <any> }. But I don't know how to apply it here:

class DiscriminatorMapping<BaseModelT extends { new (): <any> }>

Maybe I should introduce some type alias?





Why are identical types not equal?

I was developing a small plugin framework and noticed that I couldn't successfully use Type.IsAssignableFrom() to check if a plugin class implements the type IPlugin. I had checked other SO questions (such as this) to see why the function returned false, but to my surprise, none of the suggestions worked.

I had a class inside a plugin assembly which implements the PluginAPI.IPlugin class in a referenced assembly. When checking the AssemblyQualifiedName for both my PluginAPI.IPlugin type as well as the types for the plugin class's list of interfaces, I found no difference whatsoever. Both outputed the value:

PluginAPI.IPlugin, PluginAPI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

Upon further investigation, I checked Type.cs source and found that the function IsAssignableFrom() was failing in an internal call where it checks for type equality (via ==).

I had found that modifying my plugin framework to load plugin assemblies in a typical execution context (Assembly.LoadFrom) as opposed to a reflection only context (Assembly.ReflectionOnlyLoadFrom) allowed the type equality check to evaluate to true, which is what I had expected all along.

Why is it that the reflection-only context causes the types to no longer be equal?


Code:

The following section contains relevant code for reproducing the problem as well as description on the projects were set up.

Assembly 1: PluginAPI

This assembly only contains IPlugin.cs:

namespace PluginAPI
{
    public interface IPlugin
    {
    }
}

Assembly 2: Plugin1

This assembly contains several plugins (classes that implement PluginAPI.IPlugin). There is Calculator.cs and WPFPlugin1.cs

namespace Plugin1
{
    public class Calculator : IPlugin
    {
        public Calculator()
        {

        }
    }
}

namespace Plugin1
{
    public class WPFPlugin1 : IPlugin
    {
        public WPFPlugin1()
        {

        }
    }
}

Assembly 3: AppDomainTest

This assembly contains the entry point and tests loading the plugin assemblies in a separate AppDomain so they can be unloaded.

namespace AppDomainTest
{
    public class AppDomainTest
    {
        public static void Main(String[] args)
        {
            AppDomain pluginInspectionDomain = AppDomain.CreateDomain("PluginInspectionDomain");
            PluginInspector inspector = new PluginInspector();
            pluginInspectionDomain.DoCallBack(inspector.Callback);
            AppDomain.Unload(pluginInspectionDomain);

            Console.ReadKey();
        }
    }
}

namespace AppDomainTest
{
    [Serializable]
    public class PluginInspector
    {
        public void Callback()
        {
            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomain_ReflectionOnlyAssemblyResolve;

            //TODO: Change this to the output directory of the Plugin1.dll.
            string PluginDirectory = @"H:\Projects\SOTest\Plugin1\bin\Debug";
            DirectoryInfo dir = new DirectoryInfo(PluginDirectory);
            if (dir.Exists)
            {
                FileInfo[] dlls = dir.GetFiles("*.dll");

                //Check if the dll has a "Plugin.config" and if it has any plugins.
                foreach (FileInfo dll in dlls)
                {
                    Console.WriteLine(String.Format("DLL Found: {0}", dll.FullName));
                    LoadAssembly(dll.FullName);
                }
            }

            AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CurrentDomain_ReflectionOnlyAssemblyResolve;
        }

        private void LoadAssembly(string path)
        {
            Console.WriteLine(String.Format("\tLoading Assembly"));

            //From within the PluginInspectionDomain, load the assembly in a reflection only context.
            Assembly[] loadedAssemblies = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies();
            //Assembly[] loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
            AssemblyName assemblyName = AssemblyName.GetAssemblyName(path);
            bool assemblyAlreadyLoaded = loadedAssemblies.Any(new Func<Assembly, bool>((Assembly a) =>
            {
                //If the assembly full names match, then they are identical.
                return (assemblyName.FullName.Equals(a.FullName));
            }));
            if (assemblyAlreadyLoaded)
            {
                Console.WriteLine("Assembly already loaded: {0}, exiting function early.", assemblyName.FullName);
                return;
            }

            //Assembly not already loaded, check to see if it has any plugins.
            Assembly assembly = Assembly.ReflectionOnlyLoadFrom(path);
            //Assembly assembly = Assembly.LoadFrom(path);
            GetPlugins(assembly);
        }

        private Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
        {
            Console.WriteLine("Resolving assembly: {0}", args.Name);

            //This callback is called each time the current AppDomain attempts to resolve an assembly.
            //Make sure we check for any plugins in the referenced assembly.
            Assembly assembly = Assembly.ReflectionOnlyLoad(args.Name);
            //Assembly assembly = Assembly.Load(args.Name);
            if (assembly == null)
            {
                throw new TypeLoadException("Could not load assembly: " + args.Name);
            }
            GetPlugins(assembly);
            return assembly;
        }

        /// <summary>
        /// This function takes an assembly and extracts the Plugin.config file and parses it
        /// to determine which plugins are included in the assembly and to check if they point to a valid main class.
        /// </summary>
        /// <param name="assembly"></param>
        public List<IPlugin> GetPlugins(Assembly assembly)
        {
            Console.WriteLine("Searching for plugins inside assembly: " + assembly.FullName);
            using (Stream resource = assembly.GetManifestResourceStream(assembly.GetName().Name + ".Plugin.config"))
            {
                if (resource != null)
                {
                    //For brevity I have ommitted the types PluginConfiguration and Plugin from the PluginAPI assembly
                    //since they are only container classes generated from XML that have string properties.
                    //These are used to find which classes should be checked for implementing IPlugin.
                    //Parse the Plugin.config file.
                    XmlSerializer serializer = new XmlSerializer(typeof(PluginConfiguration));
                    PluginConfiguration configuration = (PluginConfiguration)serializer.Deserialize(resource);
                    if (configuration == null)
                    {
                        Console.WriteLine("Configuration is null.");
                    }
                    if (configuration.Plugins == null)
                    {
                        Console.WriteLine("Could not find any plugins.  It's null.");
                    }

                    Console.WriteLine();
                    foreach (Type type in assembly.GetExportedTypes())
                    {
                        Console.WriteLine("Type: FullName=\"{0}\"", type.FullName);
                    }


                    Console.WriteLine("\nAuthor: {0}\tVersion: {1}", configuration.Author, configuration.Version);
                    Console.WriteLine("========================================");
                    foreach (Plugin pluginDescriptor in configuration.Plugins)
                    {
                        Console.WriteLine(String.Format("Plugin: Name={0}, MainClass={1}", pluginDescriptor.Name, pluginDescriptor.MainClass));

                        bool containsType = false;
                        foreach (Type type in assembly.GetExportedTypes())
                        {
                            if (type.FullName.Equals(pluginDescriptor.MainClass))
                            {
                                containsType = true;
                                if (typeof(IPlugin).IsAssignableFrom(type))
                                {
                                    Console.WriteLine("MainClass \'{0}\' implements PluginAPI.IPlugin", pluginDescriptor.MainClass);
                                }

                                Console.WriteLine("Checking for {0}", typeof(IPlugin).AssemblyQualifiedName);
                                Console.WriteLine("Interfaces:");
                                foreach (Type interfaceType in type.GetInterfaces())
                                {
                                    Console.WriteLine("> {0}", interfaceType.AssemblyQualifiedName);
                                    if (interfaceType == typeof(IPlugin))
                                    {
                                        //This is NOT executed if in reflection-only context.
                                        Console.WriteLine("interface is equal to IPlugin");
                                    }
                                }
                            }
                        }

                        Console.WriteLine((containsType ? "Found \'" + pluginDescriptor.MainClass + "\' inside assembly.  Plugin is available." : "The MainClass type could not be resolved.  Plugin unavailable."));
                    }
                }
            }
            Console.WriteLine("Done searching for plugins inside assembly: " + assembly.FullName + "\n");
            return null;
        }
    }
}





How can I programmatically retrieve an EventInfo for an event without hard coding its name?

Given an interface:

IEventProvider
{
    event EventHandler<string> StringAvailable;

    void RequestString();
}

I want to retrieve an EventInfo for StringAvailable through some method that can be called like this: EventInfo ei = GetEventInfo(providerInstance.StringAvailable) or something to that effect. I don't want to have to pass a string containing its name.

I've tried to abuse lambdas and expression trees to extract the name of the event being passed in but to no avail. Because events are not first class members in C# this is proving to be difficult. I just help finding a way to get the name of the event at run-time with code that can be statically validated by the compiler to ensure the event exists at compile time.

My workaround right now is to remove all of the events from the classes I want to work with and change them to Action<T>. This is less than ideal though.

For those of you wondering why I'm doing this, I want to allow classes that use the event based asynchronous pattern to be adapted to async/await automatically at run-time using IL generation. In my example interface above, the adapter would wrap RequestString and StringAvailable and expose public async Task<string> RequestStringAsync() using DynamicMethod.





Iterating over all class properties

maybe quite a simple question but i have an initilised class object that is passed via parameter to another class. The class object is then read to check the values of its members and possibly alter them if incorrect.

I can access iondividual properties and change thier values but what i want to do is loop through all the integer type properties to check thier base value and alter it where neccesary.

Here is an example of the object structure:

+ Prices
++ MainPrices
+++ RelevantPrices
++++ (Int) Price

+ SubPrices
++ MainPrices
+++ RelevantPrices
++++ (Int) Price

+Rooms
++ Data
+++ (String) Name
+++ (Int) NameType
+++ (String) Location
+++ (Int) RoomNumber

What i need to do here is get Rooms.Data and loop over all its Int type parameters. I've tried using reflection but for that i require a new instance reference for the type, all i have is the initialised class object here.

Can anyone advise what might be the best way to loop over and conditionally change thier existing values please?





AutoMapper ignore member failing when mapping with Type objects

Using AutoMapper, I'm trying to map two types that I pull from two different assemblies via reflection. However, when working with Types, I am unable to get the .ForMember() method to ignore any members that I specify. The regular lambda syntax does not compile because the member name is not found on the Type type of the class. Passing in a string of the member allows compilation, but still does not ignore the member.

class ExampleSchema
{
    int Age {get; set;}
}

class ExampleDto
{
    int Age {get; set;}
    int Weight {get; set;}
}

var schemaType = typeof(ExampleSchema);
var dtoType = typeof(ExampleDto);

// This will throw
// Cannot convert lambda expression to string because it is not a delegate type
cfg.CreateMap(schemaType, dtoType)
    .ForMember(dest => dest., opt => opt.Ignore());

// Hard-code cringing aside, this still does not filter out the member
cfg.CreateMap(schemaType, dtoType)
    .ForMember("Weight", opt => opt.Ignore());  

Is this a bug in AutoMapper or am I just using the method incorrectly?





SecurityException when executing reflected method in sandbox AppDomain

I am using a separate AppDomain as a sandbox, and trying to execute a method that is constructed via reflection.

When the method is invoked, a SecurityException is thrown, even though the sandbox AppDomain has ReflectionPermission(PermissionState.Unrestricted) set on its PermissionSet.

The invocation does work when the PermissionSet is set to PermissionState.Unrestricted, but that defeats the purpose of a sandbox.

Here's an example that demonstrates the issue:

using System;
using System.Security;
using System.Security.Permissions;

namespace ConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person();
            var program = new Program();

            var customDomain = program.CreateDomain();
            var result = program.Execute(customDomain, (x) =>
            {
                var type = x.GetType();
                var propertyInfo = type.GetProperty("Name");
                var method = propertyInfo.GetMethod;
                var res = method.Invoke(x, null) as string;
                return res;
            }, person);
            Console.WriteLine(result);
            Console.ReadLine();
        }

        public object Execute(AppDomain domain, Func<object, object> toExecute, params object[] parameters)
        {
            var proxy = new Proxy(toExecute, parameters);
            var result = proxy.Invoke(domain);
            return result;
        }

        private AppDomain CreateDomain()
        {
            var appDomainSetup = new AppDomainSetup()
            {
                ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
                ApplicationName = "UntrustedAppDomain"
            };

            // Set up permissions
            var permissionSet = new PermissionSet(PermissionState.None);
            permissionSet.AddPermission(new SecurityPermission(PermissionState.Unrestricted));
            permissionSet.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));

            // Create the app domain.
            return AppDomain.CreateDomain("UntrustedAppDomain", null, appDomainSetup, permissionSet);
        }

        private sealed class Proxy : MarshalByRefObject
        {
            private Delegate method;
            private object[] args;
            private object result;

            public Proxy(Delegate method, params object[] parameters)
            {
                this.method = method;
                this.args = parameters;
            }

            public object Invoke(AppDomain customDomain)
            {
                customDomain.DoCallBack(Execute);
                return this.result;
            }

            private void Execute()
            {
                this.result = this.method.DynamicInvoke(this.args);
            }
        }
    }

    public class Person
    {
        public Person()
        {
            this.Name = "Test Person";
        }

        public string Name { get; set; }
    }
}





How to call an overriden method using reflection?

Consider we have the following:

 class Base { def name = "Base" }
 class Successor extends Base {
    override def name = "Successor"
 }

I have tried to do the following (took from How to call a superclass method using Java reflection):

import java.lang.invoke.{MethodHandles, MethodHandle, MethodType}

object TestApp {
    def main(args: Array[String]) {
        val a = new Successor;
        val h1 = MethodHandles.lookup().findSpecial(classOf[Base],
                                                    "name",
                                                    MethodType.methodType(classOf[String]),
                                                    classOf[Successor]);
        println(h1.invoke(a));
    }
}

but I get a runtime exception:

java.lang.IllegalAccessException: no private access for invokespecial: class Successor, from TestApp$

I was told that it is possible that Java reflection may not work correctly for Scala. Is it true? Or I simply do something wrong?





mercredi 26 octobre 2016

Kotlin. How to check if the field is nullable via reflection?

I'm developing a code generator that takes the data from the classes during runtime. This generator is designed to work only with Kotlin. At the moment, I was faced with the problem, as I don't know how to check if the field is nullable.

So the main question is how to implement this check via reflection?





How is BRDF usually implemented?

I have a small path tracer, and I am trying to figure out how to implement some basic BRDFs. Here's a brief description of the pipeline I use (without recursion):

1) For each pixel:
   1.1) For each sample:
      1.1.1) I construct a path.
      1.1.2) I calculate the contribution of this path.
      1.1.3) I calculate the "probability" of this path.
      1.1.4) Finally, I calculate the overall color value(taking into account number of samples, "probability" and contribution of the path).
   1.2) Take the sum of all samples' values and write it to the pixel.

So, I calculate the direction of reflected rays in the step 1.1.1) I construct a path. For now, I have implemented diffuse reflection, specular reflection, glossy reflection, refraction. Now I want to implement a complex BRDF, let's say Cook-Torrance BRDF. I see that it contains several components (diffuse reflection and specular reflection). How should I trace these rays to get the combination? Should I choose between diffuse_ray/specular_ray randomly and then accumulate the values as usual?(like, if a random value is more than 0.5 then I trace a diffuse ray, otherwise - specular) Or should I trace multiple rays from each intersection?

How is it usually implemented in physically-based renderers?

P.S. If somebody knows some good articles on this topic I would be glad to see them. I tried to read pbrt but it seems very complex and huge for me. And some things there are implemented differently, like the camera model and other stuff.





How to assert ast.TypeSpec to int type in Golang?

I have following code for Golang docs parsing. "ts" is ast.TypeSpec. I can check StructType and etc. But, ts.Type is "int". How can I assert for int and other basic type?

ts, ok := d.Decl.(*ast.TypeSpec)
switch ts.Type.(type) {
case *ast.StructType:
    fmt.Println("StructType")
case *ast.ArrayType:
    fmt.Println("ArrayType")
case *ast.InterfaceType:
    fmt.Println("InterfaceType")
case *ast.MapType:
    fmt.Println("MapType")
}





Generating DLL assembly at run time and change it?

i created a dll contains a class named PersonVM like what you see below. and its working ...

  public ActionResult Index()

    {


        using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
        {
            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.OutputAssembly = "Per.dll";
            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, "public class PersonVM{ " + "public int id{get;set;}" +
                "public string Name{get;set;}" + "public string LName{get;set;}" + " }");
        }

        Assembly assembly = Assembly.LoadFrom("Per.dll");
        var type = assembly.GetType("PersonVM");
        var d = type.GetProperties();
        object obj = Activator.CreateInstance(type, true);
        return View(obj);


    }

but this code is working just one time in my index controller. for example its not changing my dll class in here:

     public ActionResult Conf()

    {
        using (CSharpCodeProvider codeProvider = new CSharpCodeProvider())
        {
            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.OutputAssembly = "Per.dll";

            CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, "public class PersonVM{ " + "public int id{get;set;}" +
              "public string Name{get;set;}" + "public string LName{get;set;}" + "public string LNamee2 { get; set; }" + "public string L4 { get; set; }" + " }");
        }


        Assembly assembly = Assembly.LoadFrom("Per.dll");
        var type = assembly.GetType("PersonVM");


        object obj = Activator.CreateInstance(type, true);



        List<ClassInfoVM> model = obj.GetType().GetProperties()
            .Select(T => new ClassInfoVM()
            {
                PropName = T.Name,

                TypeOfProp = T.PropertyType.Name

            }).ToList();


        return View(model);
    }

there is no thing about any error.. it just doesn't changing my dll class...the dll class PersonVM is just contains the properties which i was set it, first time in Index





C# Generic method to get property values with Linq Expression and reflection

Dear Gods of Reflection

I would like to have a generic GetValue<TEntity, T> method that can return the following property values given the following User class:

public class User  
{
   public int Id { get; set; }
   public int ClientId { get; set; }
   public string UserName { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string MobileNumber { get; set; }   
   public bool IsActive { get; set; }

   public Client Client { get; set; }
   public List<Package> Packages { get; set; }

 }

Example usage of what GetValue<TEntity, T> should be able to do:

  var firstName = dataCollector.GetValue<User, string>(x => x.FirstName);
  var client = dataCollector.GetValue<User, Client>(x => x.Client);
  var packages = dataCollector.GetValue<User, List<Package>>(x => x.Packages);

  var packageFirst = dataCollector.GetValue<User, Package>(x => x.Packages[0]);
  var packageName = dataCollector.GetValue<User, string>(x => x.Packages[0].Name);
  var clientName = dataCollector.GetValue<User, string>(x => x.Client.Name);

So far I have the following method which works for the first 3 scenarios:

 public T GetValue<TEntity, T>(Expression<Func<TEntity, T>> propertyExpression) where TEntity : class
 {
    var response = _responses.FirstOrDefault(p => p.GetType() == typeof(TEntity)) as TEntity;
    if (response != null)
    {
       var expr = (MemberExpression)propertyExpression.Body;
       var prop = (PropertyInfo)expr.Member;
       return (T)prop.GetValue(response);
    }
    return default(T);
  }

But it does not work for the last 3 scenarios:

  var packageFirst = dataCollector.GetValue<User, Package>(x => x.Packages[0]);
  var packageName = dataCollector.GetValue<User, string>(x => x.Packages[0].Name);
  var clientName = dataCollector.GetValue<User, string>(x => x.Client.Name);

What changes do I need to make to the method?

I shall now sacrifice a USB flash drive whilst awaiting your answers :)





Decorate all properties with type metadata in TypeScript

Given this code:

class Foo {
    text: String;
}

TypeScript will produce this JavaScript:

var Foo = (function () {
    function Foo() {
    }
    return Foo;
}());

But if I decorate text with any decorator, such as function bar(t, k) {} like this:

class Foo {
    @bar text: String;
}

TypeScript will produce:

var Foo = (function () {
    function Foo() {
    }
    __decorate([
        bar, 
        __metadata('design:type', String)
    ], Foo.prototype, "text", void 0);
    return Foo;
}());

That is, it decorates text with the bar function and with design:type metadata. This is great, but I'd like to instruct TypeScript to decorate all properties with design:type metadata, without the need of a bogus decorator like @bar.

Is it possibile in the latest TypeScript?





Instantiating a class with reflection vs from variable

I am wondering why one would choose reflection over instantiating simply by variable in these 2 scenarios for the FactoryAbstract.

Concrete class

class Factory extends FactoryAbstract
{
    const CONSTANT = '\Namespace\Sub\Sub';
}

FactoryAbstract 1

abstract class FactoryAbstract
{
    public function __construct()
    {
        $className = $this::CONSTANT;
        $instance = new ReflectionClass($className);

        if (!$instance->isSubclassOf('\\Namspace\\Sub\\Whatever')) {
            throw new LogicException('Concrete implementation must be a subclass of the Whatever class');
        }
    }
}

FactoryAbstract 2

abstract class FactoryAbstract
{
    public function __construct()
    {
        $className = $this::CONSTANT;
        $instance = new $className();

        if (!is_subclass_of($instance, '\\Namspace\\Sub\\Whatever')) {
            throw new LogicException('Concrete implementation must be a subclass of the Whatever class');
        }
    }
}

This is not tested code but a simple code gist, in the second example you have to strip the leading backslash for it to even work, etc.

What is the advantage of using reflection like in the FactoryAbstract of the first example?

I know reflection is resource intensive and it is better to stay away from it whenever you can but I am wondering if there is a big performance difference between instantiating a reflection class vs instantiating from a variable.

It seems like in the first example(which is in the code base) there is no advantage to using a reflection class since the is_subclass_of method is available a function as well besides the reflection API.

Hopefully my examples are clear enough, if you need some more information let me know.





Android:Method Callback is not working

I am trying to implement method callback using relection but it is not calling the desired method.Here is my main activity

public class MainActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RetrofitCalls retrofitCalls = new RetrofitCalls();
        retrofitCalls.requestAccesstoken();
        retrofitCalls.requestDataFromServer(MainActivity.this,"onCountryListReceived");
    }

    public void onCountryListReceived()
    {
        String temp = "hello";
    }
}

and here is the requestDataServer method

 public void requestDataFromServer(final Activity activity, final String callBackMethod){

    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(new HeaderInterceptor())
            .build();

    retrofit = new Retrofit.Builder()
            .baseUrl(Constants.ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build();

    Api api = retrofit.create(Api.class);
    Call<JsonObject> call = api.getDataFromServer(Constants.COUNTRY_LIST);
    call.enqueue(new Callback<JsonObject>() {
        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {

            if(response.errorBody() != null){
                try {
                    String j1 = response.errorBody().string();
                    String temp = "hello";
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }else if(response.body() != null) {
                JsonObject jsonObject = response.body();
                JsonArray jsonArray = jsonObject.getAsJsonArray("Data");
                String temp = "hello";

                try {
                    String x = activity.getClass().toString();
                    Method method = activity.getClass().getDeclaredMethod(callBackMethod.trim(),Object.class);
                    method.invoke(activity);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            String temp = "hello";
        }
    });
}

why the onCountryListReceived is not invoked? It is giving NoSuchMethodException. What's the problem?





mardi 25 octobre 2016

How to reuse property fetched using Reflection

private static string GenerateStr<T>(IList<T> obj, string propName)
{
  string str = string.Empty;
  foreach(var o in obj)
  {
      str += o.GetType().GetProperty(propName).GetValue(o, null); 
          //is there a way to only call above line once, then call
          // str =+ o.myStrProp over the course of the iteration?

  }
  return str;
}

Is there a way to be able to reuse the fetched property to refrain from relying on Reflection to do it again for me. Thanks!





Could not load type 'Sitecore.Reflection.INexusDataApiEx' from assembly 'Sitecore.Kernel,

I am getting this runtime error and can not find anything on the internet around this reference. 'Sitecore.Reflection.INexusDataApiEx'

Any assistance would be greatly appreciated.

Error message





TypeScript - set artificial object to certain class

I am writing a code that handles classes instantiation (unmarshaller).

First, I create an object. I do that using let obj = new BaseModel.
During processing of the input data, I eventually figure out the class of the unmarshalled object.
I have that class, in terms of <T extends BaseModel> clazz : { new (): T }.

Now I would like to change the class of the object created earlier, in a way that it doesn't collide with TypeScripts class handling code.

Is setting the obj.__proto__.constructor = clazz the right way? Or perhaps is there a construct in TypeScript that would do this in more future-compatible way?





Building OrderBy-expression at runtime by property-name which can be nested

How can I dynamically build an order-by expression when only knowing the name of the property (or even the name of a sub-property)?

What I'm trying to achieve is something like:

dbResult = // some database-query as IQueryable<TSource> which is not yet executed;

if (!string.IsNullOrEmpty(request.OrderBy)) { // the user want's to group the results
    var grouped = dbResult.GroupBy(/* this should be build dynamically */);
}

I need something to start with as GroupBy is awaiting a Func<TSource, TKey> but I only know TKey at runtime which can be string, int or even a Guid.

The user could pass something like "Country.Name" to the request.OrderBy property which means the results should be grouped by a sub-property (sub-select), the name of a country.

I think ExpressionTrees is the way to go here but I'm stuck before even getting started as I don't know how to handle the unknown Type as well as the option to group by a property of a sub-select/sub-property.





C# Reflection tunning DAL

I made some improvements on my dal. But I still have an issue to load the cache with the propertiesInfo via reflection.

I do 2 Activator.CreateInstace(T).

Each CreateInstance is heavy and sould I try to make all work with just one or it´s not worth it?

I cache the info into (cachedPropsInfo). Before I was doing a reflection call each time I would need the info.

As far as I know, reflection is not free, but doing the timming, I don´t see too much difference using the cached info...

Am I doing the cache in the right way or this tunning that I did and nothing are the same things?

cheers

Here is part of the code.

    namespace DAL
    {
        public abstract class BaseRepository<T> where T : BaseEntity
        {
            private static Dictionary<PropertyInfo, DbPropsInfo> cachedPropsInfo;


            private IEnumerable<T> fetchRecords(DbCommand dbCommand, bool isSingleRecord)
            {
                if (dbCommand.IsNull())
                    throw new ArgumentNullException("DbCommand is null");

    #if DEBUG
                debugParameters(dbCommand, "FetchRecords");
    #endif

                CommandBehavior behavior = CommandBehavior.CloseConnection;

                if (isSingleRecord)
                    behavior ^= CommandBehavior.SingleRow;

                IList<T> list = new List<T>();

                using (DbConnection dbconn = db.CreateConnection())
                {

                    dbCommand.Connection = dbconn;

                    try
                    {
                        dbconn.Open();

                        using (var rd = dbCommand.ExecuteReader(behavior))
                        {
                            try
                            {
                                if (rd?.HasRows == true)
                                {
                                    DateTime dt1 = DateTime.Now;

                                    **cachedPropsInfo = Activator.CreateInstance<T>().GetDbInfoProps();**                          


                                    while (!rd.IsNull() && rd.Read())
                                    {
                                        list.Add(MapTo<T>(rd));
                                    }

                                    DateTime dt2 = DateTime.Now;

                                    System.Diagnostics.Debug.WriteLine($"Took {(dt2-dt1).TotalMilliseconds}");
                                }
                            }
                            catch(Exception ex)
                            {
                                string error = mountErrorMsg("Fetch Records Reader", dbCommand, ex);

                                throw;
                            }
                            finally
                            {
                                if (rd?.IsClosed == false)
                                    rd.Close();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        string error = mountErrorMsg("Fetch Records Command", dbCommand, ex);

                        throw;
                    }
                    finally
                    {
                        dbCommand?.Dispose();
                        dbconn?.Dispose();

                        if (dbconn?.State == ConnectionState.Open)                     
                            dbconn.Close();
                    }

                }

                return list.AllOrNull();
            }


            protected T MapTo<T>(DbDataReader record)
            {
                if (record.IsNull())
                    throw new ArgumentNullException("Datareader record is null");

                **T obj = Activator.CreateInstance<T>();**
                string colName = null;
                string propName = null;          
                object objValue = null;
                Type toType = null;

                try
                {
                    foreach (var prop in cachedPropsInfo)
                    {
                        propName = prop.Key.Name;
                        colName = prop.Value.DbColumnName;
                        toType = prop.Value.ToType;
                        objValue = record[colName];
                        prop.Key.SetValue(obj, (DBNull.Value == objValue) ? null : Convert.ChangeType(objValue, toType));
                    }
                }
                catch (Exception ex)
                {
                    string msg = $@"MapTo SetValue, Model: {this.GetType().Name}, 
                                        Property: '{propName}', ColumnDB: '{colName}', 
                                        PropType: '{toType.ToString()}', 
                                        Value: '{objValue.ToString()}', Exception: {ex.Message}";

                    throw;
                }

                return obj;
            }

public Dictionary<PropertyInfo, DbPropsInfo> GetDbInfoProps()
        {
            var tca = typeof(DbColumnAttribute);
            var y = new Dictionary<PropertyInfo, DbPropsInfo>();
            string colName = "";
            Type toType = null;

            foreach (var prop in this.GetType().GetProperties().Where(x => x.IsDefined(tca, true)))
            {
                colName = ((DbColumnAttribute)prop.GetCustomAttributes(true)
                                                  .SingleOrDefault(x => x.GetType() == tca)).ColumnName;

                toType = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;

                y.Add(prop, new DbPropsInfo { DbColumnName = colName, ToType = toType });
            }

            return y;
        }





Java8 Streaming a class hierarchy

I am slowly learning the new Java 8 features and I am trying to find a way to process a class hierarchy (from child to parent) as a stream.

For instance find an annotation on a class or it's parents.

Before Java 8, I would have done it this way :

public static <T extends Annotation> T getAnnonationOn(Class<?> type, Class<T> annType) {
    Class<?> t = type;
    T annot = null;
    while (t != null && annot == null) {
        annot = t.getAnnotation(annType);
        t = t.getSuperclass();
    }
    return annot;
}

Now I wish to do it with a more "functional programming" way. I could not find a better way than concatenate streams with a recursive like follow :

import java.lang.annotation.Annotation;
import java.util.stream.Stream;

public static <T extends Annotation> T getAnnonationOn(Class<?> type, Class<T> annType) {
    return ClassIterator.streamSuperclass(type)
        .map(t -> t.getAnnotation(annType))
        .filter(a -> a != null)
        .findFirst()
        .orElse(null);
}

public static class ClassIterator {
    public static Stream<Class<?>> streamSuperclass(Class<?> type) {
        if (type.getSuperclass() != null) {
            return Stream.concat(Stream.of(type), Stream.of(type.getSuperclass()).flatMap(ClassIterator::streamSuperclass));
        }
        return Stream.of(type);
    }
}

But I am not quite satisfied of the solution. Although I did not benchmark it I think the stream concatenation is quite cumbersome and under performant.

Is there a better way to turn a recursive into a stream ?





System.Reflection.Assembly.LoadFile - " is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)"

In my code, I want to create dinamically an istance to an assembly using :

System.Reflection.Assembly myDllAssembly = System.Reflection.Assembly.LoadFile();

If my dll is compiled as "AnyCPU", it works succesfully.

Now, I have to compile my DLL as X86 because it must to use a COM object.

So, LoadFile returns this error:

" is not a valid Win32 application. (Exception from HRESULT: 0x800700C1)"

Can you help me?





How to get the amount of color attachments using shader reflection in Metal?

I need to figure out the amount of MRT color outputs used in a fragment shader in Metal to setup the render pipeline accordingly in host code. However I couldn't find a way of doing it. Can anyone help me?





lundi 24 octobre 2016

Replace method implementation in Android via reflection / class loader

I am currently doing research on techniques for runtime manipulation on mobile applications. On the iOS platform I can easily do method swizzling by calling objective-c runtime library functions such as class_replaceMethod(...). Is an equivalent way possible on Android?

If I use the JDB, I can alter local variables and I can evaluate expressions. By means of the latter, I assume it is possible to change entire implementation bodies of methods. How would you exactly do this, e.g. with using reflections? What are the required steps?

Thanks in advance!





Assign result of reflect.AppendSlice to pointer

I have troubles translating this piece of code, which is effectively a left rotate on a slice, into a more generic version which accepts interface{} as an input parameter.

func rotate(a *[]int, i int) {
    x, b := (*a)[:i], (*a)[i:]
    *a = append(b, x...)
}

I have troubles with the final assignment:

func rotateSlice(a interface{}, i int) {
    v := reflect.ValueOf(a)
    x, b := v.Elem().Slice(0, i), v.Elem().Slice(i, v.Elem().Len())
    *a = reflect.AppendSlice(b, x)
}

The error message is invalid indirect of a (type {}). The value of a is interface{}, hence *a = would be to assign the right-hand value to the space where the pointer is pointing to. My call to AppendSlice returns Value though. I am not sure where the type assertion needs to happen, I suppose on the left-hand side?





Retrive private class member name

I am designing a Hibernate's entity Pre-Update Event Listener with Java 8.

I've created a StateTracker class that, from the PreUpdateEvent, gets the entity's new and old states and the parameters name. This class maps the parameters names to the corresponding pair of old and new states and a lazy evaluated Boolean hasChanged and make querying the map by key (which is of type String) available through a public method.

Problem is: I need to check if a specific property from an entity A, say it is named var, will have it's state changed by the update event. Naturally this can be done like this:

void foo(PreUpdateEvent event) {
    StateTracker stateTracker(event);
    if(stateTracker.isPropertyModified("var") {
        /* do stuff... */
    }
}

I know I can't always save the world, but if someone ever changes var name to catastrophe in A, then the above code will be broken, because even the smarter of the refactoring tools won't see that the String "var" is meant to represent the name of the parameter var (now catastrophe).

I am accepting that there is no better way out of this situation, but I want to be sure that is no way to get a variable name through reflection or something.

Ideally, this would work like this:

void foo(PreUpdateEvent event) {
    StateTracker stateTracker(event);
    if(stateTracker.isPropertyModified(A.class.var.getName()) { // Magic!
        /* do stuff... */
    }
}

Maybe some wizardry in the field of annotation processing could perform such magic...





IntrospectionExtensions error despite targeting .NET 4

I have an application that is crashing when running on a .NET 4 server with the following error:

Could not load type 'System.Reflection.IntrospectionExtensions' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

I realise that this means that I need to install .NET 4.5 on the server but sadly this is not possible due to disc space constraints.

I am building this project in VS15 with .NET 4.6.1 installed.

As far as I can tell, there are no parts of my code that are using Reflection and consequently I'm confused as to why I'm getting this error. Especially given that I am targetting the .NET Framwork 4.

I have also tried including the Mono version of IntrospectionExtensions nabbed from some other site in my project but this was just generating lots of unresolvable symbol errors.

Is there any way to get around this issue?

I have attached my code below for reference:

I have uploaded it to Hastebin as there's no point copying 600 lines of code here when I don't know which section is causing the problem.





getAnnotation for Java annotation used on Kotlin method returns null

Say, I have the following interface:

interface AppRepository : GraphRepository<App> {

    @Query("""MATCH (a:App) RETURN a""")
    fun findAll(): List<App>
}

In a test I want to check specifics of the query string and therefore I do

open class AppRepositoryTest {

    lateinit @Autowired var appRepository: AppRepository

    @Test
    open fun checkQuery() {
        val productionMethod = appRepository.javaClass.getDeclaredMethod("findAll")
        val productionQuery = productionMethod!!.getAnnotation(Query::class.java)

        //demo test
        assertThat(productionQuery!!.value).isNotEmpty() //KotlinNPE
    }
}

For a reason I don't comprehend, productionQuery is nnull. I have double checked that the types of the imported Query in the test class and the Query in the repository are the same.

Thus, why is the productionQuery null in this case?





How to use Linq with Reflection in C#?

To get the name from id using reflection from an enumerable. I'm using:

foreach(string idValue in Values)
{
    var listSource = itemsSource as IEnumerable;
    PropertyInfo idProperty = listItem.GetType().GetProperty("Id");
    PropertyInfo nameProperty = listItem.GetType().GetProperty("Name");

    foreach (var listItem in listSource)
    {
        if (idValue.Equals(idProperty.GetValue(listItem, null).ToString()))
        {
            value = nameProperty.GetValue(listItem, null).ToString();
            break;
        }
    }
    //do something with value.
}

How to use Linq with reflection, so that I need not loop through elements for each value of 'idValue' in the outer loop??

something like:

reflectionList.Select(x=> x.idProperty == idValue) and use it to get value of nameProperty

Please help.





Java Security Manager completely disable reflection

I've been reading quite a lot of questions on Stackoverflow about this question but couldn't quit find a solution or answer for my problem. If there is already one I would be grateful if somebody would give a hint ...

My problem/question is if it is possible to completely disable reflection for not trustworthy code? Functions like getDeclaredMethods(). I've already got a Java Security Manager which throws Security Exceptions if the code tries to write/read/etc. ...

If it is possible, can somebody show me how?

Bruno





vb.net dll reflection event

I'm trying to pass a user defined event argument class from a dll to my main program. Both have the event argument class defined, but when I try to bind the event delegate to the method it won't bind because its signature is not compatible. I've stripped the code down to the main problem.

The code in the dll raises an event called ValueChange with a ValueEventArgs as argument:

Public Class Main
  Public Event ValueChange(ByVal sender As System.Object, ByVal e As ValueEventArgs)
  Private _Value As Integer

  Public Sub Up()
    _Value += 1
    RaiseEvent ValueChange(Me, New ValueEventArgs(_Value))
  End Sub
End Class

Public Class ValueEventArgs
  Inherits System.EventArgs
  Public Property Value As Integer

  Public Sub New(ByVal Value As Integer)
    Me.Value = Value
  End Sub
End Class

The Main program loads the dll and binds the event delegate to the method ShowValue:

Imports System.Reflection

Public Class Main
  Private DriverAssembly As [Assembly]
  Private DriverClass As Type
  Private DriverClassInstance As Object

  Private Sub ButtonLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonLoad.Click
    DriverAssembly = [Assembly].Load("reflection_event, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
    DriverClass = DriverAssembly.GetType("ReflectionEventDll.Main")
    DriverClassInstance = Activator.CreateInstance(DriverClass)

    ' get the handler method
    Dim Method As MethodInfo = Me.GetType.GetMethod("ShowValue")

    ' get the event and create a delegate
    Dim ValueChangeEvent As EventInfo = DriverClass.GetEvent("ValueChange")
    Dim Handler As [Delegate] = [Delegate].CreateDelegate(ValueChangeEvent.EventHandlerType, Me, Method) ' Fails
    ' Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

    ' add the event handler
    ValueChangeEvent.AddEventHandler(DriverClassInstance, Handler)
  End Sub

  Private Sub ButtonUp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonUp.Click
    DriverClass.GetMethod("Up").Invoke(DriverClassInstance, Nothing) ' invoke the method on the driver class instance
  End Sub

  Public Sub ShowValue(ByVal sender As Object, ByVal e As ValueEventArgs)
    MessageBox.Show(e.Value.ToString())
  End Sub
End Class

Public Class ValueEventArgs
  Inherits System.EventArgs
  Public Property Value As Integer

  Public Sub New(ByVal Value As Integer)
    Me.Value = Value
  End Sub
End Class

If I remove the creation of the delegate and the AddEventHandler everything works without a problem, without the event of course.

Funny thing, if I change the arguments of ShowValue method in the main program everything suddenly works, including the event.

Public Sub ShowValue(ByVal sender As Object, ByVal e As EventArgs)
  ' works, but the Value is lost
End Sub

It gets better, because it's not completely lost. If I put a breakpoint on the Sub I can see e is containing a property called Value.
A DirectCast also fails, but writing the EventArgs to a Object seems to work.

  Public Sub ShowValue(ByVal sender As Object, ByVal e As EventArgs)
    Dim Obj As Object = e
    MessageBox.Show(Obj.Value.ToString())
  End Sub

It works, but I don't think this is the right way. How can I use a user defined event argument class when handling an event from a dll?





Read values from case object field which is extending a trait using reflection

This might be a weird question, but I am trying something and stuck at this point.

For enumuerators, I am using the sealed trait - case object approach. I am trying to generate a Typescript class for each of the annotations to avoid mismatch between Frontend and Backend values for enums. Here is my sample enum implementation.

sealed trait BankingTypeEnum {
  val id: Long
  val name: String
}

object BankingTypeEnum {

  case object Cheque extends BankingTypeEnum {
    override val id: Long = 1
    override val name: String = "Loan"
  }

  case object Current extends BankingTypeEnum {
    override val id: Long = 2
    override val name: String = "Current"
  }

  case object Savings extends BankingTypeEnum {
    override val id: Long = 3
    override val name: String = "Savings"
  }

}

What I want to do is to get the values into a simple case class which can be later used to generating the typescript file. However, I am not sure how I can get the field values at generation time using reflection. If I use case class instead of case object, I can create an instance of the class using reflection, but I do not want to do that. Is there any other way, I can get the values, id and name fields of the case object enums ?





Select properties based on name and fetch the value

I have the below class with getters and setters.

class A{
 private String field1Required;
 private String field2Required;
 private String field3;
 private String field4;
}

Suppose in my main program I receive an object A populate as below,

field1Required = false; field2Required=true, field3=true; field4=false;

So I want select only the field1Required, field2Required and print the values of those properties. How can I achieve it using reflection or any other way?





How to get line numbers of a method?

Suppose we have following method:

1.  public static void main(String args[]) throws Exception {

2.    setUIFont(new javax.swing.plaf.FontUIResource("tahoma", Font.PLAIN, 12));
3.    new Frame();
4.    new Resource();
6.
7.    System.out.println(Integer.MAX_VALUE);
8.    }

As you can see, this method occupied lines 1 through 6. How can I get this list? Assume that I have the reflection class of this method.





dimanche 23 octobre 2016

How to execute dynamically created assembly in a given application domain?

I have a problem trying to execute a dynamic assembly in a given application domain. The assembly is building using System.Reflection.Emit.AssemblyBuilder class as shown

    // Utility method for building 'MathClient' assembly in memory. 
    public static void CreateMathClient(AppDomain domainForAssembly)
    {
        // Assembly name... 
        AssemblyName assemblyName = new AssemblyName();
        assemblyName.Name = "MathClient";
        assemblyName.Version = new Version("1.0.0.0");

        AssemblyBuilder assembly = domainForAssembly.DefineDynamicAssembly(
            assemblyName, AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder module = assembly.DefineDynamicModule(
            "MathClient", "MathClient.exe", false);

        // Defining 'Program' class... 
        TypeBuilder programClass = module.DefineType(
            "MathClient.Program",
            TypeAttributes.Public | TypeAttributes.Class); 

        // Defining Main() method... 
        MethodBuilder mainMethod = programClass.DefineMethod(
            "Main",
            MethodAttributes.Public | MethodAttributes.Static,
            null, 
            new Type[] { typeof(string[]) });
        ILGenerator mainMethodILGenerator = mainMethod.GetILGenerator();
        LocalBuilder aLocalVariable = mainMethodILGenerator.DeclareLocal(typeof(int), true);
        mainMethodILGenerator.Emit(OpCodes.Ldc_I4, 10);
        mainMethodILGenerator.Emit(OpCodes.Stloc, aLocalVariable);      // a = 10 

        // List 'a' value... 
        mainMethodILGenerator.Emit(OpCodes.Ldstr, "a = {0}");
        mainMethodILGenerator.Emit(OpCodes.Ldloc, aLocalVariable);
        mainMethodILGenerator.Emit(OpCodes.Box, typeof(int));
        Type consoleType = typeof(System.Console);
        MethodInfo writeLineMethod = consoleType.GetMethod(
            "WriteLine",
            new Type[] { typeof(string), typeof(object) });
        mainMethodILGenerator.Emit(OpCodes.Call, writeLineMethod);

        mainMethodILGenerator.Emit(OpCodes.Ret);

        // Bake 'Program' class type... 
        programClass.CreateType(); 

        // Set Main() method as an entry point...
        assembly.SetEntryPoint(mainMethod, PEFileKinds.ConsoleApplication);

        // Optionally save to disk...
        //assembly.Save("MathClient.exe");
    }

When I'm trying to execute the assembly in a default application domain

    static void Main(string[] args)
    {
        AppDomain currentDomain = AppDomain.CurrentDomain; 

        // Create new assembly in memory... 
        CreateMathClient(currentDomain);

        // Execute 'MathClient.exe' in the current domain... 
        currentDomain.ExecuteAssemblyByName(
            "MathClient,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null");

        Console.ReadLine();
    }

the following exception is throwing

System.IO.FileNotFoundException was unhandled HResult=-2147024894 Message=Could not load file or assembly 'MathClient, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

However, if the assembly was preliminary saved to disk

        // Optionally save to disk...
        assembly.Save("MathClient.exe");

everything works perfectly fine.
Why can't I execute the assembly with ExecuteAssemblyByName()?





Get static methods of a class nested in an object using Java reflection

I want to get the list of methods in a nested companion object using Java reflection. This is A.B in the example below.

object A {
  object B {
    def foo: Int = 4
  }

  class B {}

  def bar: Int = 5
}

class A {}

// This works, `bar` is printed.
println(classOf[A].getMethods.map(_.getName).mkString("\n"))

// This doesn't work, `foo` is not printed.
println(classOf[A.B].getMethods.map(_.getName).mkString("\n"))

Seems like getting the list of methods on the outer companion object A works, but not on the nested one.

Is there any way to write a method that would take a Class[_] and get all the methods defined on the companion object whether it's nested or not?





Difference between scala's ClassTag and TypeTag

According to scala doc,TypeTag contains more information than ClassTag. It seems to me that TypeTag can do more things than ClassTag, like bring the type parameter information of compile time to runtime, etc.

However, the following example shows that ClassTag can do the job, while the TypeTag not. I want to understand why.

import scala.reflect.ClassTag
import scala.reflect.runtime.universe.TypeTag
// def func[T](o: Any): Unit = {
// def func[T : TypeTag](o: Any): Unit = {
def func[T : ClassTag](o: Any): Unit = {
  o match {
    case x: T => println(Some(x))
    case _ => println(None)
  }spark
}
func[Map[Int, Int]](List(1, 2, 3))

Only ClassTag will lead the pattern matching to None (which is the expected behavior), the first two commented lines will come up with Some branch.

It seems that ClassType can reflect on object's type on runtime, while Type Tag can't. But isn't TypeTag a superset of ClassTag ? I would like to know the explanation as detailed as possible. Thank you.





Conditionally skip a method with Matalinks

Imagine we have some method

MyClass>>#method: arg

    Transcript crShow: 'executed'

So when you do MyClass new method: 1 the transcript is filled with "executed" lines.

Now I want to skip this method is arg is 0. I've tried to install an instead metalink with a condition:

link := MetaLink new
   condition: [ :arguments |
      arguments first = 0 ]
   arguments: #(arguments);
   control: #instead.

(MyClass >> #method:) ast link: link

But then the method does not run anymore and I want to run it if the arg is not 0.

I've also tried to do the condition in the metaobject in this way:

link := MetaLink new
   metaObject: [ :ast :arguments :receiver | 
      arguments first = 0
      ifFalse: [
         ast compiledMethod
            valueWithReceiver: receiver
            arguments: arguments ] ];
   selector: #value:value:value:;
   arguments: #(node arguments receiver);
   control: #instead.

(MyClass >> #method:) ast link: link

But in this case you end up in a infinite recursion, as the metalink is called over and over again although I thought that ast compiledMethod should return a compiled method and not the reflective counterpart





How to specify an interface as a generic type argument when using reflection in C#?

I am trying to instantiate a type using reflection that takes a contract as a generic type parameter. If it was a generic type method, I could use the .MakeGenricMethod method, and specify the reflected type. However, if the type itself is not generic, how would I go about specifying the interface as the contract?

This is what the code would look like with the assemblies loaded normally:

Ice.Lib.Framework.WCFServiceSupport.CreateImpl<Erp.Proxy.BO.JobEntryImpl>(EpicorSession, Epicor.ServiceModel.Channels.ImplBase<Erp.Contracts.JobEntrySvcContract>.UriPath);

Where I am stuck is at the "Epicor.ServiceModel.Channels.ImplBase" part.

I need to specify that Erp.Contracts.JobEntrySvcContract interface when reflecting or the class won't instantiate properly. I then need to grab that .UriPath property and plug it into my CreateImpl method.

Here's what I've got for that part:

 Type _ImplBase = asmEpicorServiceModel.GetType("Epicor.ServiceModel.Channels.ImplBase");      
            FieldInfo UriPath = _ImplBase.GetField("UriPath", BindingFlags.GetField | BindingFlags.Public | BindingFlags.Static); 

The problem is, _ImplBase is returning null, and I think this is because I didn't specify that Interface as the contract so it failed.

public class ImplBase<TContract> : ImplBase where TContract : class
{
    public static readonly string UriPath;

Eventually, I will need to grab that UriPath static property.

Thank you!





Golang: loop through fields of a struct modify them and and return the struct?

I am trying to loop through the individual fields of a struct applying a function to each field and then return the original struct as a whole with the modified field values. Obviously, this would not present a challenge if it were for one struct but I need the function to be dynamic. For this instance, I am referencing the Post and Category struct as shown below

type Post struct{
    fieldName           data     `check:"value1"
    ...
}

type Post struct{
    fieldName           data     `check:"value2"
    ...
}

I then have a switch function that loops through the respective fields of the structs and depending on what value the check has, applies a function to that field's data as follows

type Datastore interface {
     ...
}

 func CheckSwitch(value reflect.Value){
    //this loops through the fields
    for i := 0; i < value.NumField(); i++ { // iterates through every struct type field
        tag := value.Type().Field(i).Tag // returns the tag string
        field := value.Field(i) // returns the content of the struct type field

        switch tag.Get("check"){
            case "value1":
                  fmt.Println(field.String())//or some other function
            case "value2":
                  fmt.Println(field.String())//or some other function
            ....

        }
        ///how could I modify the struct data during the switch seen above and then return the struct with the updated values?


}
}

//the check function is used i.e 
function foo(){ 
p:=Post{fieldName:"bar"} 
check(p)
}

func check(d Datastore){
     value := reflect.ValueOf(d) ///this gets the fields contained inside the struct
     CheckSwitch(value)

     ...
}   

How do I, in essence, re-insert the modified values after the switch statement in CheckSwitch back into the struct specified by the interface in the above example. Please let me know if you need anything else. Thanks





Reflection GetValue of static field returns null

I've done my best to create a minimal reproduction of the problem I'm experiencing, but can't. Here at least is the bare minimum of the situation and we'll see if anyone has ideas.

With these classes:

public class MainType {
   public static readonly MainType One = new MainType();
   public static readonly MainType Two = SubType.Two;
}

public sealed class SubType : MainType {
   public new static readonly SubType Two = new SubType();
}

Get fields One and Two:

List<FieldInfo> fieldInfos = typeof(MainType)
   .GetFields(BindingFlags.Static | BindingFlags.Public)
   .Where(f => typeof(MainType).IsAssignableFrom(f.FieldType))
   .ToList();

Finally, get their values:

List<MainType> publicMainTypes = fieldInfos
   .Select(f => f.GetValue(null))
   .ToList();

In LinqPad or in a simple unit test class with the above code, everything works okay. But in my solution, where I have some unit tests that want to work with all instances of these fields, GetValue works fine on the parent type, but on the subtypes always yields null! (If that happened here, the final list would be { One, null } instead of { One, Two }.) The test class is in a different project from the two types (each in their own file), but I've temporarily made everything public. I've dropped a breakpoint in and have examined all I can examine, and have done the equivalent of fieldInfos[1].GetValue(null) in a Watch expression and it does in fact return null, despite the fact that there is a line in my main class exactly like the second one from MainType above.

What is wrong? How do I get all the values of the subtype fields? How is it even possible for them to return null without an error?

On the theory that perhaps for some reason the subtype's class was not being statically constructed due to the access through reflection, I tried

System.Runtime.CompilerServices.RuntimeHelpers
  .RunClassConstructor(typeof(SubType).TypeHandle);

at the top before starting, but it didn't help (where SubType is the actual subtype class in my project).

I'll keep plugging away at trying to reproduce this in a simple case, but I'm out of ideas for the moment.

Additional Information

After a bunch of fiddling, the code started working. Now it is not working again. I am working on reproducing what triggered the code to start working.





It is possible to define Scala case objects programmatically?

In my current project, I need to define a lot of case objects subclassing a single sealed trait. The names of these objects have a pattern, e.g., Case1, Case2, Case3, ..., CaseN. I was wondering if there is way in scala to define all these case objects in a programmatical way, for example with a loop, instead of writing N lines of definitions.

If this is feasible, it would also be great to do this at compile time so that the case objects defined in this way are known to type checking. This sounds impossible in most languages (you can have either dynamically defined types like in python or have static type safety like in C/C++, but not both), but maybe it is doable in Scala for its powerful compile-time reflection?





How to enumerate a vector without knowing its element's type in reflection programming with C++11?

I'm trying to add dynamic reflection in C++ implementation with C++11. Let's say, I have a base class named Object:

class Object {
public:
    Object() = default;
    ~Object() = default;
};

And two classes inherited from Object:

class Person : public Object {
public:
    std::string name;
    int age;
}

class Group : public Object {
public:
    std::string groupName;
    std::vector<Person> persons;
}

I've implemented RefectManager to record all the classes' meta information, and I create an object with a class name, for example:

Object *obj = RefectManager::CreateObject("Group");
MetaInfo *groupMeta = obj->GetMetaInfo();

where, "groupMeta" holds the meta information of class Group, it knows that:

class Group has a field list with two fields inclued:
* one field named "groupName", and its type's name is "std::string"
* one field named "persons", and its type's name is "std::vector" and the name of the element's type in the vector is "Person"

I can get the Person's meta information through its name:

MetaInfo *personMeta = RefectManager::GetMetaInfo("Person");

But, is there a way to enumerate the field of "persons" in class Group with reflected meta informations dynamically, such as:

for (field in groupMeta's field list) {
    if (field type's name is "std::string") {
        get field's content as string
    } else if (field type's name is "std::vector") {
        // only the element type's name is known as "Person"

        // **how to enumerate the field with vector type?**

        // If we know the element's type through element type's name, 
        // we can do it as following:
        // std::vector<GetType<"Person">::type> *p = (std::vector<GetType<"Person">::type> *)field;
        // std::vector<GetType<"Person">::type>::iterator it = p->begin();
        // for (; it != p->end(); ++it) {
        //     //now we can access the element in field
        // }
    }
}





Is it possible to store types, not instances of those types, in a Vec?

Is it possible to store different Rust types into a Vec in some form that would allow me to get the types at later date?

I could store the TypeId of any types, but I couldn't then use the TypeId to get back to the original types, as far as I know.

In Java terms, I want to create a [boolean.class, char.class, ...], etc.





C# code generation, generate create statement from object

I have an object in C#. (Which is the deserialize result of a complex JSON) Now I wish to create a string from that object.

A string that describes the creation in C# of that same object. Preferably as a single statement.

Why do I want this? Because I want to generate code using T4, that contains the create statement for this object.

I was hoping there is some sort of utility class / reflection class for this in the .NET framework.





Determining if a field is using a generic parameter

I've been baffled by this and can't seem to get my head around it so hopefully someone can point me in the right direction.

I have a class as follows:

public class Foo<T>
{
    public List<T> Data;
}

Now I'm writing code to reflect this class and want to work out a way of determining that the field Data has a generic parameter being used.

My initial approach was to continue going down as many levels as I could and once I hit the IsGenericParameter field set to true I would rather than reflect the type name instead place a "Generic Argument" string there, however I can't seem to get this to work the way I want it to.

I've looked around but every solution I've found seems to point to a dead end with this at the moment.





How to check if boxed value is empty in .NET

For example,

I have input parameter of type object. And I know that this parameter can store one of value type int, float, double(boxed value) etc. But I don't know which value type will come to this method. And I want check if boxed value type empty or not.

Like this piece of code:

bool IsEmpty(object boxedProperty)
{
    return boxedProperty == default(typeof(boxedProperty))
}

I understand, I can do this:

bool IsEmpty(object boxedProperty)
{
    return boxedProperty is int && boxedProperty == default(int)
    || boxedProperty is float ....
}

But it looks like dirty solution. How do this better?





How do I pass around the result of type(of: ...) in Swift 3?

Consider the following code:

var med: Med = Med()

var cls1 = type(of:med)
var cls2 = Med.self
var cls3: AnyClass = Med.self

var med1 = cls1.init()
var med2 = cls2.init()
var med3 = cls3.init() // Compiler: 'init' is a member of the type; use 'type(of: ...)' to initialize a new object of the same dynamic type

The way of doing this seems to have changed a lot between each version of Swift and so searches online provide lots of dead ends.

If Med.self is not of type AnyClass why doesn't the compiler complain when I set cls3? If it is of type AnyClass why does it complain when setting med3? How do I pass the result of type(of: ...) around to another method to make use of it?

Or simply, how does one get a new instance of AnyClass in Swift 3?





Dynamic ByRef The best overloaded method match for ... has some invalid arguments

I have an application that is built on top of dynamic and reflection types.

dynamic obj = null;
obj = My_Assembly.CreateInstance("full.namespace.class");
obj.DateCreated = DateTime.Now;
obj.DateModified = DateTime.Now;
obj.DateStarted = DateTime.Now;
.....
myservice.Add(ref obj, false);

Runtime raises an exception that The best overloaded method match for ... has some invalid arguments

I did a trick to see whats wrong...

var objd = (full.namespace.class)obj;
myservice.Add(ref obj, false);

and it works fine. To see what's difference I ran a quick match in immediate window

? obj == objd;
true

and the result was true which means both are identical.

Can anyone explain me whats wrong with it?





C# - launch Microsoft foundation solver THROUGH Reflection

below you can find a trivial optimisation code I have written to check how Foundation Solver works. I am then trying to re-write this code using reflection, starting from the end of the code (step 6 in the code below).

I get a NullReferenceException when it comes to getting the type of the "Solution class": it seems that the fully-qualified name ("Microsoft.SolverFoundation.Services.Solution") of the "Solution" Class is wrong.

Can someone help me with that?

Thanks

class Program
{
    static void Main(string[] args)
    {
        // Get two input values
        Console.WriteLine("Input values of X and Y");
        Console.WriteLine("X value: ");
        double Xinput = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("Y value: ");
        double Yinput = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("");

        /* Create the optimisation problem */
        // 1) Creat the solver and model objects
        var solver = SolverContext.GetContext();
        var model = solver.CreateModel();

        // 2) Create variables
        var X = new Decision(Domain.RealNonnegative, "X");
        var Y = new Decision(Domain.RealNonnegative, "Y");

        // 3) Add them to the model
        model.AddDecision(X);
        model.AddDecision(Y);

        // 4) Add goals
        model.AddGoal("Goal", GoalKind.Minimize, X + Y);

        // 5) Add constraints
        model.AddConstraint("X_constraint", 0 <= X <= 500);
        model.AddConstraint("Y_constraint", 120 <= Y <= 3120);

        // 6) Solve optimisation
        // Solution solution = solver.Solve(); // This is what should be without reflection

        // rewritten with reflection
        Assembly executingAssembly = Assembly.GetExecutingAssembly();
        Type solutionType = executingAssembly.GetType("Microsoft.SolverFoundation.Services.Solution"); // <-- something wrong here??
        object solution = Activator.CreateInstance(solutionType); // HERE I GET THE ARGUMENT NULL EXCEPTION!
        MethodInfo solveMethod = solutionType.GetMethod("Solve");
        solveMethod.Invoke(solution,null);

        // 7) Print the outputs
        Console.WriteLine("Results:");
        Console.WriteLine("X: " + Math.Round(X.GetDouble(), 2));
        Console.WriteLine("Y: " + Math.Round(Y.GetDouble(), 2));
        Console.WriteLine("");

    }
}