samedi 31 décembre 2016

Reflection in Java

I am new to reflection in java and I thought that since I provided the arguments to the EnemyShip constructor that will be preserved. And After changing just the name of the ship, only that will be changed. However, I got wentworth is travelling at 0 instead of what I expected : wentworth is travelling at at 3242

Last line of code should in reflectionTest be main focus

I have 2 classes:

package com.reflectionapi.demo;

import java.lang.reflect.*;

public class reflectionTest {

public static void main(String[] args) {


    Class shipClass = EnemyShip.class;
    int shipMod= shipClass.getModifiers();
    String shipModStat="";

    switch(shipMod){
    case Modifier.PUBLIC: shipModStat="Public";
            break;
    case Modifier.PRIVATE: shipModStat="Private";

    }


    System.out.println(shipClass.getName()+" "+shipModStat
            );//prints class of ship




    Method[] methods = shipClass.getMethods();


    Class[] parameters;


    for (Method method: methods){
        String methodName = method.getName();
        parameters= method.getParameterTypes();// assign method parameters to paramters array

        if (methodName.startsWith("get"))
                    System.out.println(methodName+" is a Getter Method "+
                            "it returns "+ method.getReturnType()+"\n");    

        else 
            if (methodName.startsWith("set"))

                    for (Class param: parameters){
                System.out.println(methodName+" is a Setter Method and "+
                "takes parameters "+ param.getName()+"\n");
                    }

        }

    Class superClass = shipClass.getSuperclass();
    System.out.println(shipClass+" is a subclass of "+ superClass.getName()+"\n");


    Constructor[] constructors = shipClass.getConstructors();   
    //Constructor constructors = shipClass.getConstructor(new Class[] {EnemyShip.class} ); not iterable

    Object constructorItem =null;

    for (Constructor construct: constructors){
        System.out.println(construct);

    }


    try {
         constructorItem= shipClass.getConstructor(String.class , int.class ).newInstance("XT-1800", 5000);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
            | NoSuchMethodException | SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    EnemyShip ship = new EnemyShip("Carl", 3242);

    ship.setName("Wentworth");
    //ship.setSpeed(1230420);

    System.out.println(ship.getName()+
            " is travelling at "+
            ship.getSpeed());



    }

}

Second class

 package com.reflectionapi.demo;

 public class EnemyShip {



public EnemyShip (String s, int m){// s= name m= speed
    /*
    name =s;
    speed=m;
 try later */

    System.out.println(s+
             " is travelling at :"+ m);
}

public EnemyShip (String s, int m, double j){// s= name m= speed

    System.out.println(s+
             " is travelling at :"+ m);
}


public String getName (){   
    return name ;
}

public void setName(String s){

    name =s;
}

public void setSpeed(int s){

    speed =s;
}

public int getSpeed(){
    return speed;
}

    private String name =""; 
    private int speed=0;

}





String to token [duplicate]

This question already has an answer here:

Is there a possibility in C++ to turn a string into an element like a function name? For example:

"MyFunction()" to MyFunction() so it's callable or maybe using a macro. I know the concatenating operator '##', but it does not work with strings.





How to know when Binding of property is changed

The following code is used to directly set value of property that is bound to control's property. (In my case a property is bound to ValueProperty of Slider).

private Action<double> _valueSetter; // target property setter cache

private double _newValue;

protected override void OnThumbDragCompleted(DragCompletedEventArgs e)
{
    if (_valueSetter == null)
    {
        var bindingExpr = BindingOperations.GetBindingExpression(this, ValueProperty);

        var property = bindingExpr?.DataItem
            .GetType()
            .GetProperty(bindingExpr.ParentBinding.Path.Path);

        _valueSetter = (Action<double>)property?
            .GetSetMethod()
            .CreateDelegate(typeof(Action<double>), bindingExpr.DataItem);
    }

    _valueSetter?.Invoke(_newValue); // as fast as possible!

    base.OnThumbDragCompleted(e);
}

The problem is if I change the Binding of the ValueProperty I don't know that happened and therefor my _valueSetter is still referring to old property setter.

Obviously one way is to always use reflection without using _valueSetter but is there better way? It would be really nice if I knew that ValueProperty is just bound to new property and then I could update my _valueSetter.

I tried to create another binding for dependency property but they are static and that confuses me. is there any way to fire an event when binding of control's property changes?





vendredi 30 décembre 2016

Call method of lazy generic type with reflection in c#

I want to call close method of _baseInfoService with reflection if IsValueCreated. how can I do it with reflection?

public static partial class ServiceFactory
{
    private static readonly Lazy<ServiceWrapper<IBaseInfoWcfService>> _baseInfoService = 
        new Lazy<ServiceWrapper<IBaseInfoWcfService>>(CreateWrapper<IBaseInfoWcfService>);

    public static IBaseInfoWcfService BaseInfoService => _baseInfoService.Value.Instance;
}





Pass parameter to function via reflection

I have an extesion method with the following signature

public static void AddConfiguration<TEntity>(this ModelBuilder builder, EntityTypeConfiguration<TEntity> configuration)
    where TEntity : class
{
    ...
}

I want to pass the parameter via Reflection and tried this method:

var ctors = type.GetConstructors(BindingFlags.Public);
modelBuilder.AddConfiguration(ctors[0].Invoke(new object[] { }));

And this way:

modelBuilder.AddConfiguration(Activator.CreateInstance(type));

Both return an object so the method does not accept them. Is there any way to do that?





Create an instance based on a stringvalue

I wish to create an instance of a class, using a string value. According to what I read here: Activator.CreateInstance Method (String, String) it should work!

public class Foo
{
    public string prop01 { get; set; }
    public int prop02 { get; set; }
}   

//var assName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var assName = System.Reflection.Assembly.GetExecutingAssembly().GetName().FullName; 
var foo = Activator.CreateInstance(assName, "Foo");

Why won't this work? I get the following error:

{"Could not load type 'Foo' from assembly 'theassemblyname, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.":"Foo"}





Reflection Emit for Property Getter

I want to build type dynamically like this:

public class Sample
{
    Sample Parent { get; set; }
    public Sample(Sample parent)
    {
        Parent = parent;
    }

    public int Depth
    {
        get
        {
            if (Parent == null)
                return -1;
            else
                return Parent.Depth + 1;
        }
    }
}

The code I write is :

        const string assemblyName = "SampleAssembly";
        const string parentPproperty = "Parent";
        const string depthProperty = "Depth";
        const string typeName = "Sample";     
        const string assemblyFileName = assemblyName + ".dll";

        AppDomain domain = AppDomain.CurrentDomain;
        AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.RunAndSave);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName, assemblyFileName);
        TypeBuilder typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public);
        FieldBuilder parentField = typeBuilder.DefineField($"_{parentPproperty}", typeBuilder, FieldAttributes.Private);
        PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(parentPproperty, PropertyAttributes.None, parentField.FieldType, Type.EmptyTypes);
        MethodBuilder getParentMethod = typeBuilder.DefineMethod($"get_{propertyBuilder.Name}", DynamicMethodBuilder.GetMethodAttrs, parentField.FieldType, Type.EmptyTypes);
        ILGenerator il = getParentMethod.GetILGenerator();
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Ldfld, parentField);
        il.Emit(OpCodes.Ret);
        propertyBuilder.SetGetMethod(getParentMethod);

        MethodBuilder setParentMethod = typeBuilder.DefineMethod($"set_{propertyBuilder.Name}", DynamicMethodBuilder.GetMethodAttrs, null, Type.EmptyTypes);
        il = setParentMethod.GetILGenerator();
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Stfld, parentField);
        il.Emit(OpCodes.Ret);
        propertyBuilder.SetSetMethod(setParentMethod);


        parentField = typeBuilder.DefineField($"_{depthProperty}", typeBuilder, FieldAttributes.Private);
        propertyBuilder = typeBuilder.DefineProperty(depthProperty, PropertyAttributes.None, parentField.FieldType, Type.EmptyTypes);
        MethodBuilder getDepthMethod = typeBuilder.DefineMethod($"get_{depthProperty}", DynamicMethodBuilder.GetMethodAttrs, parentField.FieldType, Type.EmptyTypes);
        il = getDepthMethod.GetILGenerator();
        LocalBuilder lb = il.DeclareLocal(typeof(bool));

        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Call, getParentMethod);
        il.Emit(OpCodes.Ldnull);
        il.Emit(OpCodes.Ceq);
        il.Emit(OpCodes.Stloc_0);
        il.Emit(OpCodes.Ldloc_0);
        il.Emit(OpCodes.Brfalse_S);
        il.Emit(OpCodes.Ldc_I4_1);
        il.Emit(OpCodes.Stloc_1);
        il.Emit(OpCodes.Br_S);
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Call, getParentMethod);
        il.Emit(OpCodes.Callvirt, getDepthMethod);
        il.Emit(OpCodes.Ldc_I4_1);
        il.Emit(OpCodes.Add);
        il.Emit(OpCodes.Stloc_1);
        il.Emit(OpCodes.Br_S);
        il.Emit(OpCodes.Ldloc_1);
        il.Emit(OpCodes.Ret);
        propertyBuilder.SetGetMethod(getDepthMethod);

        ConstructorBuilder constructor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[] { typeBuilder });
        il= constructor.GetILGenerator();            
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));
        il.Emit(OpCodes.Ldarg_0);
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Call, setParentMethod);          
        il.Emit(OpCodes.Ret);

        Type type = typeBuilder.CreateType();
        var obj1 = Activator.CreateInstance(type, null);

        var obj2 = Activator.CreateInstance(type, obj1);

        assemblyBuilder.Save(assemblyFileName);

I think I had problem in building constructor and Depth property getter method.

Please help me get out of this.

Instance is not created as well.

Thanks





jeudi 29 décembre 2016

When and how to use attribute based programming

I have seen many ORM mapping tables/columns to corresponding classes in C# using Custom Attributes. Even entity framework do in a similar way. I am trying to figure out when and how to use Attributes to make my solution more manageable efficient and scalable.

Some of the problem statements I assume it might be useful are 1. Mapping Tables/Views to Classes

Table Employee{ Name, Age, salary, height}...
class Employee{Name, Age, Salary, Height}...

  1. Mapping KeyValue pair/dictionary to class

Table

PersonAttributes{
Column1, Column2
"Age", "25"
"Salary", "3000"
"Weight", "80"
...
}

Class Person{
string Name;

[MapToTable(TableName="PersonAttributes", Key="Column1", Value="Column2",DataType="Int", Field="Age", )]
int Age;

[MapToTable(TableName="PersonAttributes", Key="Column1", Value="Column2",DataType="Int", Field="Weight", )]
int Weight;

[MapToTable(TableName="PersonAttributes", Key="Column1", Value="Column2",DataType="Int", Field="Salary", )]
int Salary;
}





Object does not match target type when constructing an object dynamically

I have some reflection code that takes one object type and then dynamically creates another object with the same properties (different type) and then sets the properties on the new object.

As seen on the screenshot, the properties are Int32, so I dont know why I am getting this exception on the Setvalue method

Code:

private static T AssembleObject(K sourceObject, T editObject, bool enableAssembleChildObjects, int? level, int? currentLevel)
{
    if (sourceObject == null)
        return default(T);

    T resultObject = (editObject != null) ? editObject : default(T);

    //Se incrementa el nivel de profundidad
    if (currentLevel.HasValue)
        ++currentLevel;

    PropertyInfo[] sourceObjectProperties = typeof(K).GetProperties();
    PropertyInfo[] resultObjectProperties = typeof(T).GetProperties();

    if (sourceObjectProperties != null && resultObjectProperties != null)
    {
        if (editObject == null)
        {
            resultObject = new T();
        }

        for (int i = 0; i < sourceObjectProperties.Length; i++)
        {
            PropertyInfo fromProperty = (PropertyInfo)sourceObjectProperties[i];

            for (int j = 0; j < resultObjectProperties.Length; j++)
            {
                PropertyInfo toProperty = (PropertyInfo)resultObjectProperties[j];

                if (fromProperty.Name == toProperty.Name)
                {
                    //Se obtienen los tipos básicos del objeto
                    if (fromProperty.PropertyType.IsValueType ||
                        (fromProperty.PropertyType.IsArray && fromProperty.PropertyType.GetElementType().IsValueType) ||
                        fromProperty.PropertyType == typeof(System.String))
                    {
                        //Se establece el valor de la propiedad
                        if (toProperty.CanWrite)
                        {

                            toProperty.SetValue(resultObject, fromProperty.GetValue(sourceObject, null), null);
                        }
                    }
                    else
                    {
                        if (enableAssembleChildObjects)
                        {
                            //Validación del nivel de profundidad
                            if (level.HasValue && currentLevel.HasValue && (currentLevel > level))
                                continue;

                            //Se obtiene el tipo del ensamblador
                            Type hermesAssemblerType = typeof(HermesAssembler<,>);
                            //Se definen los argumentos y se crea el tipo genérico dinamicamente
                            Type[] typeArgs = { fromProperty.PropertyType, toProperty.PropertyType };
                            Type resultType = hermesAssemblerType.MakeGenericType(typeArgs);
                            //Se obtiene la lista de métodos del tipo
                            MethodInfo[] methods = resultType.GetMethods(BindingFlags.NonPublic | BindingFlags.Static);
                            string methodName = (fromProperty.PropertyType.IsArray) ? "AssembleObjects" : "AssembleObject";
                            //Se obtiene el método estático específico a ejecutar
                            MethodInfo method = (from m in methods
                                                 where m.Name == methodName && m.GetParameters().Length == 3
                                                 select m).First();
                            //Se obtiene el valor desde la propiedad fuente
                            object sourceValue = fromProperty.GetValue(sourceObject, null);
                            //Se ejecuta el método
                            object resultValue = (sourceValue != null) ? method.Invoke(null, new object[] { sourceValue, level, currentLevel }) : null;

                            if (toProperty.CanWrite)
                            {
                                //Se establece el valor de la propiedad  
                                toProperty.SetValue(resultObject, resultValue, null);
                            }
                        }
                    }

                    break;
                }
            }
        }
    }

    return resultObject;
} 

Screenshot

enter image description here





How do I write a method that fills a property using the property's name?

Here is what I am looking at doing. Say I have a Class with a number of properties. I am trying to write a method that looks something like this

       public static void GetNullableInt32(this DbDataReader reader, Type property)
       {
           property = reader.IsDBNull(reader.GetOrdinal(property.name))
                         ? (int?)null
                         : reader.GetInt32(reader.GetOrdinal(property.name));

       }

Where the property name is pulled from reflection, and the property is set in the method. I put in Type in the parameters as a placeholder for whatever type it needs to be. Then I would call it like

      reader.GetNullableInt32(Class.Property1);

To set all the properties on a class from a database reader.

Is there an easy way to do this? Or is there a better structure where instead of having to enter the column name as a string it is pulled from the column name?





convert invoked funtion to List<>

It's really hard to explain my problem but i will do my best

my code is:

    public virtual void LoadList() {
        MethodInfo method = ClassType.GetType().GetMethod("Set", new Type[0]);
        MethodInfo generic = method.MakeGenericMethod(this.ClassType.GetType());
        var List = generic.Invoke(_classType, null);
        //everything works great till here. but now i want to convert the list, that
        //was returned from invoke method, into the List, in order to bind it to the
        //DataSource
      grdList.DataSource = List;
      grdList.Columns["ID"].Visible = false;
    }

so i want to convert the result from invoked method to list. any suggestions? pardon me if couldnt explain the problem well.





Enable Bluetooth HCI log programatically

For some logging purposes I need to enable Bluetooth HCI log on my device. Of course this can be easily done from the Developers Settings menu, but most of my users won't be familiar with that and I would like to do it programatically. These devices won't be rooted, so I can't manually edit bt_stack.conf file.

While searching through the internet, I found a hidden API method BluetoothAdapter.configHciSnoopLog(). I don't really want to mess with SDK jars, so I wanted to use reflection in order to access this method, like this:

Method configHciSnoopLogMethod = BluetoothAdapter.class.getDeclaredMethod("configHciSnoopLog", boolean.class);
Object r = configHciSnoopLogMethod.invoke(BluetoothAdapter.getDefaultAdapter(), true);

This works well on about ~20% of devices I tested (returns true) but returns false for the rest (out of ~20 different devices). I am giving the app correct BLUETOOTH_ADMIN permission, so I don't know why it's not working. As I looked at the AOSP source code for main Settings application, this is exactly what it it doing internally (just without reflection of course). Is there something I am missing? Some permission that should be added?

Thanks for help!





how to create List

I have model name like

UserModel

i want create List of UserModel by string variable with "UserModel" value like

string className = "UserModel";
List<className> users = new List<className>();

thanks





List of Static Methods on Class shows Lambdas using reflection

public class StaticMethodList {
    public static void main(String[] args) {
        listStaticMethods();
    }

    private static void print1To10() {
        IntStream.range(1, 11).forEach(System.out::println);
    }

    private static void listStaticMethods() {
        Stream<Method> staticMethods = Arrays.<Method>asList(StaticMethodList.class.getDeclaredMethods()).stream();
        staticMethods
                .filter(method -> !("listStaticMethods".equals(method.getName())))
                .forEach(m -> {
                    System.out.println(m.getName());
                 });

    }
}

The above code produces following output

main
print1To10
lambda$0
lambda$1

I am not sure why the lambda$ is being considered as static method. Also is there any way to obtain more details about the lambda here?





Using Generic Repository Pattern With Deattached Entities

I am using generic repository pattern with deattached objects.I have different layers.In my web layer(where I make crud operations on entities) I have simple generic save method as shown in the below.

MyEntityService.Save(Entity)

In the service layer(where I have DbContext commit changes to db)

I removed some lines for brevity.

    private void SetMyEntityStates(IEntityCommon entity)
    {
        if (entity == null )
        {
            return;
        }

        var navProperties= entity.GetNavigationProperties;

        foreach (var navprop in navProperties)
        {

            if (typeof(IEntityCommon).IsAssignableFrom(p.PropertyType))
            {
                var val = p.GetValue(entity) as IEntityCommon;
                if (val != null)
                {
                    var entry = Context.Entry(val);
                    if (entry.State == EntityState.Detached || entry.State == EntityState.Unchanged)
                    {
                        entry.State = val.IsNew() ? EntityState.Added : EntityState.Modified;
                        SetMyEntityStates(val);
                    }
                }
            }
        }
    }

Because I don't know which property or navigation property is modified in the web layer I change state of all of navigation properties even nav properties of nav properties recursively to modified/added.

Because all of my entities have at least one navigation property I almost flag all entities in my Context as modified.

Must I do modify every nav prop recursively as I do ?

Consider the example below,If I change a customer's home price ,must I change entity state for both home and price or home is enough?

 public class Customer
 {
   virtual ICollection<Home> {get; set;}
 } 

 public class Home
 {
  virtual ICollection<Price> {get; set;}
 }

 public class Price
 {
  PriceType {get;set;}/1 2 3 Euro Gbp Dollar
  Value {get;set;}
 }

For each entity state that I change to modified EF creates a update sql ? If there any other way to accomplish my task ?

Thanks in advance





mercredi 28 décembre 2016

How to invoke method from another Java project

The task is to invoke a method from another Java compiled .class file. File is located in different location (e.g. C:\Downloads\Task.class) and already compiled. Method, which shoud be invoked is static and consumes FileOutputStream OR returns String:

public static void task(FileOutputStream out, String[] args) {...}

or

public static String task(String[] args) {... return result;}

Is there any possible way to do this? Can I do a classload of class, located in different folder, or shoud I just save classfile to a location, where class with main method is?





mardi 27 décembre 2016

Reflection Emit: how to build constructor for this

The code I want to build dynamically is as follows:

public class Sample
{
    public Sample()
    {
        Items = new ObservableTestCollection<Sample>(this);
    }
    public Sample(IEnumerable<Sample> source)
    {
        Items = new ObservableTestCollection<Sample>(this, source);
    }
    public ObservableTestCollection<Sample> Items;

}

The Source of ObservableTestCollection is as follows:

public class ObservableTestCollection<T> : ObservableCollection<T>
{
    public T Parent;       
    public ObservableTestCollection(T parent)
    {
        Parent = parent;
    }
    public ObservableTestCollection(T parent, IEnumerable<T> source) : base(source)
    {
        Parent = parent;
    }
}

Code I write as

const string assemblyName = "SampleAssembly";
const string fieldName = "Items";
const string typeName = "Sample";
const string assemblyFileName = assemblyName + ".dll";

AppDomain domain = AppDomain.CurrentDomain;
AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(new AssemblyName(assemblyName), AssemblyBuilderAccess.RunAndSave);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName, assemblyFileName);

TypeBuilder typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public);

Type[] ctorParameters = new Type[] { typeBuilder };
Type typeOfCTS = typeof(ObservableTestCollection<>);
Type genericTypeOTS = typeOfCTS.MakeGenericType(typeBuilder);


FieldBuilder fieldBuilder = typeBuilder.DefineField(fieldName, genericTypeOTS, FieldAttributes.Public);

        //first constructor
ConstructorBuilder ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, Type.EmptyTypes);
ILGenerator generator = ctorBuilder.GetILGenerator();
        generator.Emit(OpCodes.Ldarg_0); //load this
        generator.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes)); //call object constructor

var ci = typeOfCTS.GetConstructors()[0];
generator.Emit(OpCodes.Newobj, ci);            
generator.Emit(OpCodes.Stfld, fieldBuilder); // store into Items
generator.Emit(OpCodes.Ret); //return


//second constructor
var typeOfIE = typeof(IEnumerable<>);
var genericTypeIE = typeOfIE.MakeGenericType(typeBuilder);          
ctorParameters = new Type[] {genericTypeIE };
ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, ctorParameters);

ctorParameters = new Type[] { typeBuilder, genericTypeIE };
generator = ctorBuilder.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0); //load this

ci = typeOfCTS.GetConstructors()[1];
generator.Emit(OpCodes.Newobj, ci);
generator.Emit(OpCodes.Stfld, fieldBuilder); // store into Items
generator.Emit(OpCodes.Ret); //return
Type type = typeBuilder.CreateType();
var obj = Activator.CreateInstance(type);
assemblyBuilder.Save(assemblyFileName);

I can't create instance of Sample Any one can help me correct this problem.

Your help would be much appreciated.





Is it possible to bind to a property using reflection in WPF?

I'm writing code to generate a bunch of textboxes attached to property. Is there any way you can set the source to a property found using reflection, stored as PropertyInfo?

Code for going through the properties:

foreach(PropertyInfo prop in GetType().GetProperties())
            {
                UI.Text ctrl = new UI.Text(prop.Name, prop.GetValue(this).ToString(), prop);
                sp.Children.Add(ctrl);
            }

(Note: UI.Text is a custom control that contains the textbox, and sp is a StackPanel)

Binding code:

        Binding bind = new Binding() { Source = prop };
        if (prop.CanWrite)
        {
            TextBox.SetBinding(TextBox.TextProperty, bind);
        }
        else
        {
            TextBox.IsEnabled = false;
        }

I currently get the error "Two-way binding requires Path or XPath" which usually occurs when trying to bind to a read-only property. Since the code is protected against that, it's obvious that simply binding to the PropertyInfo doesn't bind to the property itself.





Easy Way to Perform C# Null Check in a Type Conversion

I am doing some quick type conversions in a project I am not that very familiar with.

They look similar to this:

var NewType = new
{
    NewTypeId = old.SubType == null ? 0 : old.SubType.SubTypeId ?? 0,
    OtherType = old.OtherType ?? "",
    Review = old.CustomerComments ?? "",
    Country = old.Country == null ? "" : old.Country.Abbreviation ?? "",
    Customer = old.SubType == null ? "" :
                    old.SubType.Customer == null ? "" :
                        old.SubType.Customer.Name ?? ""
};

The objects I'm converting are usually Entity Framework objects. I also don't have the ability to modify the classes I will be converting form.

Is there an easier way to check for nulls, specifically for situations like this where any of the sub-objects could be null?

OldType.SubType.AnotherSubType.SomeProperty





Getting fields of a class from Element

I have created a custom annotation and used that in a class as follows:

@Reportable
public class CustomerModel extends BaseModel {
    public String CustomerName;
    public int orderCount;
}

In annotation processor I have all elements that have been annotated with @Reportable using the following code:

 Set<? extends javax.lang.model.element.Element> elements = 
roundEnv.getElementsAnnotatedWith(Reportable.class);

How can I get fields of that classes? I want to list all properties of CustomerModel





lundi 26 décembre 2016

How to: Reflection Emit Derived by ObservableCollection

I want to create dynamic type with refelction emit like: public class ObservableTestColleciton<T> : ObservableCollection<T> { public T Parent { get; set; } public ObservableTestColleciton(T parent) { Parent = parent; } public ObservableTestColleciton(T parent, IEnumerable<T> source):base(source) { Parent = parent; } } The code I could not complete is this like:

' AppDomain myDomain = AppDomain.CurrentDomain; AssemblyName myAsmName = new AssemblyName("AAB"); AssemblyBuilder myAssembly = myDomain.DefineDynamicAssembly(myAsmName,AssemblyBuilderAccess.Save); ModuleBuilder myModule = myAssembly.DefineDynamicModule(myAsmName.Name,myAsmName.Name + ".dll"); TypeBuilder myType = myModule.DefineType("ObservableTestCollection", TypeAttributes.Class | TypeAttributes.Public);

string[] typeParamNames = { "T" };
GenericTypeParameterBuilder[] typeParams = myType.DefineGenericParameters(typeParamNames);

Type observableOf = typeof(ObservableCollection<>);
Type genOb = observableOf.MakeGenericType(typeParams[0]);          
FieldBuilder myField = myType.DefineField("Parent", typeParams[0], FieldAttributes.Public);
ConstructorBuilder constructor = myType.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, Type.EmptyTypes);         

var type = myType.CreateType();
var obj = Activator.CreateInstance(type);
myAssembly.Save("AAB.dll");'





Invoke method from base class using reflection

I implemented generic repository pattern and unitofwork. I used basic patterns and they work great. In project I have requirement which says, every table has several fields which contains long, really long text, and user should have ability chose and open any of it. As each field named differently i decided to use power ov generics with reflection, to write method which resieves table name and field name and returns it. Generic method i wrote looks like this, it seems work properly

public string GetPropertyByName(int id, string property)
        {
            TEntity model =  this.Get(id);            
            var obj = model.GetType().GetProperty(property).GetValue(model, null);
            return obj != null ?  obj.ToString() : null;
        }

I have problem on invoking this method in business layer. I tried this:

public string GetHistory(string tableName, string fieldName, int id)
    {
        var prop = unitOfWork.GetType().GetProperty(tableName);
        MethodInfo method = prop.PropertyType.GetMethod("GetPropertyByName");
        var res = method.Invoke(prop, new object[] { id, fieldName });
        return (string)res;
    }

Which returns System.Reflection.TargetException. As I understood the problem is whith unitofwork implementation. In this pattern we create property:

public ICompanyRepo Company { get; private set; }

And then in constructor bind it with implementation:

Company = new CompanyRepo();

In my invoke method "prop" is type of interface (ICompanyRepo), but invoke's target should be interface implementation class, in this case "CompanyRepo". I could not find how to identify type of implementetion class, and solve this problem. Any help is appropriated





C# GetMethod info of Queryable class

I'm new at Reflection and I was trying the below peice of code

var queryableLastMethodInfo = typeof(Queryable).GetMethod("Last", new Type[]{ typeof(IQueryable<>) });

but queryableLastMethodInfo always returns null.

Could you please help?





C# Reflection Vs. method Attributes

I am trying to create a Log4Net wrapper interface. The code for the Interface:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PlayGround
{
    public interface ILogger
    {
        void SetSource(string typeName);

    /// <summary>
    /// Provide Log "message" and/or "exception" data only
    /// </summary>
    /// <param name="message"></param>
    /// <param name="exception"></param>
    /// <param name="memberName"></param>
    /// <param name="sourceFilePath"></param>
    /// <param name="sourceLineNumber"></param>
    void Error(string message, Exception exception = null,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = null,
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = null,
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0);

    /// <summary>
    /// Provide Log "message" and/or "exception" data only
    /// </summary>
    /// <param name="message"></param>
    /// <param name="exception"></param>
    /// <param name="memberName"></param>
    /// <param name="sourceFilePath"></param>
    /// <param name="sourceLineNumber"></param>
    void Warn(string message, Exception exception = null,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = null,
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = null,
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0);

    /// <summary>
    /// Provide Log "message" and/or "exception" data only
    /// </summary>
    /// <param name="message"></param>
    /// <param name="exception"></param>
    /// <param name="memberName"></param>
    /// <param name="sourceFilePath"></param>
    /// <param name="sourceLineNumber"></param>
    void Debug(string message, Exception exception = null,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = null,
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = null,
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0);

    /// <summary>
    /// Provide Log "message" and/or "exception" data only
    /// </summary>
    /// <param name="message"></param>
    /// <param name="exception"></param>
    /// <param name="memberName"></param>
    /// <param name="sourceFilePath"></param>
    /// <param name="sourceLineNumber"></param>
    void Info(string message, Exception exception = null,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = null,
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = null,
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0);

    /// <summary>
    /// Provide Log "message" and/or "exception" data only
    /// </summary>
    /// <param name="message"></param>
    /// <param name="exception"></param>
    /// <param name="memberName"></param>
    /// <param name="sourceFilePath"></param>
    /// <param name="sourceLineNumber"></param>
    void Fatal(string message, Exception exception = null,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = null,
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = null,
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0);
    }
}

The implementation:

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PlayGround
{
    class Log4NetLogger : ILogger
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Log4NetLogger));
        private static readonly bool isErrorEnabled = log.IsErrorEnabled;
        private static readonly bool isWarnEnabled = log.IsWarnEnabled;
        private static readonly bool isDebugEnabled = log.IsDebugEnabled;
        private static readonly bool isInfoEnabled = log.IsInfoEnabled;
        private static readonly bool isFatalEnabled = log.IsFatalEnabled;

    private string TypeName;

    public void SetSource(string typeName)
    {
        TypeName = typeName;
    }

    public void Error(string message, Exception Exception = null, string memberName = null, string sourceFilePath = null, int sourceLineNumber = 0)
    {
        if (isErrorEnabled)
        {
            string Message = BuildSourceDetails(message, memberName, sourceFilePath, sourceLineNumber);

            if (Exception != null)
            {
                Message += BuildExceptionMsg(Exception.Message);
            }

            log.Error(Message);
        }
    }

    public void Warn(string message, Exception Exception = null, string memberName = null, string sourceFilePath = null, int sourceLineNumber = 0)
    {
        if (isWarnEnabled)
        {
            string Message = BuildSourceDetails(message, memberName, sourceFilePath, sourceLineNumber);

            if (Exception != null)
            {
                Message += BuildExceptionMsg(Exception.Message);
            }

            log.Warn(Message);
        }
    }

    public void Debug(string message, Exception Exception = null, string memberName = null, string sourceFilePath = null, int sourceLineNumber = 0)
    {
        if (isDebugEnabled)
        {
            string Message = BuildSourceDetails(message, memberName, sourceFilePath, sourceLineNumber);

            if (Exception != null)
            {
                Message += BuildExceptionMsg(Exception.Message);
            }

            log.Debug(Message);
        }
    }

    public void Info(string message, Exception Exception = null, string memberName = null, string sourceFilePath = null, int sourceLineNumber = 0)
    {
        if (isInfoEnabled)
        {
            string Message = BuildSourceDetails(message, memberName, sourceFilePath, sourceLineNumber);

            if (Exception != null)
            {
                Message += BuildExceptionMsg(Exception.Message);
            }

            log.Info(Message);
        }
    }

    public void Fatal(string message, Exception Exception = null, string memberName = null, string sourceFilePath = null, int sourceLineNumber = 0)
    {
        if (isFatalEnabled)
        {
            string Message = BuildSourceDetails(message, memberName, sourceFilePath, sourceLineNumber);

            if (Exception != null)
            {
                Message += BuildExceptionMsg(Exception.Message);
            }

            log.Fatal(Message);
        }
    }

    private string BuildSourceDetails(string message, string memberName, string sourceFilePath, int sourceLineNumber)
    {
        return "[Class: " + TypeName + " Member: " + memberName + " Source: " + sourceFilePath + " Line: " + sourceLineNumber + "] [" + message + "]";
    }

        private string BuildExceptionMsg(string message)
        {
            return " [System Exception: " + message + "] ";
        }
    }
}

I believe from a performance point of view the code works based on the online research I have carried out.

The question being; instead of using Attributes within the interface, is there an approach using C# Reflection so that I can move the code for Logging to the concrete implementation only? This way the interface is more generic?

Thank you kindly.





How to cide a checkStyle method in Java?

Our teacher asked us to make a method which takes a Class as a parameter then checks the fields and methods if they follow the rules of Checkstyle (Upper case, lower case, final attribute, etc.)

He gave us a piece of code to start with but I don't know what to do next.

public class CheckStyle {
    static String  valider(Class c){
        Field[] tattribut = c.getDeclaredFields();
        String name = c.getName();
        Method[] tmethod=c.getDeclaredMethods();
    }   

    public static void main(String[] args) {
        String error = CheckStyle.valider(a.class);
        System.out.println(error);
    }
}





dimanche 25 décembre 2016

JAVA - How to get package distance when Initial Class Loader

I have class file from cloud network, for sample test on my project.

I want test this file using reflection. so I must initial class using class loader.

for e.g

File file = new File("path");
URL[] cp = 
{
    file.getParentFile().toURI().toURL()
};
URLClassLoader urlcl = new URLClassLoader(cp);
Class cls = urlcl.loadClass(file.getName().replaceAll("\\.class", ""));

so I get an error because I don't know package that included class like com.mypackage:

Exception in thread "main" java.lang.NoClassDefFoundError: packclass (wrongname: dirclass\packclass)

so, my question how can I know package that included to my class file.





samedi 24 décembre 2016

Store and access data from reflection

I have a jar file, which is used by 2 different applications. In this jar file a have some models annotated with special annotation:

public interface Component {
   // title, image and other properties
   String getId();
}

@ComponentToParse
public class Component1 implements Component {
   //
}

@ComponentToParse
public class Component2 implements Component {
   //
}

In first application these models are listed into ComboBox and then id of selected component is copied to clipboard;

In second application i click paste and need to create this Component by id.

So, i need at least two classes:

  1. Class, which returns all components or return components by some category etc.(DAO, Repository etc)
  2. Class, which creates components by id.

My current solution is:

  1. ComponentsRepository (implementation of Repository, has getAll(), getByCategory() and others), it calls ComponentsFactory.createAll() when constructs.
  2. ComponentsFactory (implementation of Factory, has create(String id) and createAll which return list of all Components). In this class i use reflection methods.

But i think createAll in factory is very bad solution.

What is the correct way to do this?





What does the "+<>c__DisplayClass2_0" suffix mean in some CLR type names?

When listing the fullnames of the types contained in a CLR assembly, some types are suffixed with the following: "+<>c__DisplayClass2_0".

For Example:

CustomNameSpace.SomeClass+<>c__DisplayClass2_0

What does this mean?





Get a struct's field names

I want to use a struct's field names for metaprogramming.

For example:

(struct pt [x y])
(struct-fields pt) ;; -> '(x y)





vendredi 23 décembre 2016

how to cast generic class in run-time, java8

everyone.

I am trying to cast generic class in run-time, java8.
I want to cast object to generic class ( such like List< String >, ArrayList< Integer >).
However, String or Integer is not determined in my situation, compile-time.
But I know the name of the classes( "String" or "Integer" ).
So, I think I can get Class by using reflection.
But I don't know how to do it. Is it possible? and What should I do?

List<String> list = new ArrayList<>();
list.add("hoge");

Object obj = (Object) list;
String className = "String";

List<String> list2 = /* do something to get this */
// (List<String>)list is NG. obj and className can be used only.





Returning error value in reflect.MakeFunc

I am trying to create an return a function in golang which has a return type of (SomeStruct, error) (standard error interface)

fn := func (args []reflect.Value) []reflect.Value {
    database := mongoConnectorInstance.GetDatabase()
    defer database.Session.Close()

    selector := bson.M{
        field : args[0].Interface(),
    }

    newValue := reflect.New(fieldFunctionValue.Type().Out(0))
    newValueInterface := newValue.Interface()
    fmt.Println(reflect.TypeOf(newValueInterface))

    err := database.C(collection).Find(selector).One(newValueInterface)

    secondValue := reflect.ValueOf(err)
    return []reflect.Value {
        newValue.Elem(),
        secondValue,
    }
}

resultFunctionValue := reflect.MakeFunc(fieldFunctionValue.Type(), fn)

If err returned by .One function is null, I get address pointer error on this line, internally in golang :

panic("reflect: function created by MakeFunc using " + funcName(f) +
                    " returned wrong type: have " +
                    out[i].typ.String() + " for " + typ.String())

I have tried to change the line of secondValue assignment to :

secondValue := reflect.ValueOf((error)(nil)) 

in the case where err == nil, however the problem did not go away.

If I create a dummy error struct that implements the interface error and return that, ignoring error return value has to be nil when it is really nil, then it complains that the return value by the function made by makeFunc is incorrect

Can you think of a way to solve this problem? (Except wrapping the error in a struct, and changing the return type to that struct instead )





Block reflection field/method access from classloader

I'm doing a plugin system with a security manager to restrict the plugin's actions. My problem is, it will be easy to bypass the system when people are able to access every field using reflection.

I don't want to block reflection for everything, because it is useful to use reflection sometimes. Now my question is, is there a way to block reflection only for some fields/method when they are accessed from a certain classloader? (I want to access them myself, so I can't work with Reflection field filters)





Mono: CustomAttributeExtensions

I use the method GetCustomAttributes from the extension class CustomAttributeExtensions:

var serviceInterface = service.GetInterfaces().FirstOrDefault(i => i.GetCustomAttributes().Contains(new ServiceContractAttribute()));

When I run my application under mono 4.0 on debian I get the following exception:

Missing method GetCustomAttributes in assembly /root/mkmServer/MKMWatcher.Services.exe, type System.Reflection.CustomAttributeExtensions

Unhandled Exception: System.TypeLoadException: Could not load type 'System.Reflection.CustomAttributeExtensions' from assembly 'MKMWatcher.Services'.
  at System.Linq.Enumerable.First[Type] (IEnumerable`1 source, System.Func`2 predicate, Fallback fallback) [0x00000] in <filename unknown>:0
  at System.Linq.Enumerable.FirstOrDefault[Type] (IEnumerable`1 source, System.Func`2 predicate) [0x00000] in <filename unknown>:0
  at MKMWatcher.Services.ServiceManager.CreateService (System.Type service, System.String serviceAddress) [0x00000] in <filename unknown>:0
  at MKMWatcher.Services.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.TypeLoadException: Could not load type 'System.Reflection.CustomAttributeExtensions' from assembly 'MKMWatcher.Services'.
  at System.Linq.Enumerable.First[Type] (IEnumerable`1 source, System.Func`2 predicate, Fallback fallback) [0x00000] in <filename unknown>:0
  at System.Linq.Enumerable.FirstOrDefault[Type] (IEnumerable`1 source, System.Func`2 predicate) [0x00000] in <filename unknown>:0
  at MKMWatcher.Services.ServiceManager.CreateService (System.Type service, System.String serviceAddress) [0x00000] in <filename unknown>:0
  at MKMWatcher.Services.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0

When I decompile the mscorlib.dll from mono which should contain the class I don't find it in his namespace:

enter image description here

But when I take a look at the mono github repository, the class is present: http://ift.tt/2hyyAz1

Do you know what's happening ? Are the assemblies deployed in the latest version of mono not reflecting... their source code ? The file haven't been touched for a while and it's not like it was a new feature... Any ideas ? Any solution that does not involve for me to get the latest mono source and compile them by hand ?

Thank you in advance for you answers.





Differentiate between staticmethd and instancemethod with Class and not its instance

I am trying to find out all instance but not static methods of a class. Furthermore, I am constrained not to create instance of the class (constructor is complex, and required many setups). However, type of both static and instance method is FunctionType as accessed via Class, as shown below.

import types
import inspect

class TestType():

    @staticmethod
    def test_staticmethod():
        pass 

    def test_instancemethod(self):
        pass

test_type = TestType()

print(type(TestType.test_staticmethod)) #<class 'function'>
print(type(TestType.test_instancemethod)) # <class 'function'>

print(type(test_type.test_staticmethod)) #<class 'function'>
print(type(test_type.test_instancemethod)) #<class 'method'>

Are there ways, I can distinguish between instance method and static method, just by accessing them from the Class and not its instance?





FieldInfo get subfield from field

Good day,

I need to make function that will iterate on Dictionary that stores variable name and variable value. After that, I need to update class variable with that value.

void UpdateValues(Type type, Dictionary<string, string> values)
{
    foreach (var value in values)
    {
        var fieldInfo = selected.GetComponent(type).GetType().GetField(value.Key);
        if (fieldInfo == null) continue;

        fieldInfo.SetValue(selected.GetComponent(type), value.Value);
    }
}

It works but I want little improvement and I absolutely don't know if it is possible. As you can see, that function can accept any class, not just one specific.

If I have class like this

class test
{
    public string age;
}

And I would use function this way, it would work.

UpdateValues(typeof(test), new Dictionary<string, string>age);

Problem is if I have class like this and I would like to update "subfield" (field in field)

class test
{
    public string age;
}

class test2
{
    public test data;
}

I was thinking that syntax could be something like this, but I have no idea how could I do it.

UpdateValues(typeof(test2), new Dictionary<string, string>data.age);

To sum it up, I need to make function that will take class that is stored in another class. Function will iterate trough the dictionary and update fields of class and even her subfields.





jeudi 22 décembre 2016

Reflection to automatically initiate implementations

I'm trying to use reflection to make it easier for me to add impl classes.

This is how I'm trying to use it:

This is in my main class (Person.java)

public MyHouse myHouse;

Then this is what initiates it:

myHouse = new MyHouse();
myHouse.setPerson(this);

So what I'm trying to do is use reflection and an abstract class to automatically execute the 2 both codes.

The problem is, I can execute: myHouse.setPerson(this);

by using setPerson as an abstract method, but how can I execute myHouse = new MyHouse(); ? Obviously the class I am trying to initiate will be called MyHouse.java, so perhaps something to do with class.getSimpleName() and format it with a lowercase first letter to find the field?

For example, after formatting the class's simple name, it will be equal to "myHouse" which is what the field is called in the Person class, but is still just a String, so how would I do that?

I know the literature is quite confusing any questions please ask below.





C#: Get name of specific Exception

Is this the best method for getting the name of a specific Exception in C#:

ex.GetType().ToString()

It is in a generic exception handler:

catch (Exception ex)





Dynamically convert List

I have a list, the type of the object will be found only at the runtime through reflection. But when I try to assign the list to the actual entity, it is throwing error as "object cannot be converted". Below is the code,

`Var obj = New List<Object>();
obj.Add(cust1);
obj.Add(Cust2);
Type t = t.GetProperty("Customer").PropertyType// I will get type from property
var data= Convert.ChangeType(obj,t); //This line throws error`





Get property values of properties of types derived from certain type in TypeScript?

I have an abstract class Section that will be used to represent a section of a document that can be either valid or invalid. Such sections can also have embedded sections. A section cannot be valid if it contains an invalid inner section.

I created classes ASection1 and ASection2 for the purpose of use them as inner sections of MySection, to which the validation process is invoked by means of performValidation().

How do I get the properties of types derived from class MySection. I need help on the abstract class reflection logic as commented below.

 abstract class Section {

   constructor(public name: string) {
   }

   performValidation(): boolean {

       let result: boolean = true;

       //HELP IS NEEDED HERE!!!
       //get all properties of this instance 
       //whose type inherit from "Section"
       //and execute Validate() on each of them
       //one at a time, if any of them returns
       //false, return false.

       return this.Validate();
   }

   abstract Validate(): boolean; 
 }

 class ASection1 extends Section {
    constructor() {
       super("Section example 1"); 
    }
    Validate(): boolean {
       //validation logic goes here
    }
 }

 class ASection2 extends Section {
    constructor() {
       super("Section example 2"); 
    }
    Validate(): boolean {
       //validation logic goes here
    }
 }

class MySection extends Section {

   constructor() {
      super("My Section"); 
   }

   subsection1: ASection1;
   subsection2: ASection2;

   prop1: number;

   Validate(): boolean {
      return this.prop1 > 100;
   }

}

//run

let mySect = new MySection();
mySect.prop1 = 101;
mySect.subsection1 = new ASection1();
mySect.subsection2 = new ASection2();
mySect.performValidation();  

Thanks.





mercredi 21 décembre 2016

How can I call a generic WebAPI action from JavaScript?

How can I call a generic WebAPI action from JavaScript? and pass the T type.

public class ClassUtilitiesController : ApiController
{
    [HttpPost]
    public string GetClassNamespace<T>()
    {
        return typeof(T).FullName;
    }
}

I need an action that returns something from input T type. What should I do





Getting Field names for all objects from an arary of Objects in Java

I have an Array of object

Object ob1 = new Object(); //Object1
Object ob2 = new Object(); //Object2

Object [] array = {
         ob1,
        ob2

        };

I want to get name of Object1 and Object1 which is ob1 and ob2 respectively





Need help implementing a custom hibernate validation annotation

So I am trying to create a custom hibernate annotation for checking if the value already exists in the database. This validation is within a Spring Boot Web Application. I am having difficulty writing the annotation in a way that is loosely coupled and reusable. I was using reflection but as stated here, I shouldn't try to access private fields by Field.setAccessible(true). At this point I am stumped and need advice on the best possible way to achieve this. This is quite a complex problem for my skill level which happens to be the first time I have used reflection or created an annotation.

Rough Draft of annotation

@Target( { ElementType.TYPE })
@Retention( RetentionPolicy.RUNTIME)
@Constraint(validatedBy = NotDuplicate.NotDuplicateValidator.class)
@Documented
public @interface NotDuplicate {

    String message() default "A duplicate was found.";

    Class<?> respository();

    String methodName();

    public static class NotDuplicateValidator implements ConstraintValidator<NotDuplicate, Object> {

        @Autowired
        Class<?> respository;

        String methodName;

        public void initialize(NotDuplicate constraintAnnotation) {
            this.respository = constraintAnnotation.respository();
            this.methodName = constraintAnnotation.methodName();
        }


        public boolean isValid(Object object, ConstraintValidatorContext constraintContext) {

            if (object == null) {
                // Bean Validation specification recommends to consider null values as being valid unless annotated @NotNull
                return true;
            }

            try {

                Method method = respository.getMethod(methodName, String.class);
                List<?> resultSet = method.invoke(respository, someFieldValue);
                if (resultSet == null){
                    return false;
                }
                return true;

            } catch (Exception e) {
                System.printStackTrace(e);
                return false;
            }
        }
    }
}

Sample usage of annotation based on vision

@NotDuplicate(respository = UserRepository.class, methodName = "findByEmailAddressIgnoreCase")
private String email;    

The user repository

public interface UserRepository extends CrudRepository<User, Integer> {

    List<User> findByEmailAddressIgnoreCase(String emailAddress);
}





Accessing a Components Property prior to the Instantiation

I have the following problem: I have a list of Components, that contain Rectangles with a width of either 200 or 800. I'd like to filter this list, and only create objects of the Rectangles with a width of 200 as I work on a small screen.

Preferably I do not want to create all objects, check their width, and destroy those with the wrong width again. For obvious reasons I really only want to create those with a width of 200.

To do this I would need to aquire knowledge of the width, before I instantiate them. As far as I have seen, there is no publicly available and documented way of introspecting/reflecting the Component prior to it's instantiation.

My question is: Is there a non-public way to gain knowledge about what is packaged inside of my Component?





Using generic type to create instance instead of reflection in java

I have code that looks like follows:

public class Person{
    private Configuration configuration;
    public void act(){
        final Action action = new Factory().createAction(configuration);
        ....
    }
}

public class Factory{
    public Action createAction(Configuration configuration){
        Constructor<? extends Action> constructor =
                  configuration.getActionClass.
                  getConstructor(configuration.getClass());
        return constructor.newInstance(configuration);
    }
}

public class Configuration{
    private Class<? extend Action> actionClass;

    public void setActionClass(Class<? extend Action> cls){
        this.actionClass = cls;
    }

    public Class<? extend Action> getActionClass(){
        return this.actionClass;
    }
}

Each time act() is called, a new Action instance is created for some reason. I need to subclass Action and pass it to act().

So I use reflection on a factory method to achieve that. But it seems overkill and not type safe.

Is it possible to repalce reflection with a type safe method such like generics?





How to solve InaccessibleObjectException ("Unable to make {member} accessible: module {A} does not 'opens {package}' to {B}") on Java 9?

This exception occurs in a wide variety of scenarios when running an application on Java 9. Certain libraries and frameworks (Spring, Hibernate, JAXB) are particularly prone to it. Here's an example from Javassist:

java.lang.reflect.InaccessibleObjectException: Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @1941a8ff
    at http://ift.tt/2h9UsTo
    at http://ift.tt/2ifaNUu
    at http://ift.tt/2h9KH7L
    at http://ift.tt/2ifkG4E
    at javassist.util.proxy.SecurityActions.setAccessible(SecurityActions.java:102)
    at javassist.util.proxy.FactoryHelper.toClass2(FactoryHelper.java:180)
    at javassist.util.proxy.FactoryHelper.toClass(FactoryHelper.java:163)
    at javassist.util.proxy.ProxyFactory.createClass3(ProxyFactory.java:501)
    at javassist.util.proxy.ProxyFactory.createClass2(ProxyFactory.java:486)
    at javassist.util.proxy.ProxyFactory.createClass1(ProxyFactory.java:422)
    at javassist.util.proxy.ProxyFactory.createClass(ProxyFactory.java:394)

The message says:

Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain) throws java.lang.ClassFormatError accessible: module java.base does not "opens java.lang" to unnamed module @1941a8ff

What can be done to avoid the exception and have the program run successfully?





Convert object content to json string

I'm using reflection to deserialize object from binary stream ("objType=SM.Backend.Entities.Erp.CodeListBase"):

var methodInfo = typeof(SM.Core.Serializator).GetMethod("DeserializeCache");
var genericMethod = methodInfo.MakeGenericMethod(objType);
var _objItem = genericMethod.Invoke(null, new[] { _streamedData });

It works. If I inspect _objItem in Locals window it looks like:_objItem

Now i would like to export _objItem content to json string:

var jsonString=JsonConvert.SerializeObject(_objItem, Formatting.Indented);

But result is empty: "[]". If I do the same for other objects it works. I guess for this object it doesn't work because it is complex type(nested):

SM.Backend.Entities.Erp.CodeListBase{SM.Backend.Entities.Erp.CodeList<SM.Backend.Entities.Erp.MaterialType>}.

Any idea how to extract the content from locals to json string? Should I convert object to different type first?





Resolving Generic Interface with Autofac

These are my classes:

    public interface ICommandDtc{
            string Command { get; set; }
            string Xml { get; set; }
        }


     public interface ICommandHandler<in TCommand>
            where TCommand : ICommandDtc
        {
            CommandResult Execute(TCommand command);
            Task<CommandResult> ExecuteAsync(TCommand command);
        }
    public class CommandResult
        {

            public string Description { get; set; }
            public int Code { get; set; }
        }
    public interface ICommandBus{
        Task<CommandResult> SubmitAsync<TCommand>(TCommand command) where TCommand : ICommandDtc;
        CommandResult Submit<TCommand>(TCommand command) where TCommand : ICommandDtc;
    }
    public class CommandBus : ICommandBus{
        private readonly ILifetimeScope _container;
        public CommandBus(ILifetimeScope scope){
            _container = scope;
        }
        public async Task<CommandResult> SubmitAsync<TCommand>(TCommand command)
            where TCommand : ICommandDtc{
            var commandHandler = _container.Resolve<ICommandHandler<TCommand>>();
            return await commandHandler.ExecuteAsync(command);
        }
        public CommandResult Submit<TCommand>(TCommand command)
            where TCommand : ICommandDtc
{
**//its worked**
            var commandHandler = _container.Resolve<ICommandHandler<IntegerationCommand>>();
**//exception**
            var commandHandler2 = _container.Resolve<ICommandHandler<TCommand>>();
            return commandHandler2.Execute(command);
        }
    }
    public abstract class CommandBase<TCommand> : ICommandHandler<TCommand>
        where TCommand : ICommandDtc{
        public async Task<CommandResult> ExecuteAsync(TCommand command){
            var commandResult = new CommandResult();
            try{
                commandResult = await InternalExecuteAsync(command);
            }

            catch (Exception exp){

            }
            return commandResult;
        }
        public CommandResult Execute(TCommand command)
        {
            var commandResult = new CommandResult();
            try
            {
                commandResult =  InternalExecute(command);
            }
            catch (Exception exp)
            {
            }
            return commandResult;
        }

        protected abstract Task<CommandResult> InternalExecuteAsync(TCommand command);
        protected abstract CommandResult InternalExecute(TCommand command);
    }
 public class IntegerationCommandHandler : CommandBase<IntegerationCommand>
    {
        protected override Task<CommandResult> InternalExecuteAsync(IntegerationCommand command){
            throw new System.NotImplementedException();
        }
        protected override CommandResult InternalExecute(IntegerationCommand command){
            switch (command.Command) {
                case "SendDocument":
                    return SendDocument(command.Xml);
            }
            return new CommandResult {Code = 5,Description = ""};
        }
        private CommandResult SendDocument(string xml){
            throw new System.NotImplementedException();
        }
    }

and my Autofac :

   public static IContainer InitializeBusiness()
        {
            if (_lifetimeScope != null)
            {
                _lifetimeScope.Dispose();
                _lifetimeScope = null;
            }
            ConfigureAutoMapper();
            var builder = new ContainerBuilder();
            builder.RegisterType<Bootstrapper>().AsSelf();
            var assemblies = Assemblies.GetBusinessAssemblies.ToArray();
            builder.RegisterAssemblyTypes(assemblies).AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(ICommandDtc))).Named<ICommandDtc>(x => x.Name);

            builder.RegisterType<AutoFacValidatorFactory>().As<IValidatorFactory>();

            _container = builder.Build();
            return _container;
        }

I tried to use :

try
            {

          var addFormDtc=new AddFormDtc {CommandName = "SendDocument",SiteCollectionName = "IntegerationCommand",Xml = "1"};
                var obj = _scope.ResolveNamed<ICommandDtc>(addFormDtc.SiteCollectionName);
                obj.Command = addFormDtc.CommandName;
                obj.Xml = addFormDtc.Xml;
                var commandBus = _scope.Resolve<ICommandBus>();
                return commandBus.Submit(obj);
            }
            catch (Exception ex){
                comandResult.Code = 0;
                comandResult.Description = ex.Message;
                return comandResult;
            }

But I'm getting exception in this line :

var commandHandler2 = _container.Resolve<ICommandHandler<TCommand>>();

when i tried manually its worked :

var commandHandler = _container.Resolve<ICommandHandler<IntegerationCommand>>();

exception :

The requested service 'JahadServices.Business.Services.Command.ICommandHandler`1[[JahadServices.Business.Dtos.Command.ICommandDtc, JahadServices.Business.Dtos, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' has not been registered. To avoid this exception, either register a component to provide the service, check for service registration using IsRegistered(), or use the ResolveOptional() method to resolve an optional dependency.





How to get the correct process id of a Process

Using the jna library to get the windows process id as adviced in other questions here on stackoverflow.

String command = "cmd /c start cmd.exe";
Process process = Runtime.getRuntime().exec(command);
long pid = windowsProcessId(process);

private static Long windowsProcessId(Process process) {
    if (process.getClass().getName().equals("java.lang.Win32Process")
            || process.getClass().getName().equals("java.lang.ProcessImpl")) {
        /* determine the pid on windows plattforms */
        try {
            Field f = process.getClass().getDeclaredField("handle");
            f.setAccessible(true);
            long handl = f.getLong(process);

            Kernel32 kernel = Kernel32.INSTANCE;
            WinNT.HANDLE handle = new WinNT.HANDLE();
            handle.setPointer(Pointer.createConstant(handl));
            int ret = kernel.GetProcessId(handle);
            return Long.valueOf(ret);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
    return null;
}

This however never returns the correct process id of the just started process, rather something random but usually close to the actual id. How do I get the correct process id?





mardi 20 décembre 2016

D language: Iterate over members of a struct and check a UDA (runtime reflection)

In D language, I want to iterate over a structure and perform logic specific to each annotation attached to each member. Ex.

struct Pattern {
    string pattern;
}

string Max {
    int max;
}

string Min {
    int min;
}

struct StructToValidate {
    @Pattern("^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$")
    string phone;

    @Max(20)
    @Min(3)
    int someValue;
}

and then in a function, do something like this:

int main() {
    StructToValidate struct;

    // begin pseudocode
    // for each member of struct mem = [phone, someValue] {
    //     if (hasUDA!(mem, Pattern)) {
    //         do stuff like validation on the runtime value of this member
    //     } else if (hasUDA!(mem, Min)) {
    //         ...
    //     } else if (hasUDA!(mem, Max)) {
    //         ...
    //     }
    // }
    //
    return 0;
}

How do I do this?





How do you get the Discriminated Union Type from a Case instance?

Given these two Discriminated Unions I'd like to get the DeclaringType case.

type SingleCaseUnion =
    | One

type MultiCaseUnion =
    | Two
    | Three

An example for each case would be as follows:

getDiscriminatedUnionType One = typeof<SingleCaseUnion> // true

getDiscriminatedUnionType Three = typeof<MultiCaseUnion> // true


My first attempt was to get the case type and get it's base class, this works because in F# a subtype is created for each case.

MultiCaseUnion.Two.GetType().BaseType = typeof<MultiCaseUnion> // true

However, for a single case union this doesn't work because no nested types are created.

SingleCaseUnion.One.GetType().BaseType = typeof<SingleCaseUnion> // false


My second attempt, which aimed to get a more robust solution was to use the FSharp Reflection helpers.

FSharpType.GetUnionCases(unionValue.GetType()).First().DeclaringType

This does work for all cases but it has to generate UnionCaseInfo instances for each case which seems somewhat unnecessary.

Is there Something built in that I may have missed? Something like:

FSharpValue.GetUnionCase(SingleCaseUnion.One)





Getting the name of the declaring class?

Suppose I got a parent class and a child class:

public abstract class Parent
{
    public string GetParentName()
    {
        return GetType().Name;
    }
}

public class Child : Parent
{
    public string GetChildName()
    {
        return GetType().Name;
    }
}

As of current, both GetParentName() and GetChildName() will return Child.

However, in my scenario, I'd like to get the name of the class in which the method is declared.

Thus GetChildName() should return Child but GetParentName() should return Parent.

Is this by any means possible?

NOTE:

I understand that I could use GetType().BaseType.Name but this won't work since the hierarchy could be complex.





Java - How to link a class created by Javassist with JVM

This is the first time I ever use Javassist, I created a class using javassist and I added some methods to it, and now I want to know how to link it with the JVM. Here is the code I wrote:

package up.coo.tp10;

import java.io.DataOutputStream;
import java.io.FileOutputStream;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;

public class Main {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    ClassPool pool = ClassPool.getDefault();
    CtClass cc = pool.makeClass("COOUnitGenerator");
    try {
        CtMethod cm4 = CtNewMethod.make("public void test4(){System.out.println(\" === Method 4 === \");}", cc);
        CtMethod cm1 = CtNewMethod.make("public void test1(){System.out.println(\" === Method 1 === \");}", cc);
        CtMethod cm3 = CtNewMethod.make("public void test3(){System.out.println(\" === Method 3 === \");}", cc);
        CtMethod cm2 = CtNewMethod.make("public void test2(){System.out.println(\" === Method 2 === \");}", cc);
        CtMethod cmSetUp = CtNewMethod.make("public void setUp(){System.out.println(\" === Set Up === \");}", cc);

        cc.addMethod(cm4);
        cc.addMethod(cm1);
        cc.addMethod(cm3);
        cc.addMethod(cm2);
        cc.addMethod(cmSetUp);

    } catch (CannotCompileException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}





Loading referenced assemblies

Is a good idea to loading referenced assemblies like this:

public void Load(string assemblyFilePath)
{
    var assembly = Assembly.LoadFrom(assemblyFilePath);

    string assemblyDirectory = Path.GetDirectoryName(assemblyFilePath);
    var assembliesFilesPaths = Directory.GetFiles(assemblyDirectory, "*.dll");

    var referencedAssembliesNames = assembly.GetReferencedAssemblies();
    foreach (var referencedAssembliesName in referencedAssembliesNames)
    {
        var assemblyPath = assembliesFilesPaths.FirstOrDefault(path => Path.GetFileNameWithoutExtension(path) == referencedAssembliesName.Name);
        if (string.IsNullOrEmpty(assemblyPath))
            continue;

        Assembly.LoadFrom(assemblyPath);
    }
}

I would like to load assembly and have access to types which are defined in another (referenced) assembly.





Spark Dataframe schema definition using reflection with case classes and column name aliases

I ran into a little problem with my Spark Scala script. Basically I have raw data which I am doing aggregations on and after grouping and counting etc I want to save the output to a specific JSON format.

  1. Let's say I have raw data in a dataframe with nested structs inside (I am using only one in this example).

    case class Person(Name: String, Gender: String, Age: Int)
    var p1 = Person("James", "male", 32)
    var p2 = Person("James", "male", 36)
    var p3 = Person("Anna", "female", 25)
    var dm = sqlContext.createDataFrame(Seq(("1",p1),("2",p2),("3",p3))).toDF("Id", "Person")
    
    
  2. Then I have a list of column names which should be used for grouping. The thing is that the amount of these column names may be different, therefore I want to add these grouping values as a new column of string arrays.

    For example, the following grouping parameters have been entered from an outside system (which doesn't have the nested structure):

    val cols = Seq("PersonName", "PersonGender")
    
    
  3. But as in Spark I would have to use full stops to get the child attributes, i.e Person.Name, I have to do some manual mapping of the names. I have a helper function for that:

    def matchColHeaders(name: String) : String = name match {
    case "PersonName" => "Person.Name"
    case "PersonGender" => "Person.Gender"
    case "PersonAge" => "Person.Age"
    case _ => name
    }
    
    var groupByList: Seq[org.apache.spark.sql.Column] = cols.map(p => col(matchColHeaders(p)).as(p))
    groupByList: Seq[org.apache.spark.sql.Column] = List(Person.Name AS PersonName#76, Person.Gender AS PersonGender#77)
    
    
  4. I am currently using initial grouping parameters as aliases for clarification. Mostly because there may rise a situation where the raw data has different types of structs, which may also contain attributes called "Name" and when I just use the helper function to map the initial string Seq to a new string Seq, not column Seq, then using Person.Name as a grouping parameter would leave Name as the resulting column name. And this way the result may contain identical column names which would make selecting by these columns throw an exception.

  5. Then I use this list in the groupBy function and add an alias to the column name:

    val ncColName = "NameCount"
    val grouped = dm.groupBy(groupByList:_*).agg(count("Id").as(ncColName))
    
    
  6. This currently results in a dataframe with 3 columns:

    +----------+------------+---------+
    |PersonName|PersonGender|NameCount|
    +----------+------------+---------+
    |      Anna|      female|        1|
    |     James|        male|        2|
    +----------+------------+---------+
    
    
  7. But as the amount of grouping parametes may differ, I want to add them all in a string array (because when I want to use case classes later, I cannot add attributes to a case class dynamically):

    import org.apache.spark.sql.functions._
    val gvColName = "GroupedValues"
    val groupedArrayDF = grouped.withColumn(gvColName, array((cols.map(c => col(c))):_*))
    
    
  8. Now when I create a case class with the structure I want for the resulting dataframe (which I want to write as a JSON), mapping each row to that class object using the variables of the column names (ncColName and gvColName), I get an "Task not serializable" exception:

    case class Result(GroupValues: Seq[String], Count: Long)
    
    val result = groupedArrayDF.map(row => Result(row.getAs(gvColName), row.getAs(ncColName))).toDF
    
    org.apache.spark.SparkException: Task not serializable
    ...
    Caused by: java.io.NotSerializableException: org.apache.spark.sql.Column
    Serialization stack:
    - object not serializable (class: org.apache.spark.sql.Column, value: Person.Name AS PersonName#54)
    
    

    This exception is thrown in the combination of using column names with aliases + using variables for the getAs function. Doesn't matter if I use string variables for column names or int variables for indices, still fails.

  9. When I hardcode the column names or indices, then everything works, but I want to use variables, not hardcode string values in my code:

    scala> val result = groupedArrayDF.map(row => Result(row.getAs("GroupedValues"), row.getAs("NameCount"))).toDF
    result: org.apache.spark.sql.DataFrame = [GroupValues: array<string>, Count: bigint]
    
    

    And when I use Seq("Person.Name", "Person.Gender"), then everything also works with the variables for column names or indices. But then I will run into the problem explained in point 4.

  10. And actually the final schema should be an array of these Result class objects. I still haven't figured out, how to do this as well. The expected result should have a schema like that:

    case class Test(var FilteredStatistics: Array[Result])
    val t = Test(Array(Result(Seq("Anna", "female"), 10L), Result(Seq("James", "male"), 22L)))
    
    val t2 = sc.parallelize(Seq(t)).toDF
    
    scala> t2.printSchema
    root
     |-- FilteredStatistics: array (nullable = true)
     |    |-- element: struct (containsNull = true)
     |    |    |-- GroupValues: array (nullable = true)
     |    |    |    |-- element: string (containsNull = true)
     |    |    |-- Count: long (nullable = false)
    
    

TL;DR:

  1. How to map dataframe rows to a case class object when dataframe columns have aliases and variables are used for column names?

  2. How to add these case class objects to an array?





lundi 19 décembre 2016

Is it possible to get the data type of the complex field of IEnumerable

Issue : When the filtering operation is performed based on the complex filed to the DataSource, Error has been thrown

Requirement : Need to get the Data type of the complex field attribute So that i can do the filtering operation on that Data Source.

I have defined my performFiltering Method as follows and it has two arguments

First argument : DataSource As IEnumerable Second argument : FilteredColumn as List

DataSource Holds the following data,

Order
{
  OrderID : Long
  EmployeeID : String
  Employee : Info
}

Info
{
     Address : String
}

and the "FilteredColumn" holds the following data

enter image description here

In this above pic, Field is set as Employee.Address, So i need to filter the Order DataBase Based on the Address Field.

How to get the Data Type of Address which is present inside in the Info class.

I have tried with the following way

        string[] splits = filteredColumn.Field.Split('.');
        var prop = dataSource.AsQueryable().ElementType.GetProperties();
        Type type = null;
        object value = null;
        foreach (var pro in prop)
        {
            if (splits.Length == 1)
            {
                if (pro.Name == filteredColumn.Field)
                    type = pro.PropertyType;
            }
            else
            {
                foreach (string split in splits)
                {
                    if(pro.Name == split)
                        type = pro.PropertyType;
                }
            }
        }

But I cannot able to get the Address data Type.

Could you please figure out my mistake in the above code block.





Java reflection API : How to get the list of Parameters in a method before trying to invoke it

I'm trying to invoke methods stored in an excel file. Got stuck when i could not solve the problem while trying to get the list of parameters before invoking the method. Some of methods have int,few have string and the rest have both

//read excel file using poi API, so assuming the method name is LaunchBrowser

MyClass c = new MyClass();

Class classObj = c.getClass();

Method[] m1 = classObj.getDeclaredMethods();

Class[] parameterTypes = m1[0].getParameterTypes();

System.out.println(parameterTypes[0]);

Method gs1Method = classObj.getMethod("LaunchBrowser",new Class[] {parameterTypes}); // got stuck here





How to change the result of a method in a class?

I know that using Proxy and InvocationHandler will work in interfaces.But how can I change the invoke method in a class?





better way for creating multiple instances from children abstract class without using class.newInstance java

I create school project in Greenfoot and I try creating one method which has two parameters, one for numbers of instances and second for a name of a class from which I want to create instances. Here is the concrete code:

private <T extends Actor> void manyActors(int many, Class<T> cls)
    {          
        try
        {
        for(int i=0;i<many;i++)
        {
            addObjectRnd( cls.newInstance() ); 
        }
    }
    catch(InstantiationException e)
    {
        some not important code
    }
    catch(IllegalAccessException e){
       ...
    }

I think this is not a good solution but I can't figure out how this problem solve in another way and possibly better. exist different and possibly better solution or only another option is it using a structure like array or List?





Dynamically convert property to Type

Is it possible to simplify this logic, Is there generic way to do it. The code finds marked attributes and parses it according to the attribute type. Please suggest some way to optimize this code, all the data type of Product class will be string, I'm getting product input as xml directly converting serialized data to a class with decimal,int,float will not give proper error message, If there is list of item it throws error in xml we wont know which row has caused the error.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace TestSolution
{
  public interface ICustomParser
  {
    bool Parse(string input);
  }

public class DecimalParserAttribute : Attribute, ICustomParser
{
    public bool Parse(string input)
    {
        if (input == null) return false;

        decimal decimalValue;

        return decimal.TryParse(input, out decimalValue);
    }
}

public class intParserAttribute : Attribute, ICustomParser
{
    public bool Parse(string input)
    {
        if (input == null) return false;

        int intValue;

        return int.TryParse(input, out intValue);
    }
}

public class Product
{
    [DecimalParser]
    public string Weight { get; set; }

    [intParser]
    public string NoOfItems { get; set; }

    [intParser]
    public string GRodes { get; set; }

    [intParser]
    public string WRodes { get; set; }
}

class Program
{
    static void Main(string[] args)
    {

        var sb = Validate(new Product() { NoOfItems = "1", GRodes = "4", Weight = "5", WRodes = "23" });

        Console.WriteLine(sb);
        sb = Validate(new Product() { NoOfItems = "1", GRodes = "4w", Weight = "5", WRodes = "23" });

        Console.WriteLine(sb);
        Console.ReadKey();
    }

    private static string Validate(Product product)
    {
        var sb = new StringBuilder();

        foreach (var property in product.GetType().GetProperties())
        {
            var value = Convert.ToString(property.GetValue(product, null));

            var sel = property.GetAttribute<ICustomParser>();

            if (sel == null) continue;

            var parserinstance = (ICustomParser)Activator.CreateInstance(sel.GetType());

            if (parserinstance.Parse(value)) continue;

            sb.AppendLine(string.Format("{0} Has invalid value", property.Name));
        }
        return sb.ToString();
    }
}

public static class Extensions
{
    public static T GetAttribute<T>(this PropertyInfo property)
    {
        return (T)property.GetCustomAttributes(false).Where(s => s is T).FirstOrDefault();
    }
}





dimanche 18 décembre 2016

Is it possible to obtain the type of a property of an unknown type?

public class TypeA {}

public class TypeB
{
    TypeA PropertyA { get ;set; }
}

There are two classes of types TypeA and TypeB in an assembly that we are unaware of at compile-time. The only thing known is the name of the property PropertyA.

I would like to obtain the type of this property at run-time, if it is possible.

T GetGenericObject<T>()
{
    T result = (T)Activator.CreateInstance(typeof(T));
    PropertyInfo pInfo = typeof(T).GetProperty("PropertyA");

}

Assuming this method is called with TypeB,

var obj = GetGenericObject<TypeB>();

I can access the PropertyInfo of PropertyA but its type seems to be undeterminable.





Obtain methods of a parent class using java reflection

Imagine that I need to obtain the methods of a parent class and that parent class is also extended to another. So when I use the ,

Method [] getMethods();

It gives all the methods existing in the parent class and as well methods of its parent class as well.

I only need to take the methods of the immediately parent class which are not overridden.

Can we use Method getMethod (String, Object ....); for this purpose? If not , for what we can use it.





PayPal-Java-SDK & Google App Engine - Subscription Reflection Error

I am trying to create a PayPal Subscription on Google App Engine using the PayPal-Java-SDK. I have a slight variation of the code in this link implemented, but I am getting the exception below when calling the Plan.update after creating the PATCH object.

java.lang.SecurityException: java.lang.IllegalAccessException: Reflection is not allowed on protected java.lang.String java.net.HttpURLConnection.method





Generate stub classes and method signatures for a huge code base using reflection

I am attempting to build a development environment from a huge application. I can access it by running Java directly, but do not have the source code.

In order to develop against it, I would like to stub out everything I can use, along with super classes, interfaces, fields, etc.

I have done a lot of this via reflection, but I am having trouble figuring out how to convert the data from enums and generics.

The rest has been ok, get the package, then the modifiers of the class, the class name, the super class, and any interfaces if they exist, results in

package x;

public class Test() Extends Temp implements Thing
{
}

etc, looping over fields, constructors, methods, inner classes. But I don't really understand enums, the are prefaced by $SWITCH_TABLE$ and I don't want to hard code a replacement, I'd rather understand how to operate on this data correctly.

I also have no clue how to generate code for generic types.

Any help would be greatly appreciated!

Thanks! Greg

Enum,





how to get the value of a javax.lang.model.element.Element?

I am implementing my own annotation processor and i would like to get the value of final static fields. Example:

public final static String ID = "id";

how is it possible to get this value "id"?





Data Attributes on EF POCO to Ignore Attributes When Exporting Object Values Violates SRP?

I am working with Entity Framework as my ORM for a project at work, and I need to be able to write only some of the values of each entity to an existing Excel template.

The data is required to be formatted as Excel Tables so that the end user can reference the information by using formulas like "=AVG(People_Table[Age])". (note, this is just a contrived example for a simplicity). There is also a requirement to export the values to PDF as well.

I've decide that reflection is the way to go to export the information in the least painful manner possible. The problem now, however, is I want to exclude certain properties from being written to the spreadsheet. And I also might want to write the properties in a certain order and specify a display format.

One way I could do this is with defining specific Data Attributes on the properties. I liked this answer on ignoring specific attributes: Exclude property from getType().GetProperties(). So a possible solution could be:

// class I want to export
public class PersonEntity {

    [SkipAttribute] // per solution in the referenced answer
    public int PersonId { get; set; }

    [SkipAttribute]
    public int ForeignKeyId { get; set; }

    [Display(Order = 3)]
    public int Age { get; set; }

    [Display(Name="First Name", Order = 1)]
    public string FirstName { get; set; }

    [Display(Name="Last Name", Order = 2)]
    public string LastName { get; set; }
}

The Problem I see with the above solution is that this entity class is now doing two things: One, proving a mapping between EF and the Database which is it's primary function, and two providing information on how to consume the class for exporting to Excel. I see this as getting messy and leading to confusion because it (possibly?) violates SRP.

An alternative solution that I see could be to create a separate set of classes that only contains the needed properties and to use this for exporting to Excel, and then using a tool like AutoMapper to map from EF Person to this class.

So, the export class would be:

public class PersonExportModel {

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public int Age { get; set; }
}

And I would just use reflection to dump the values out to the specified format using ClosedXML or a PDF rendering library like ITextSharp.

Concern with the above solution is that this is going to end up with a lot of extra code just to ignore a few unwanted properties (mostly PK's, FK's, and some complex relationship properties). I am also at the issue any updates to the EF class, like removing a property, will require me to also go through the other classes and remove the corresponding properties.

So I'm stuck between either bloating my EF class to tell how it should be exported or creating other ExportModels that are tightly coupled to the EF class and would be a pain to update if the underlying model changes. And the whole mapping between classes is a real pain, which can be alleviated with AutoMapper. This comes with, however, it's own set of problems with obfuscated mapping and performance penalties. I could live with these "problems" if it means I do not have to manually map between the two classes.

I've thought about farming the work out to a SSRS but I need to ability to write the data to specific existing workbooks which I understand is not possible. I'd also need the ability to create named tables which also I understand is not possible out of the box with SSRS. I'd also need to create two reports because the Excel output would look much different than the PDF format. So even the SSRS would cause a lot of extra work.

Any suggestions on which solution might be best, or perhaps an alternative approach? The requirement of this project is in flux so I'm looking for a solution that will be as painless as possible to updates.





How to get a KClass of Array?

I wrote the below code to get a KClass of Array<*>.

Array::class

However, this code has a compilation error.

Kotlin: Array class literal requires a type argument, please specify one in angle brackets

Do you know any solution for this error?





samedi 17 décembre 2016

Fastest way to list all the annotated methods in annotated classes

DISCLAIMER: "Fastest" here refers to execution time.

I'm trying to list all the methods annotated by M if they are within classes annotated by C.

I know I can get a list of classes using Reflections.getTypesAnnotatedWith and then iterate over the classes asking each method if it is annotated by M. But I wonder if this is the fastest way to do so!





Kotlin invoke getter/setter reflectively

Beginner in Kotlin here.

I try to create and populate objects by reflection in a program. I cannot find the equivalent functionality in pure kotlin so my solution resembles the code below which works fine, but requires the use of dirty references like java.lang.String::class.java and intelliJ, understandably, doesn't seem to like this. Is there a simpler way that I am missing to do this?

val jclass = myObject::class.java 
val setters = jclass.declaredMethods.filter { it.name.startsWith("set") }
for (s in setters) {
    val paramType = s.parameterTypes.first()
    val data = when(paramType) {
        java.lang.Integer::class.java -> foo
        java.lang.Double::class.java -> bar
        java.lang.String::class.java -> baz
    }
    s.invoke(myObject, data)
}





How to check if `System.Type` is a pointer?

Given a System.Type, how can I check that it is in fact a pointer? (For example, I reflect on a String and some of its ctors take pointers.)





Get non-static block variable of a class

I have this class: Rat.java

public class Rat extends Mob {

{
    spriteClass = RatSprite.class;

    HP = HT = 8;
    defenseSkill = 2;

    maxLvl = 5;
}

@Override
public int damageRoll() {
    return Random.NormalIntRange( 1, 4 );
}

@Override
public int attackSkill( Char target ) {
    return 8;
}

@Override
public int drRoll() {
    return Random.NormalIntRange(0, 1);
}
}

And need to access its field "spriteClass" knowing the class' canonical name.

How does one do this kind of thing?

What I have done so far:

public Class<? extends CharSprite> getSprite(String e){
    if(e.indexOf("Hero") != -1) return HeroSprite.class;

    Class<?> cl = null;

    try {
        cl = Class.forName(e);
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }
    /*
    Field f = null;
    try {
        Log.d("ssss", cl.toString());
        if(cl != null) f = cl.getField("spriteClass");
    } catch (NoSuchFieldException e1) {
        e1.printStackTrace();
    }
    try {
        if(f != null){
            Class c = (Class) f.get(this);
            return c;
        }
    } catch (IllegalAccessException e1) {
        e1.printStackTrace();
    }*/
    Constructor<?> ctor = null;
    try {
        ctor = cl.getConstructor();
    } catch (NoSuchMethodException e1) {
        e1.printStackTrace();
    }
    try {
        Object object = ctor.newInstance();
        object.



    } catch (InstantiationException e1) {
        e1.printStackTrace();
    } catch (IllegalAccessException e1) {
        e1.printStackTrace();
    } catch (InvocationTargetException e1) {
        e1.printStackTrace();
    }
    return null;
}

I guess you can access non-static block when the object is created.