vendredi 31 août 2018

Java Reflection traverse into nested object and list and update the fields

I have the following complex POJO class Invoice

public class Measure {

    private String id;
    private Float value;

    public String getId() { return id; }
    public void setId(String id) { this.id = id; }    

    public Float getValue() { return value; }
    public void setValue(Float value) { this.value = value; }

}

public class LineItem {

    private Integer lineNumber;      
    private Measure shipped;       
    private List<LineItem> lineItems;  


    public Integer getLineNumber() { return lineNumber; }
    public void setLineNumber(Integer lineNumber) { this.lineNumber = lineNumber; }

    public Measure getShipped() { return shipped; }
    public void setShipped(Measure shipped) { this.shipped = shipped; }

    public List<LineItem> getLineItems() { return lineItems; }
    public void setLineItems(List<LineItem> lineItems) { this.lineItems = lineItems; }

}

public class Invoice {


    private String originUid;
    private String vehicleUid;
    private List<LineItem> lineItems;

    public String getOriginUid() { return originUid; }
    public void setOriginUid(String originUid) { this.originUid = originUid; }

    public String getVehicleUid() { return vehicleUid; }
    public void setVehicleUid(String vehicleUid) { this.vehicleUid = vehicleUid; }

    public List<LineItem> getLineItems() { return lineItems; }
    public void setLineItems(List<LineItem> lineItems) { this.lineItems = lineItems; }


}

Now I want to traverse deep into every single field including nested objects in the Invoice object and update them using Reflection.

I can call updateIncomingObject() recursively. But I need to know how to get the nested objects out of the field as shown in the commented section.

public Object updateIncomingObject(Object incomingObject) {

    Field[] incoming =  incomingObject.getClass().getDeclaredFields(); 
    for (Field incomingField : incoming) {
        incomingField.setAccessible(true);
        if (incomingField.getType().isArray()) {
         // for (each occurrence in thisArray ???) {
         //     Object result = updateIncomingObject(occurrence);
         //     thisArray.set(index,result);
         // }
         // incomingField.set(incomingObject, thisArray);
        } 
        else if (!incomingField.getType().getName().startsWith("java.lang")) {
         // Object objInstance = incomingField.???; 
         // Object result = updateIncomingObject(objInstance);
         // incomingField.set(incomingObject, result);
        }
        else {
            if (incomingField.getType().equals(String.class) && incomingField.get(incomingObject) != null) {
                String trimmed = incomingField.get(incomingObject).toString().trim();
                incomingField.set(incomingObject, trimmed);
            }
        }
    }
    return incomingObject;
}

How do I turn field into object instance?





@SQLInsert dynamic database schema

I have a need to call a stored procedure on insert of an entity. To do this, I am using @SQLInsert, which is working well. The problem I'm facing is that I need to be able to change part of the string during integration tests, as we use a different database schema.

Entity (getters/setters removed for space savings):

@Entity
@Table(name = "SNIPPET")
@SQLInsert(sql = "{ call MY_SCHEMA.INSERT_SNIPPET (?, ?, ?, ?, ?, ?) }", callable = true)
public class Snippet extends BaseDomain {

@Lob
@Column(name = "SNIPPET_TEXT_V2", nullable = false)
private String snippetText;

@Column(name = "ORDER", nullable = false)
private int snippetOrder; //1 based.

@Column(name = "NOTES", nullable = true)
private String snippetNotes;

@Column(name = "STATUS", nullable = false)
@Enumerated(EnumType.STRING)
private Status status;

@ManyToOne
@JoinColumn(name = "QUERY_ID")
private Query query;

}

This is the line I want to be able to change at runtime/test startup: @SQLInsert(sql = "{ call MY_SCHEMA.INSERT_SNIPPET (?, ?, ?, ?, ?, ?) }", callable = true)

I need to make MY_SCHEMA variable/adjustable at runtime. Is there a way to do this via reflection or other means?

A couple of things to note -

  • Setting the default schema on my connection doesn't work. We use USER_SCHEMA to connect to the DB and keep objects stored in MY_SCHEMA. Changing the default schema to MY_SCHEMA and using { call INSERT_SNIPPET (?, ?, ?, ?, ?, ?) } would have adverse effects on other parts of our application.
  • Versions - oracle 11g, java 8, hibernate 5.2




Spring & Java 9 and above - Spring without reflection

From Java 9 reflection is deprecated.
So as I know Spring use reflection during context initialisation.

So how Spring works without reflection?





Using reflection to change HttpRequest _form filed

I am trying to change an HttpRequest's Forms parameters at run-time using reflection, i am aware that this is like shaking hands with the devil, and aren't at all recommended, but i have to.

I am following the way suggested in this answer, but the GetValue method always returns null.

  public static HttpContext InjectFakePostParamsInHttpContext(HttpContext context, NameValueCollection postParameters)
    {
        var field = context.Request.GetType().GetField("_form", BindingFlags.NonPublic | BindingFlags.Instance);            
        var requestForm = (NameValueCollection)field.GetValue(context.Request);
        if (requestForm != null)
        {
            PropertyInfo readable = requestForm.GetType().GetProperty("IsReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
            if (readable != null)
            {
                readable.SetValue(requestForm, false, null);
                foreach (string postParameter in postParameters)
                {
                    requestForm[postParameter] = postParameters[postParameter];
                }

                readable.SetValue(requestForm, true, null);
            }
        }
        return context;
    }

This seems to work perfectly when using "_queryString", but when using "_form" i am getting a null requestForm!

What i am missing here?

Any help would be appreciated.





jeudi 30 août 2018

scala check if at least one case class field value is nonEmpty using reflection

I have a requirement that for a given case class with around 30+ Option[T] fields needs to have at least 1 field nonEmpty in order to be valid. Instead of checking each field individually I opted for checking all fields via reflection in a generic way. The code I came up with (based on some other answers in SO as well) was:

import scala.reflect.runtime.universe._
import scala.reflect.runtime.{universe => ru}

  // gets all methods of a Case Class
  def getMethods[T: ru.TypeTag] = typeOf[T].members.collect {
    case m: MethodSymbol if m.isCaseAccessor => m
  }.toList


  /**
    *  Returns the value of all Case Class fields
    * @param obj case class object
    * @return a Sequence of all field values
    */
  def getAllCaseClassFieldValues[T: ru.TypeTag](obj: Object): Seq[Any] = {
    val mirror = ru.runtimeMirror(getClass.getClassLoader)
    getMethods[T].map(m => mirror.reflect(obj).reflectField(m).get)
  }

The case class:

case class SampleRequest(field1: Option[String], field2: Option[String], //.... up to 30 or more fields

The code that checks to see if at least 1 is nonEmpty:

 val fieldValues = getAllCaseClassFieldValues[SampleRequest](r)
 val noneCount = fieldValues.count(_ == None)
 val atLeastOneNonEmpty = noneCount < fieldValues.size

I was wondering if there would be a better way for validating this via reflection or other mechanism?





Java using Reflection to compare object for all field values

I have the following complex POJO class

public class Measure {

    private String id;
    private Float value;

    public String getId() { return id; }
    public void setId(String id) { this.id = id; }    

    public Float getValue() { return value; }
    public void setValue(Float value) { this.value = value; }

}

public class LineItem {

    private Integer lineNumber;      
    private MeasureF shipped;       
    private List<LineItem> lineItems;  


    public Integer getLineNumber() { return lineNumber; }
    public void setLineNumber(Integer lineNumber) { this.lineNumber = lineNumber; }

    public MeasureF getShipped() { return shipped; }
    public void setShipped(MeasureF shipped) { this.shipped = shipped; }

    public List<LineItem> getLineItems() { return lineItems; }
    public void setLineItems(List<LineItem> lineItems) { this.lineItems = lineItems; }

}

public class Base {

    private String tenantUid;
    private String sourceRecordId;
    private String uid;
    private String id;


    public String getTenantUid() { return tenantUid; }
    public void setTenantUid(String tenantUid) { this.tenantUid = tenantUid; }

    public String getSourceRecordId() { return sourceRecordId; }    
    public void setSourceRecordId(String sourceRecordId) { this.sourceRecordId = sourceRecordId; }

    public String getUid() { return uid; }   
    public void setUid(String uid) { this.uid = uid; }

    public String getId() { return id; }
    public void setId(String id) { this.id = id; }

}

public class Invoice extends Base {


    private String originUid;
    private String vehicleUid;
    private List<LineItem> lineItems;

    public String getOriginUid() { return originUid; }
    public void setOriginUid(String originUid) { this.originUid = originUid; }

    public String getVehicleUid() { return vehicleUid; }
    public void setVehicleUid(String vehicleUid) { this.vehicleUid = vehicleUid; }

    public List<LineItem> getLineItems() { return lineItems; }
    public void setLineItems(List<LineItem> lineItems) { this.lineItems = lineItems; }


}

I would like to use reflection to compare the values for all fields including child object and/or parent object and make update to one of the object. Something like this.

public Object updateIncomingObject(Object incomingObject, Object existingObject) {

    try {
        List<Field> incoming =  incomingObject.getClass().getDeclaredFields(); 
        for (Field incomingField : incoming) {

            incomingField.setAccessible(true);
            String incomingFieldName = incomingField.getName();
            String typeName = incomingField.getType().getName();

            if (incomingField.getType().IsSubType()) {
                // get field instance and then recursive call to updateIncomingObject();

            } else if (typeName.contains("java.util.List")) {
                // Loop list and recursive call to updateIncomingObject() 

            } else {
                Field existingField = getField(existingObject.getClass(), incomingFieldName);
                existingField.setAccessible(true);
                Object updatedTo = existingField.get(existingObject);
                if (updatedTo != null) {
                    incomingField.set(incomingObject, updatedTo);
                    String updateMsg = incomingFieldName + " Updated to : " + updatedTo;
                    LOGGER.debug(updateMsg);
                }
            }
        }
        return incomingObject;
    } catch (Exception e) {
        throw new Exception("updateIncomingObject() - " + e.getMessage());
    }
}

Can anyone tell me how to change the field object into a sub type object? Or filling the comment portion of the code? Or even better way to do this?

UPDATE: This is not a duplicate. I am looking for field to field update between to POJO objects with the same structure and the update is conditional. I didn't put the condition logic in updateIncomingObject() because I want to simplify things.

What I ma looking for is how to get to the fields of an field that is of non-primitive type, Such as Measure and LineItem as shown above.





ReflectiveDynamicAccess Does Not Accomodate Default Values

I have pre-existing code that calls the createInstanceFor method of akka.actor.ReflectiveDynamicAccess. This code essentially loops through a bunch of config values and creates instances based on the configuration (the class name is provided in the config). However, I had to update the definition of one of my classes like so.

//Old way
class MyClass(val1: String)

//New way
class MyClass(val1: String, val2: String = "defaultValue").

However, this causes the reflection object instantiation to fail with a java.lang.NoSuchMethodException. So it looks like it's not picking up that defaultValue.

Does anyone know a way around this? I know I could worst case I could update the config to include the default value, but this would result in a ton of duplication on the default value.

Thanks.





java declare anonymous class using proxy api

This morning I fell into a particular case that never happened to me before. I'm developing a Minecraft plugin using the minecraft server API which is usually called NMS with reference to the name of its packages (eg net.minecraft.server.v1_13_R1 for version 1.13). The main problem with the use of the minecraft server API is that it is difficult to write a cross version code: indeed the name of the packages changes with each new version. When the plugin only supports two versions it is usually easier to use the interfaces to write two different codes depending on the version. But when you have to support a dozen different versions (and this is my case), it's a bad idea (the plugin would be much too heavy, it would have to import every jar in the IDE, and I would have to redo the code with each new version). In these cases I usually use reflection but I do not think it's possible here:

            packet = packetConstructor.newInstance(
                    new MinecraftKey("q", "q") {
                        @Override
                        public String toString() {
                            return "FML|HS";
                        }
                    },
                    packetDataSerializerConstructor.newInstance(Unpooled.wrappedBuffer(data)));

As you probably guessed MinecraftKey is a class from NMS and I was told to use Java Dynamic Proxy API. I have never used it and would like to know if you would know a place that would explain to me how to do it simply? If you know of another better method that interests me too!

When I think about it, I think that this is really a lot of trouble for a tiny piece of code x)





How to invoke a MethodHandle with varargs

I'm trying to replace a reflective invocation with a MethodHandle, but varargs seem to be impossible to deal with.

My reflective invoker currently looks like this:

public class Invoker {

    private final Method delegate;

    public Invoker(Method delegate) {
        this.delegate = delegate;
    }

    public Object execute(Object target, Object[] args) {
        return delegate.invoke(target, args);
    }
}

My current attempt at rewriting it looks like this (the interface the Invoker exposes has to stay the same):

public class Invoker {

    private final Method delegate;
    private final MethodHandle handle;

    public Invoker(Method delegate) {
        this.delegate = delegate;
        this.handle = MethodHandles.lookup().unreflect(delegate);
    }

    public Object execute(Object target, Object[] args) throws InvocationTargetException, IllegalAccessException {
        Object[] allArgs = merge(target, args);
        return handle.invokeWithArguments(allArgs);
    }
}

And this works just fine in most cases. But varargs break everything. E.g. have a method like:

public String test(int i, String... args) {
    return ...;
}

And the above will fail. I tried various combinations of asSpreader(), MethodHandles.explicitCastArguments(), invoke instead of invokeWithArguments etc with 0 success.

The only way I can invoke a varargs method is to provide the arguments inline and not as an array (e.g. handle.invokeWithArguments(args1, args2...)), but I can not do that and maintain the generic nature of the Invoker that it currently has.

Is this really impossible to do the way I'm trying?





how to find the System.Type from a complex full path string?

for example, my Type is a complex type, it is a generic type.

public class TestType<T> : xxx

{ }

this is a generic class in Assmebly A. my Assembly B reference A, there is another type TestObject. so the actual type is : TestType .... if i save the fullname of this type, it is a very complex string, like this:

BluePrint.Core.CustomObjectConverter`1[[BluePrint.SGame.VInt2, BluePrint.SGame.Plugins, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], BluePrint.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null

so, if i want to find the System.Type of this string, how to do this? i use System.Type.GetType, it return null. the generic type and the parameter type are in different assemblies.





mercredi 29 août 2018

How to get number of method and it's name using reflection?

1). I have already try belowe code :

if let types = getTypesOfProperties(in: Book.self){
    for (name, type) in types {
        print("'\(name)' has type '\(type)'")
    }
 }

Book class :

class Book: NSObject {
    let title: String
    let author: String?
    let numberOfPages: Int
    let released: Date
    let isPocket: Bool

    init(title: String, author: String?, numberOfPages: Int, released: Date, isPocket: Bool) {
        self.title = title
        self.author = author
        self.numberOfPages = numberOfPages
        self.released = released
        self.isPocket = isPocket
    }
}

i used reflation frmawork but types evry time it's return nil.

2).I have also try second

let myClass = Car.self

        var methodCount: UInt32 = 0
        let methodList = class_copyMethodList(myClass, &methodCount)

        for i in 0..<Int(methodCount) {
            let selName = sel_getName(method_getName(methodList![i]))
            //  let methodName = String(CString: selName, encoding: NSUTF8StringEncoding)!
            print(selName)
        }

Car class :

class Car: NSObject { var brand:String var model:String var price :Double var year:Int init(brand:String,model:String,price:Double,year:Int){

    self.brand = brand
    self.model = model
    self.price = price
    self.year = year
    func f1() {}
    func f2() {}
    func f3() {}
   }
}

here method is 4 but count return only 1.

please help .





Creating instance of generic class using Assembly.GetType

I have a factory which creates instances of classes, given a fully qualified type name i.e. Instruments.ClassName

Namespace Instruments
    Public Class ClassName
        Implements IInstrument

This has always worked using this method

public Type LoadFromAssemblies(string className, IEnumerable<Assembly> assemblies)
{
    return assemblies.Select(Assembly a => a.GetType(className)).Single(t => t != null);
}

However, I've changed some classes to inherit from a base, instead of implement an interface, that that base has a generic parameter. The class is now generic

Namespace Instruments
    Public Class ClassName(Of T As ClassNameSettings)
        Inherits ClassNameBase(Of T)

The class name is Instruments.ClassName`1 with the `1 denoting 1 generic parameter. The method above no longer works as the type name doesn't match. If I know before calling LoadFromAssemblies that the class is generic, I could append `1 but I don't know at that point. I could also iterate assemblies multiple times, once for each number of possible generic parameters (up to one for now) but this function is called hundreds of times and it would seem wasteful.

So is there a good method for instantiating a generic class from a list of assemblies, given the non-generic type name?





newProxyInstance returns null

I am trying to use Java Reflection to call a method which takes a callback as an argument. I instantiate all of the objects with Java Reflection. Also, I am using a Java Dynamic Proxy Class as the callback argument.

The weird thing is the java.lang.reflect.Proxy.newProxyInstance() method returns null.

Here is the interface I want to instantiate as an anonymous object as a Java Dynamic Proxy Class:

public interface MyListener {
    void onEvent(String eventName);
}

And here is how I instantiate the interface via newProxyInstance():

Object callbackObject = null;

try {
    Class callbackClass = Class.forName("com.example.MyListener");

    Class[] interfaceArray = new Class[]{callbackClass};

    InvocationHandler invocationHandler = new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("onMyEvent")) {
                Log.d(TAG, "InvocationHandler.invoke onMyEvent");
            }
            return null;
        }
    };

    callbackObject = java.lang.reflect.Proxy.newProxyInstance(
            this.getClass().getClassLoader(),
            interfaceArray,
            invocationHandler);
}
catch (Throwable t) {
    Log.e(TAG, "newProxyInstance got exception [" + t + "] caused by [" + t.getCause() + "]");
}

Log.d(TAG, "callbackObject=[" + callbackObject + "]");

if (null == callbackObject) {
    Log.e(TAG, "callbackObject is null according to null check");
}
else {
    Log.d(TAG, "callbackObject is NOT null according to null check");
}

The log messages seem to conflict about whether callbackObject is null:

callbackObject=[null]
callbackObject is NOT null according to null check

According to Why does newInstance() return null? it's not possible for newProxyInstance() to return null because it gets the value from newInstance().

So how can the result of newProxyInstance() be null and not null?





Recursively modify all fields in an object annotated with a given annotation

Given an input object, I need to find all fields in it with a given annotation and modify it with some value.

This annotation could also be present in an object present inside the given input object.

public class A {
  private B b;

  @MyAnnotation
  private String s;

}

public class B {

    @MyAnnotation
    private String a;

    private String b;
}

Output, in this case, should be fields s and a and I need to modify the same with some String. I found fieldUtils from apache which gives annotation on a given class, and I think I can add a simple DFS search to find all fields with the given annotation. The problem comes while setting the value using reflection, I need to specify the object as part of field.set(). I'm not sure which object should be used while setting the value of a and how to get that in a generic manner (in case I need to retrieve instance of B from A in this example)





Are instances of Class?> immutable?

I was wondering whether Class<?> instances are immutable. The declared methods names do not suggest that the instance state is changed when they are invoked, but I found no explicit guarantee on the javadoc.

Scenario: I need to store unique class names in a Set. Ideally, I would like to populate the set with Class<?> instances to avoid unnecessary calls to Class.forName() when I need to access the classe via reflection. However, it preferable to use immutable objects as keys of sets. Hence I was wondering if I could use Class<?> instances right away.





Loading a class with reflection - ObjC

Is there another way to load a class with reflection in ObjC other than NSClassFromString?





List fields with a specific attribute

I'm trying to list all the fields with a certain Attribute, but still not quite understanding what kind of object GetValue() expects.

[AttributeUsage(AttributeTargets.Field, AllowMultiple = true)]
class SerializedAttribute : Attribute
{

}

class Program
{
    [Serialized] public Single AFloat = 100.0f;
    [Serialized] public Single AnotherFloat = 125.5f;
    [Serialized] public Single OnceAgain = 75.0f;

    static void Main(string[] args)
    {

        foreach(FieldInfo field in typeof(Program).GetFields())
        {
            foreach(Attribute attr in field.GetCustomAttributes())
            {
                if (attr is SerializedAttribute)
                {
                    Console.WriteLine("\t" + "Variable name: " + field.Name + "\t" + "Variable value:" + field.GetValue(/*"??????????????"*/));           
                }
            }
        }

        Console.ReadKey();

    }
}

I tried few google searches but apperantly I'm not a very good at problem solving.





Is it possible to change the default initial field value via reflection in java?

lets say we have a class with an field and it has a default initial value and that is not changed by the constructor, for example

public class Server {
  private int pingFrequency = 500;

  public Server() {
  }
}

Now I want't to change the default initial value to another value BEFORE the object is constructed. The reason is that this class is used by an library and hide away the object instance. So I could only control when the object is constructed but not where and how.

I've tried to get field via reflection, but I dont't see any way to change the default value

Field pingFrequency =  Class.forName("Server").getDeclaredField("pingFrequency")

I think I must change something in the classloader, but I don't know what and how.

Thank you





mardi 28 août 2018

Java di module with help of generics and reflection

I want to build my own simple di module, for that purpose I created:

public interface Factory<T> {
T getInstance();
}

and

public class DiImpl implments Di{

private Map<Class, Factory> map = new HashMap<>();

@Override
public <T> Factory<T> getFactory(Class<T> type) {
    return (Factory<T>) map.get(type);
}

@Override
public <T> void bind(Class<T> base, Class<? extends T> impl) {
    map.put(base, new Factory<Class<?>>() {
        @Override
        public Class getInstance() {
            return impl;
        }
    });
}
}

But this code not pass simple test:

interface SimpleService {
....
}

FirstVaraintService implements SimpleService {
...
}

@Test
void test(){
Di di= new DiImpl();
di.bind(SimpleService.class, FirstVaraintService.class);       
Factory<SimpleService> factory = di.getFactory(SimpleService.class);
assertSame(FirstVaraintService.class, factory.getInstance().getClass());
}

compiler returns:

java.lang.ClassCastException: java.lang.Class cannot be cast to ... SimpleService

I know that, such di structure can be implemented with help of reflection API, but I don't know how to properly use it in this example. Please help me to change my code to pass the test.





Endless loop in reflections

Need help with this macro. Created it and it runs as I want it to, but when it gets to the final page on reflections it does not stop when the RIP Number is " ". Not sure what the issue is. Maybe the placement of that line to tell the macro when to stop? Let me know your thoughts. Thanks in advance.

    Sub RMBR2()
    Dim text As String * 4, continue As String * 4, pl As String
    Dim PGST As Single, PGEND As Single
    Dim USED As String * 3, password As String
    Dim VENDOR As String * 7, FN As String * 4
    Dim QTY As String * 8, PKGLST As String * 10, SHIPDT As String * 6, SID As String * 10, LINE As String * 3
    Dim part As String * 19, ST As String, Part3 As String * 19
    Dim stdate As String * 10, enddate As String * 10
    Dim SZ As Integer, col As Integer, length As Integer, n As Integer, i As Integer, PASTDUE As Integer, OPENSCH As Integer, fai As Integer
    Dim past As Single, CHASSIS2 As String, CHASSIS As String, partNumber As String, partNumber2 As String, counter As String, check As String
    Dim screenString As String
    Dim whichCell As String, cellLabel As String
    Dim excel As Object
    Dim a As String, b As String, c As String, D As String, E As String, F As String, G As String
    Dim ACELL As String, BCELL As String, CCELL As String, DCELL As String, ECELL As String, FCELL As String, GCELL As String
    Dim PART1 As String, PART2 As String

Part3 = InputBox$("PART?", "PART")
VENDOR = InputBox$("SUPPLIER CODE?", "SUPPLIER")

With Application
    .TransmitTerminalKey rcIBMClearKey
    .WaitForEvent rcKbdEnabled, "30", "0", 1, 1
    .WaitForEvent rcEnterPos, "30", "0", 1, 1
    .TransmitANSI "RMBR"
    .TransmitTerminalKey rcIBMEnterKey
    .WaitForEvent rcKbdEnabled, "30", "0", 1, 1
    continue = .GetDisplayText(1, 2, 4)
        If continue <> "RMBR" Then
            password = ""  ' Password has not been recorded for security
            password = .PasswordBox("                                                           Password . . .", "Password")
            .TransmitANSI password
            .TransmitTerminalKey rcIBMEnterKey
            .WaitForEvent rcKbdEnabled, "30", "0", 1, 1
        End If
    .MoveCursor 4, 11
    .TransmitANSI Part3
    .MoveCursor 6, 12
    .TransmitANSI VENDOR
    .TransmitTerminalKey rcIBMEnterKey
    .WaitForEvent rcKbdEnabled, "220", "0", 1, 1

     Set excel = CreateObject("Excel.Application")
     excel.Workbooks.Add
      excel.Visible = True

  excel.Columns("A:A").ColumnWidth = 30
  excel.Columns("B:B").ColumnWidth = 30
  excel.Columns("C:C").ColumnWidth = 30
  excel.Columns("A:A").ColumnWidth = 30
  excel.Columns("B:B").ColumnWidth = 30
  excel.Columns("C:C").ColumnWidth = 30
  excel.Columns("G:G").ColumnWidth = 30

   excel.Range("A1").select
   excel.activecell.formulaR1C1 = "RIP NUMBER"

   excel.Range("B1").select
   excel.activecell.formulaR1C1 = "QTY"

   excel.Range("C1").select
   excel.activecell.formulaR1C1 = "PO/ORDER"

    excel.Range("D1").select
    excel.activecell.formulaR1C1 = "LINE"

    excel.Range("E1").select
    excel.activecell.formulaR1C1 = "SCH"

    excel.Range("F1").select
    excel.activecell.formulaR1C1 = "PACKING LIST"

     excel.Range("G1").select
     excel.activecell.formulaR1C1 = "RIP DATE"



RipNumber = .GetDisplayText(9, 6, 10)
QTY = .GetDisplayText(9, 33, 6)
PO = .GetDisplayText(9, 42, 10)
LINE = .GetDisplayText(9, 53, 3)
sch = .GetDisplayText(9, 57, 3)
PLIST = .GetDisplayText(9, 61, 10)
R_DATE = .GetDisplayText(9, 73, 8)



i = 2

Do Until RipNumber = "      "

For n = 9 To 22

c = Trim$(Str$(i))

ACELL = "A" + c
BCELL = "B" + c
CCELL = "C" + c
DCELL = "D" + c
ECELL = "E" + c
FCELL = "F" + c
GCELL = "G" + c



        RipNumber = .GetDisplayText(n, 6, 10)
        QTY = .GetDisplayText(n, 33, 6)
        PO = .GetDisplayText(n, 42, 10)
        LINE = .GetDisplayText(n, 53, 3)
        sch = .GetDisplayText(n, 57, 3)
        PLIST = .GetDisplayText(n, 61, 10)
        R_DATE = .GetDisplayText(n, 73, 8)



                       excel.Range(ACELL).select
                       excel.activecell.formulaR1C1 = "'" + RipNumber

                       excel.Range(BCELL).select
                       excel.activecell.formulaR1C1 = "'" + QTY

                       excel.Range(CCELL).select
                       excel.activecell.formulaR1C1 = "'" + PO

                       excel.Range(DCELL).select
                       excel.activecell.formulaR1C1 = "'" + LINE

                       excel.Range(ECELL).select
                       excel.activecell.formulaR1C1 = "'" + sch

                       excel.Range(FCELL).select
                       excel.activecell.formulaR1C1 = "'" + PLIST

                       excel.Range(GCELL).select
                       excel.activecell.formulaR1C1 = "'" + R_DATE


i = i + 1

Next n

c = Trim$(Str$(i))

ACELL = "A" + c
BCELL = "B" + c
CCELL = "C" + c
DCELL = "D" + c
ECELL = "E" + c
FCELL = "F" + c
GCELL = "G" + c



        RipNumber = .GetDisplayText(22, 6, 10)
        QTY = .GetDisplayText(22, 33, 6)
        PO = .GetDisplayText(22, 42, 10)
        LINE = .GetDisplayText(22, 53, 3)
        sch = .GetDisplayText(22, 57, 3)
        PLIST = .GetDisplayText(22, 61, 10)
        R_DATE = .GetDisplayText(22, 73, 8)


                       excel.Range(ACELL).select
                       excel.activecell.formulaR1C1 = "'" + RipNumber

                       excel.Range(BCELL).select
                       excel.activecell.formulaR1C1 = "'" + QTY

                       excel.Range(CCELL).select
                       excel.activecell.formulaR1C1 = "'" + PO

                       excel.Range(DCELL).select
                       excel.activecell.formulaR1C1 = "'" + LINE

                       excel.Range(ECELL).select
                       excel.activecell.formulaR1C1 = "'" + sch

                       excel.Range(FCELL).select
                       excel.activecell.formulaR1C1 = "'" + PLIST

                       excel.Range(GCELL).select
                       excel.activecell.formulaR1C1 = "'" + R_DATE


i = i + 1


        .TransmitTerminalKey rcIBMPf8Key
        .WaitForEvent rcKbdEnabled, "30", "0", 1, 1


        Loop

End With




End Sub





BeanUtils NoSuchMethodError

I want to set custom data into the fields of my class in this example its 'obj' i get this error:

java.lang.NoSuchMethodError: org.slf4j.spi.LocationAwareLogger.log(Lorg/slf4j/Marker;Ljava/lang/String;ILjava/lang/String;[Ljava/lang/Object;Ljava/lang/Throwable;)V
    at org.apache.commons.logging.impl.SLF4JLocationAwareLog.debug(SLF4JLocationAwareLog.java:133)
    at org.apache.commons.beanutils.ConvertUtilsBean.convert(ConvertUtilsBean.java:418)
    at org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1002)
    at org.apache.commons.beanutils.BeanUtils.setProperty(BeanUtils.java:313)

'the field exists the name of the field is correct (private String 'mymiddleName') I dont know what the problem is

for(Map.Entry<String, Object> entry : customValues.entrySet()) {
        for(Field field : myFields){
            if(field.getName().equals(entry.getKey())) {
                System.out.println("key: " + entry.getKey() + " Value:" + entry.getValue());
                BeanUtils.setProperty(obj, entry.getKey(), entry.getValue());
                break;
            }
        }
    }

Excuse my bad english skills i work on it.





Getting private variable name of a property

Might be a duplicate but I couldn't find a way to properly formulate what I was looking for.

Is there a way to get the name of the private variable returned by a property using the property itself or an extension?

private string VariableNameToGet;
public string TheProperty {get => VariableNameToGet; set {VariableNameToGet = value;}}

In other words, would there be a way to end up with something like this TheProperty.GetPrivateVariableName() that would return "VariableNameToGet" in a generic way





How to access a Scala object instance given it's full qualified name?

So I have defined a Scala object using the following code:

trait SomeTrait {
  def someMethod(): Unit
}

package somepackage1 {
  object Impl1 extends SomeTrait {
    def someMethod(): Unit = { }
  }
  object Impl2 extends SomeTrait {
    def someMethod(): Unit = { }
  }
}

I want to access the object given its fully qualified name i.e. somepackage1.Impl2. A method something like following:

package object somewhereElse {
  def getImpl(qualifiedName: String): SomeTrait = {
    ???
  }
}

What should be the code as part of getImpl method?





Can I get private constructor in .NET Core?

In .NET Framework such method exists:

public ConstructorInfo GetConstructor(
    BindingFlags bindingAttr,
    Binder binder,
    CallingConventions callConvention,
    Type[] types,
    ParameterModifier[] modifiers
)

But in .NET Core (1.1) I found only extension, which doesn't give me private constructor:

public static ConstructorInfo GetConstructor(this Type type, Type[] types)

So I'm wondering if I can somehow access and get private constructor in .NET Core.





lundi 27 août 2018

How do you access name of a ProtoField after declaration?

How can I access the name property of a ProtoField after I declare it?

For example, something along the lines of:

myproto = Proto("myproto", "My Proto")

myproto.fields.foo = ProtoField.int8("myproto.foo", "Foo", base.DEC)

print(myproto.fields.foo.name)

Where I get the output:

Foo





C# - Is it possible to retrieve the variable name (not value) of a property using reflection?

I am trying to retrieve the variable name of a property, instead of the value. I am currently using reflection, but if anyone has other suggestions it would be much appreciated.

I have three classes involved

A:

Class A {

public B bObject;

int Number{ return bObject.number;} //returns 3
}

B:

Class B {   public int number = 3; }

C:

Class C {

public void myMethod(){
A aObject = new A();
var aNumber = aObject.GetType.GetProperty("Number").GetValue(aObject, null);
//this is the value. aNumber = 3.
var objName = nameof(aNumber); //returns aNumber
}

I want objName to return the string "bObject.number," the variable that was called inside the property. Is this possible with my current setup, and if not, does anyone have recommendations?

I'd rather not have another method in B to return "nameof(bObject) + nameof(bObject.number)" then call both that method and the prop due to redundancy. Thanks for your time.





How to determine a method signature dynamically when throwing custom exceptions?

I am following a standard that requires me to log the class#method that originates an exception for easy debugging from our UI. Without pulling the logs I know what method spawned the exception and can (usually) easily find the root cause.

However, I would like a dynamic way of determining the method signature because I am currently hard-coding it everywhere I am throwing an exception. Is there a better way.

 @Service
 public class UserService {

     @Autowired
     private UserRepository userRepository;

     public User findUser(Long id){

          if(id == null || id < 1){
               throw new BadRequestException("UserService#findUser", String.format(
                                             "Invalid Id: %d", id));
          }

          User user = userRepository.findOne(id);

          if(user == null){
               throw new DataNotFoundException("UserService#findUser", String.format(
                                               "Can't Find User for Id: %d", id));
          }
          return user;
     }
 }

--

The goal is that I can create any custom exception and within that constructor I can infer the method signature by where the exception was created from.

 public BadRequestException(String issue){
      super(String.format("%s | Bad Request | %s", <<signature>>, issue);
 }

--

 UserService class --> findUser method --> BadRequest("UserService#findUser")
 UserService class --> createUser method --> BadRequest("UserService#createUser")





How do I get the namespaces of an assembly and not its dependencies?

How do I get the namespaces of an assembly and not of its dependencies?

For example, if I get the namespaces in EntityFramework.dll using

assembly.GetTypes().Select(t => t.Namespace).Where(n => n != null).Distinct() 

and then only list the namespaces with the minimum periods, I get the following two namespaces

System.Data.Entity
System.Linq.Expressions

However, System.Linq.Expressions is the namespace of an assembly that EntityFramework.dll is dependent on and not a namespace of EntityFramework.dll, which clearly is System.Data.Entity.

How do I distinguish between the 2?

I am loading the assembly via Assembly.LoadFrom(path) and I understand that it automatically loads the assembly's dependencies. For the solution, do I have to load the assembly in a way that the dependencies are not loaded? If yes, how do I do that?

Also, I do not have any control over the Assembly creation, like adding an empty class etc.





How do I get the primary namespace in an assembly?

For example, if I get the namespaces in EntityFramework.dll using

assembly.GetTypes().Select(t => t.Namespace).Where(n => n != null).Distinct() 

and then only list the namespaces with the minimum periods, I get the following two namespaces

System.Data.Entity
System.Linq.Expressions

However, System.Linq.Expressions is the namespace of an assembly that EntityFramework.dll is dependent on and not the primary namespace of EntityFramework.dll, which clearly is System.Data.Entity.

How do I distinguish between the 2?





dimanche 26 août 2018

c# How to detect if a particular method has overloaded versions?

I just need to know if there's a smart way to detect if a particular Type method has overloads or not.

At the moment I'm iterating through methods and searching for DeclaringType+Name ambiguity...but I think it's a bit lame :)

thx





Get Base Class Event Delegates by Reflection

I need to get all Delegates which are subscribed to events in an object. The object is instantiated from a class which inherits a base class. I can get all Delegates for events defined in the class, but not for the ones of the base class.

So, in code, here's what I have in principle (I don't copy declarations etc. to keep it short):

public class DerivedClass : Base Class
{
    public event EventHandler<UserDefinedEventArgs> DerivedClassEvent;
    [...]        
}

The Base class is defined like this (hosting the functions for getting the Delegates I need):

public abstract class BaseClass 
{
    public event EventHandler<UserDefinedEventArgs> BaseClassEvent;

    public Dictionary<EventInfo, List<Delegate>> getAllEventsSubscribersList()
    {

        EventInfo[] eventInfoS = this.GetType().GetEvents(); //Get all events / event infos defined in the class

        foreach (EventInfo eventInfo in eventInfoS)
        {
            resDelegates = this.getEventSubscriberList(eventInfo); //Get the delegates for each event
        }
    }

    public List<Delegate> getEventSubscriberList(EventInfo eventInfo)
    {
        FieldInfo eventFieldInfo = this.GetType().GetField(eventInfo.Name, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);

        Delegate eventFieldValue = (System.Delegate)eventFieldInfo.GetValue(this);

        Delegate[] subscribedDelegates = eventFieldValue.GetInvocationList();
    }
}

Then, I try to get all events and their Delegates like this:

DerivedClass myObject = new DerivedClass();
Dictionary<EventInfo, List<Delegate>> EventAndDelegatesList = myObject.getAllEventsSubscribersList();

When calling 'getAllEventsSubscribersList', all events of the derived as well as of the base class are found correctly. But in the function for retreiving the actual Delegates, the FieldInfo for the "BaseClassEvent" is always 'null'.

How can I read the delegates for the base class event?





samedi 25 août 2018

Dynmically cast a object using reflection

Can someone explain why this code doesnt work and throw error:incompatible type :Object cannot be converted to aaa

class aaa {}

class bbb extends aaa {

}

class psp {

 public static void main(String args[]) {

  bbb b = new bbb();

  Object object = b;
  Class clazz = aaa.class;
  //aaa a=clazz.cast(b); doesnot work
  //aaa a=Class.forName("aaa").cast(object); doesnt work
  //aaa a=Class.forName("aaa").cast(b);doesnt work
  aaa a = (aaa) object;
  a = (aaa) aa;
  a = aaa.class.cast(b);

 }
}

PS:I'm talking about commented code





Casting object dynmically using cast() in java

Can someone explain why this code doesnt work and throw error:incompatible type :Object cannot be converted to aaa

    class aaa{
    }

    class bbb extends aaa{

    }

    class psp{

    public static void main(String a[]){

    bbb aa=new bbb();

    Object o=aa;
    Class z=aaa.class;
    //aaa a1=z.cast(aa); doesnot work
//aaa a1=Class.forName("aaa").cast(o); doesnt work
//aaa a1=Class.forName("aaa").cast(aa);doesnt work
aaa a1=(aaa)o;
a1=(aaa)aa;
 a1=aaa.class.cast(aa);

    }
    }

Can someone tell what i'm missing ?





Dynamically add item to ListBox whose DataSource is bound to a collection

I'm trying to create custom reusable WPF UserControl that has a listbox and a button to add a new row, just like how a DataGrid can allow users to add a new row.

This control will be bound to many different types of collections in various view models (i.e. List, ObservableCollection, etc.).

I have the UserControl with a dependency property called DataSource of type IEnumerable (it has to be IEnumerable to allow ObservableCollections, Lists, etc). I want to create a new instance of whatever object is in the underlying collection, and add it to the original collection that is bound to ItemsSource.

I have created a method that will make a new instance of an object that the collection is comprised of:

private object GetNewItem()
{
    if (ItemsSource == null)
        throw new ArgumentException("ItemsSource not set");

    Type itemType = null;
    foreach (Type i in ItemsSource.GetType().GetInterfaces())
    {
        if (i.IsGenericType && i.GetGenericTypeDefinition().Equals(typeof(IEnumerable<>)))
            itemType = i.GetGenericArguments()[0];
    }

    if (itemType == null)
        throw new ArgumentException("Unable to get ItemsSource's Type T");

    return Activator.CreateInstance(itemType);
}

Now I just need to get that new object added to the original collection. Unfortunately, IEnumerable does not allow adding items, as it's not intended to be mutable.

I can detect which type of collection was originally used, i.e.:

if (itemsType.IsGenericType && itemsType.GetGenericTypeDefinition() == typeof(ObservableCollection<>))

So, I can get the type of collection, and that collection's generic type (i.e. collection was an 'ObservableCollection<>', and the generic type was 'Person'), but I cannot figure out how to cast it back... and even if I could, I couldn't add the result of GetNewItem to it as:

((ObservableCollection<Person>) ItemsSource).Add(object) 

... doesn't work without casting object to 'Person'.

DataGrids are able to add a new instance of it's ItemsSource's underlying type, even though it's ItemsSource is IEnumerable, so I know it isn't impossible. I just can't see how to make it work. I would appreciate any advice.





Would java allow me to assign this object to this generic field?

In my POJO editor I need to check whether the class name supplied by the user can be instantiated and assigned to a generic property. Guava reflection provides almost everything I need: I resolve the types and then call proptype.isSupertypeOf(implClazz), but this does not work as expected.

For example, I have the type token: java.util.Collection<java.sql.Timestamp> and I want my check to accept ArrayList and classes that extend raw ArrayList or ArrayList<Timestamp> or themselves are parameterized, but not accept a class that extends ArrayList<Integer>.

However, isSupertypeOf() only works well with fully resolved types, while incomplete and raw classes not treated as subtypes.

    package com.common.jsp.beans;

    import java.lang.reflect.Field;
    import java.lang.reflect.Type;
    import java.sql.Timestamp;
    import java.util.ArrayList;
    import java.util.Collection;

    import com.google.common.reflect.TypeToken;

    public class TestTypeInf
    {
        public static class MyCollection1 extends ArrayList<Integer> {
        }
        public static class MyCollection2 extends ArrayList<Timestamp> {
        }
        public static class MyCollection3<T> extends ArrayList<T> {
        }
        public static class MyCollection4 extends ArrayList {
        }

        public static Collection<Timestamp> fld;

        public static void main( String[] args )
                        throws Exception
        {
            // bad: fld = new MyCollection1();
            fld = new MyCollection2();
            fld = new MyCollection3(); // just a warning
            fld = new MyCollection4(); // just a warning

            Field getter = TestTypeInf.class.getField( "fld" );
            Type memberType = getter.getGenericType();

            TypeToken<?> resolved = TypeToken.of( TestTypeInf.class ).resolveType( memberType );
            System.out.println( "type of fld: " + resolved );

            checkAssignable(resolved, MyCollection1.class);
            checkAssignable(resolved, MyCollection2.class);
            checkAssignable(resolved, MyCollection3.class); // This should be totally valid
            checkAssignable(resolved, MyCollection4.class); // why no?
        }

        private static void checkAssignable(TypeToken<?> resolved, Class<?> implClass) {
            System.out.println( "fld = new " + implClass.getSimpleName() + "()" );
            System.out.println( resolved.isSupertypeOf( implClass ) ? "yes" : "no" );
        }
    }

_

type of fld: java.util.Collection<java.sql.Timestamp>
fld = new MyCollection1()
no
fld = new MyCollection2()
yes
fld = new MyCollection3()
no
fld = new MyCollection4()
no
fld = new ArrayList()
no





How to set values by accessing variable through method invocation

How can I set values to tmpBean of MainAction01 with bean values passed by class Operation in below example:

public class Bean01 {
  private int Id01 = 0;
  //getters and setters
}

public interface MainInterface<T> {
  public T getBean();
}

public class MainActionBase<T> {
  public final void startMainJob(T objBean) throws RuntimeException {
    try {
      Object bean = new Object();
      Method getBean = this.getClass().getDeclaredMethod("getBean");
      getBean.setAccessible(true);
      bean = getBean.invoke(this);
      bean = objBean;
    } catch (Exception ex) {
      Logger.getLogger(MainActionBase.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}

public class MainAction01 extends MainActionBase implements MainInterface<Bean01> {
  private Bean01 tmpBean = new Bean01();

  @Override
  public Bean01 getBean(){
    return tmpBean;
  }

  public void getBeanDetails(){
    System.out.println("Id01: " + tmpBean.getId01());
  }
}

public class Operation {
  public static void main(String[] args) {
    Bean01 tmpBean = new Bean01();
    tmpBean.setId01(100);
    MainAction01 tmpMain = new MainAction01();
    tmpMain.startMainJob(tmpBean);
    tmpMain.getBeanDetails();
  }
}

I cannot access the field tmpBean in MainAction01 since I am not aware what of field name in other classes extending MainActionBase. I can only access bean through getBean() method forced by interface.

I know my method of setting bean = objBean does not make sense and rightly so the values are not set to tmpBean.





vendredi 24 août 2018

C# Reflection - PropertyInfo.SetValue [Object does not match target type]

This is a command system that runs using Command Attributes. An example of how this works is listed below.

If you were to type /message in the chat, this will run the method in the entry assembly that contains a CommandAttribute with the Text value of "message". All Classes that use the CommandAttribute inherit from the CommandContext Class. Using reflection, I am trying to set the value of the CommandContext properties so that they can be used in the Derived Class which would contain the Command Method that was invoked.

When setting the value of a property located in the CommandContext Class (Message in this case) I am receiving the following error.

Object does not match target type

I have tried the solutions from other questions but I am still receiving the error. I have posted the Derived class, Base Class, and the Method below. Please let me know if there is any other information needed to help me out. Thank you all for your help.

Error is occurring here:

messageProp.SetValue(baseType, Convert.ChangeType(rawMessage, messageProp.PropertyType), null);

BASE CLASS

public class CommandContext
{
    public string Message { get; internal set; }

    public CommandContext() { }
}

DERIVED CLASS

public class Maintenance : CommandContext
{
    [Command("message")]
    public void SendMessage()
    {
        Console.WriteLine(Message);
    }
}

METHOD

string rawMessage = messageData.SelectToken("msg")?.ToString();   

if (rawMessage[0] == _commandPrefix)
{
    var method = Assembly.GetEntryAssembly()
        .GetTypes()
        .SelectMany(t => t.GetMethods())
        .FirstOrDefault(m => 
            m.GetCustomAttribute<CommandAttribute>()?.Text == rawMessage.Substring(1).ToLower());


    if (method != null)
    {
        method.Invoke(Activator.CreateInstance(method.DeclaringType), null);

        var baseType = method.DeclaringType.BaseType;
        var messageProp = baseType.GetProperty("Message");

        messageProp.SetValue(baseType, Convert.ChangeType(rawMessage, messageProp.PropertyType), null);
    }
    else
        new Channel(messageData.SelectToken("rid")?.ToString()).SendMessage("Command does not exist");
}





C# reflection object does not match the target type

I have read the other questions in regards to this error with reflection however none of the answers are fixing my issue. I have tried tons of different variations and each one is throwing the same error.

string rawMessage = messageData.SelectToken("msg")?.ToString();

                if (rawMessage[0] == _commandPrefix)
                {
                    var method = Assembly.GetEntryAssembly()
                        .GetTypes()
                        .SelectMany(t => t.GetMethods())
                        .FirstOrDefault(m => m.GetCustomAttribute<CommandAttribute>()?.Text == rawMessage.Substring(1).ToLower());


                    if (method != null)
                    {
                        method.Invoke(Activator.CreateInstance(method.DeclaringType), new object[] { rawMessage });

                        var baseType = method.DeclaringType.BaseType;
                        var messageProp = baseType.GetProperty("Message");

                        messageProp.SetValue(baseType, Convert.ChangeType(rawMessage, messageProp.PropertyType), null);
                    }
                    else
                        new Channel(messageData.SelectToken("rid")?.ToString()).SendMessage("Command does not exist");
                }





ArrayList object inspection

I have an ArrayList which elements are ArrayList, which elements are either ArrayList or a custom object. How can I determine what object type the inner object is? I believe it can be done with streams and I am using Java8, but a practical would be greatly appreciated.





How to find out why a reflection call freezes the app

I detected an issue that on the nexus 5x with android 8.1 and security patch from august calling a method by reflection freezes the app, this same call works on 10 other devices with android 8.0, android 7.1.1 etc. Is it possible to find out what is causing the problem when making a call by reflection, I am not even getting an exception or some helpfull log, nothing, it justs freezes.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
            try {
                final TelephonyManager telMan = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                final Class<?> classTemp = Class.forName(telMan.getClass().getName());
                final Method methodTemp = classTemp.getDeclaredMethod("getITelephony");
                methodTemp.setAccessible(true);
                ITelephony telephonyService = (ITelephony) methodTemp.invoke(telMan);                
                telephonyService.endCall();
                return true;
            } catch (Exception ex) {
               return false;
            }
        } else {

The freeze happens at telephonyService.endCall(); and no exception is thrown.





jeudi 23 août 2018

Implementing an interface and forwarding method calls at runtime using Reflection.Emit

I need to implement an interface at runtime.

The implementation of all methods should just call some common static method (like 'Executor.Execute()') while passing the MethodInfo of the interface method being implemented, and forwarding any arguments passed to the newly emitted implementation.

The code works so far, and prints "Hello" when a method is called on the generated implementation.

Now, instead of WriteLine("Hello"), I need to insert code to call 'Executor.Execute()' with the MethodInfo of the interface method, etc..

How do I pass the 'method' variable from the for loop and any arguments of the implemented method to Executor.Execute?

public class Executor
{
    public static object Execute(MethodInfo method, object[] args)
    {
        Console.WriteLine($"Executing {method.Name}");
        return null;
    }
}

public class Builder
{
    public static T Implement<T>() where T : class
    {
        var interfaceType = typeof(T);

        var assemblyName = new AssemblyName(Guid.NewGuid().ToString());
        var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
        var moduleBuilder = assemblyBuilder.DefineDynamicModule("Implementation");

        var typeBuilder = moduleBuilder.DefineType("Implementation",
                                                   TypeAttributes.Public |
                                                   TypeAttributes.Class |
                                                   TypeAttributes.AutoClass |
                                                   TypeAttributes.UnicodeClass |
                                                   TypeAttributes.AutoLayout,
                                                   null);

        typeBuilder.AddInterfaceImplementation(interfaceType);

        // Implement all interface methods as calls to Executor.Execute()
        // passing the MethodInfo of the interface method being implemented,
        // and the arguments passed to the implemented method.
        foreach(var method in interfaceType.GetMethods())
        {
            var methodBuilder = typeBuilder.DefineMethod(
                method.Name,
                MethodAttributes.Public | MethodAttributes.Virtual,
                method.ReturnType,
                method.GetParameters().Select(p => p.GetType()).ToArray());

            var ilGen = methodBuilder.GetILGenerator();
            ilGen.EmitWriteLine("Hello");
            ilGen.Emit(OpCodes.Ret);

            // Generate a call like this:
            // -first arg is the 'method' from this for loop
            // -second is args passed to the generated method
            // Executor.Execute(method, args...);

            typeBuilder.DefineMethodOverride(methodBuilder, interfaceType.GetMethod(method.Name));
        }

        return Activator.CreateInstance(typeBuilder.CreateType()) as T;
    }
}

public interface Test {
    void Hello();
}

class Program
{
    static void Main(string[] args) {
        var impl = Builder.Implement<Test>();
        impl.Hello(); // should print "Executing Hello"
    }
}





Android P (API 28) - What does the StrictMode policy violation "SmartSelectionEventTracker$SelectionEvent;->selectionAction" mean?

I am using the StrictMode in order to find non-SDK usages:

if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
            .detectNonSdkApiUsage()
            .penaltyLog()
            .build());
}

Now I am getting a policy violation:

D/StrictMode: StrictMode policy violation: android.os.strictmode.NonSdkApiUsedViolation: Landroid/view/textclassifier/logging/    SmartSelectionEventTracker$SelectionEvent;->selectionAction(IIILandroid/view/textclassifier/TextClassification;)Landroid/view/textclassifier/logging/    SmartSelectionEventTracker$SelectionEvent;
        at android.os.StrictMode.lambda$static$1(StrictMode.java:428)
        at android.os.-$$Lambda$StrictMode$lu9ekkHJ2HMz0jd3F8K8MnhenxQ.accept(Unknown Source:2)
        at java.lang.Class.getDeclaredMethodInternal(Native Method)
        at java.lang.Class.getPublicMethodRecursive(Class.java:2075)
        at java.lang.Class.getMethod(Class.java:2063)
        at java.lang.Class.getMethod(Class.java:1690)
        at bzi.a(SourceFile:11)
        at bzq.a(SourceFile:12)
        at org.chromium.content.browser.selection.SmartSelectionClient.<init>(SourceFile:5)
        at bzZ.a(Unknown Source:7)
        at org.chromium.android_webview.AwContents.e(SourceFile:193)
        at org.chromium.android_webview.AwContents.d(SourceFile:153)
        at org.chromium.android_webview.AwContents.<init>(SourceFile:81)
        at uY.run(SourceFile:15)
        at ahv.a(SourceFile:13)
        at ahw.run(SourceFile:2)
        at org.chromium.base.ThreadUtils.b(SourceFile:31)
        at ahv.a(SourceFile:7)
        at com.android.webview.chromium.WebViewChromiumFactoryProvider.b(SourceFile:6)
        at com.android.webview.chromium.WebViewChromium.init(SourceFile:111)
        at android.webkit.WebView.<init>(WebView.java:678)
        at android.webkit.WebView.<init>(WebView.java:604)
        at android.webkit.WebView.<init>(WebView.java:587)
        at android.webkit.WebView.<init>(WebView.java:574)
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:647)
        at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:720)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:788)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at com.mine.ui.events.EventScreen.onCreateView(EventScreen.java:70)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
        at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:781)
        (... shortened ...)

The important line is:

at com.mine.ui.events.EventScreen.onCreateView(EventScreen.java:70)

Examining the mentioned line:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// This is the important line:
ViewGroup content = (ViewGroup) inflater.inflate(R.layout.mine_event, container, false);
WebView webView = (WebView) content.findViewById(R.id.container);
webView.loadUrl(event.getWebViewUrl());
webView.getSettings().setJavaScriptEnabled(true);
(...)

So I get the violation while the inflation happens, which I dont quite understand.

As you can see shortly after the mentioned line a WebView comes into play. I have looked at the source-code for the SmartSelectionEventTracker here and it seems like a generic class for Widgets like TextViews, WebViews, .... WebViews seem to be related to MockViews which are related to TextViews.

But apart from that finding I do not understand how / why the violation is happening and what I can do against it.

Can someome explain this to me?





How to extract field from interface

I would like to extract the time from the obj variable i have create trough a method of which you can pass multiple types(hence interface). i am using go for a language and tried to extract using reflection but that was a fail. Thanks in advanced for anyone who can solve this one if possible.

type Soft struct { Create *time.Time Delete *string Update *string }

                        type Obj struct {
                            Name string
                            Soft Soft
                        }

                        func main() {
                            var soft Soft
                            n := time.Now().Format(time.RFC3339)
                            now, _ := time.Parse(time.RFC3339, n)
                            nowUpdate := "update"
                            nowDelete := "delete"
                            soft.Create = &now
                            soft.Update = &nowUpdate
                            soft.Delete = &nowDelete

                            var obj Obj
                            obj.Name = "hi"
                            obj.Soft = soft
                            Extract(obj)
                        }

                        func Extract(a interface{}) {
                            aValue := reflect.ValueOf(a)
                            //i would like to extract the field named Soft from this and Convert it into time.Time.
                        }





mercredi 22 août 2018

How do get Nested Fields through reflection rather than object as a field

This is my old class structure .

 class User {
 private int userId;
 private String userName;
 private String userEmail;
 private String firstName;
 private String lastName;
 //.. getters and setters 
 }

And i was generating excel reports from this class exactly having same column as of property .

 Class<Object> headers = (Class<Object>) excelDataMapper.getClass();
 Field[] objectFields = headers.getDeclaredFields();
 for (int j = 0; j < objectFields.length; j++) {
  objectFields[j].setAccessible(true);
  Object value = objectFields[j].get(excelDataMapper);
 }

Now due to some requirement , structure of User class has changed to this

class User {
 private int userId;
 private String userName;
 private String userEmail;
 private UserBasicInfo basicInfo;
 //.. getters and setters 
 }

And Structure of UserBasicInfo

   class UserBasicInfo {
   private String firstName;
   private String lastName;
   private Date lastLoginDate;
   private int invalidLoginAttempt;
   // ..getters and setters ; 
 }

With nested object UserBasicInfo now i have different field in excell sheets UserBasicInfo which is not required , i want to continue with reports as previous structure only , i.e firstName , lastName which is now inside UserBasicInfo . For this i want to have something like this

        List<String> colHeaders= new ArrayList<String>();
        Class<LoginsReport> headers = LoginsReport.class;
        Field[] objectFields = headers.getDeclaredFields();
        for (int j = 0; j < objectFields.length; j++) {
            String fieldName = objectFields[j].getName();
            if(fieldName.indexOf("encrypted") == -1 && fieldName.indexOf("Mongo") == -1 &&  !(ArrayUtils.contains( excluededPropertyInLoginReports, fieldName ))  )
                colHeaders.add(fieldName);
        }
        colHeaders.add("userBasicProfile.firstName");
        colHeaders.add("userBasicProfile.lastName");





How do I create an instance of an F# option type using Activator.CreateInstance?

I can create a function to create an option type based on any type:

let createOptionType typeParam =
    typeof<unit option>.GetGenericTypeDefinition().MakeGenericType([| typeParam |])

...and I can confirm that the function works:

createOptionType (typeof<int>) = (Some 5).GetType() // returns true

...and I can create the value "Some 0" by doing this:

System.Activator.CreateInstance(x.GetType(), [| null |]) // returns Some 0

However, I don't know how to create any other "Some x" value, or how to create "None". (It appears that it creates "Some ", because for strings it's "Some null".)





How to get processed object and set it a new value to it in Java via Reflection API?

I was searching and learning Java Reflection API more about it. But I could not find some part of my problem's solution in it. The problem is, I want to change just one feature of my object. Here is code;

    public class Car{
          private String model_name;
          private int horsepower;
          public Tire t;

          public void setModelName(String s){
              model_name = s;
          }

          public void setHorsePower(int i){
              horsepower = i;
          }

          public String getModelName(){
              return model_name;
          }

          public int getHorsePower(){
              return horsepower;
          }
    }

    // Tire.java

    public class Tire{
          private String name;

          public void setName(String s){
              name = s;
          }

          public String getName(){
              return name;
          }
    }

    // Main class

    public class Main{
       public static void main(String []args){
           Car a = new Car();
           a.setModelName("Mustang 67");
           a.setHorsePower(700);
           a.t = new Tire("DummyBrand");
           Class c = a.getClass();
           Field []f = c.getDeclaredFields();
           for(int i = 0; i < f.length; i++){
               if(f[i].getType().getSimpleName().toString().matches("Tire"){
                   // How to change a object's t field's name variable? 
               }
           }
           System.out.printline(a.getModelName)   
       }
    }

I would be gladful if you guys and ladies can help. Thanks in advance.





IsEnum does not recognise enum

My .Net 4.0 code. Im trying to understand some legacy code i now work with. I cant change it at the moment and im sure this code has worked before my time. It needs to make an enum from strings. But the type is not recognized as en enum.

EDIT: I now realise the enum property is actually nullable. So its NetType? How can i convert that into an enum if it has a value?

When i debug and see the type that is being checked if enum this is what i see:

FullName = System.Nullable1[[AppName.Model.NetType, AppName.Model, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]
Name = Nullable
1

This is the enum

   public enum NetType
    {

        ChoiceOne = 1,

        ChoiceTwo = 2
    }

Main code, simplified for clarity:

var property = typeof(MainClass).GetProperty("NetType");
var value = GetValue(property.PropertyType, "ChoiceOne");


   private object GetValue(Type type, string valueString)
        {
            if (type.IsEnum)// Why false?
                return Enum.Parse(type, valueString);

            if (type == typeof (Int32))
                return Int32.Parse(valueString);

            return valueString;
        }





Trying to get the generic type from PropertyInfo [duplicate]

This question already has an answer here:

And let me say at the outset, that I know about the 'PropertyType' property.

So I've been working with a generic converter.

Usage is pretty simple; it looks like this:

int1 = TConverter.ChangeType<int>(strt1);

So that string becomes and int (if it can). And the above works fine. The problem, however, is that part between the angular brackets where the type is listed. I want to get the type of a PropertyInfo in there, but I can't see to.

The code, which I have simplified down to the main issue, looks like this:

foreach (PropertyInfo pi in props)
        {
            Type tp = pi.PropertyType;

            var converted = TConverter.ChangeType<tp>("Test");
        }

I guess I must be making a mistake because it has a problem with the contents of the angular brackets. I get this message: "Error 2 The type or namespace name 'tp' could not be found (are you missing a using directive or an assembly reference?)"

Can someone offer a solution?





linq query dynamically inside where

I would like to change dynamically a specific part of the query - depending on the result of if condition. I would be glad for your help:

if (someCondition == true)
    var ADDITION_FILTER_CRITERIA = && z.t.Name == Keyword
else
    var ADDITION_FILTER_CRITERIA = "";

                var ToursPerDestination = await _context.Tours
                 .Join(_context.CruiseDestinations, t => t.DestinationId, d => d.DestinationId, (t, d) => new { t, d })
                 .Where(z => z.d.CruiseId == SelectedCruise.CruiseId ADDITION_FILTER_CRITERIA )
                 .Select(z => new ToursViewModel()
                 {                   
                     Name = z.t.Name,                   
                 }).OrderByDescending(z => z.Name).ToListAsync().ConfigureAwait(false);





Iterate through property and creating an Expression

Im not used to working with expression funcs, but my problem is: I get the name of a property as a string, i then need to convert this to the appropriate expression.

Currently im doing something like this:

if (string.Equals(propertyString, "customerNo", StringComparison.InvariantCultureIgnoreCase))
        {
            return _repo.DoSomething(x=>x.CustomerNo);
        }
if (string.Equals(propertyString, "customerName", StringComparison.InvariantCultureIgnoreCase))
        {
            return _repo.DoSomething(x => x.CustomerName);
        }

With the repo function something like this:

public IEnumerable<ICustomer> DoSomething(Expression<Func<IObjectWithProperties, object>> express)
{
    //Do stuff
}

What i would like to do, is use reflection like this:

var type = typeof(IObjectWithProperties);
PropertyInfo[] properties = type.GetProperties();

foreach (PropertyInfo property in properties)
{
    if(string.Equals(property.Name,propertyString,StringComparison.InvariantCultureIgnoreCase))
        return _repo.DoSomething(x => x.PROPERTY);
}

But I can't figure out a way to generate the expression func from the propertyinfo





mardi 21 août 2018

Java initialising classes with populators in their constructor

I have a repository of classes in a package, in their constructor, they populate a component of the server.

For example:

The master class:

public abstract class MessageDecoder<T> {

    public MessageDecoder(boolean logicType, Integer...opcodes) {
        for (int opcode : opcodes) {
            GameConstants.RELEASE.register(logicType, opcode, this);
        }
    }

    /**
     * Get the encoded message to send to the client.
     * 
     * @param the {@link GamePacket} ready to be read.
     * @return a constructed message ready to be handled.
     */
    public abstract T decode(GamePacket packet);

}

And the repoistory classes look like:

public final class PlayerWalkPathMessageDecoder extends MessageDecoder<PlayerWalkPathMessage> {

    public PlayerWalkPathMessageDecoder() {
        super(true, 8, 58);
    }

    @Override 
    public PlayerWalkPathMessage decode(GamePacket packet) {

        return null;
    }

}

In the master class you can see how the method

register(logicType, opcode, this); 

is being used to register the class to a

map < Integer, MessageDecoder< ? > >

But during runtime, the map will not be populated because the repository classes have not been constructed yet.

This warrents me using an empty iterator to get the classes to be constructed:

Iterate.classes("bin/com/web/net/decoders", clazz -> {


});

Is there a better way to construct the classes located in a repository package?





How to use reflection to run to variable

I want to run this code

New main1().main2(); 

Where main1 is a variable and main2 is a variable thank you





Two different classes with identical AssemblyQualifiedName?

In a MSTest project I declare an internal class for a few tests. It's declared in the test project's namespace like this:

namespace Körningar.Test.Hjälpklasser
{
    internal interface ITestkörningParams { int Heltal { get; } string Text { get; } }
    internal class TestkörningParams : ITestkörningParams { public int Heltal { get; set; } public string Text { get; set; } }
    // ...
}

In a tested method I have an instance of this class parms, and iterate through it's properties to log its values:

// Create parms of type körningsparametrarKlass.
object parms = paramhämtare.HämtaParametrar(args, körningsparametrarKlass);

// Log the property values of the parms object.
log.Info($"Körningsparametrar:\r\n"
    + string.Join("\r\n",
        körningsparametrarKlass.GetProperties()
        .Where(pi => pi.GetGetMethod() != null)
        .Select(pi
          => $"{pi.Name} = {Convert.ToString(pi.GetGetMethod().Invoke(parms, null))}")
    )
);

This line of code throws a TargetException with message saying that the object doesn't match the target type.

The method paramhämtare.HämtaParametrar creates the returned object like this:

object parms = Activator.CreateInstance(körningsparametrarKlass)
// ...assign properties
return parms;

I fail to see how the parms object could possibly be the wrong type for a property getter that's extracted from körningsparametrarKlass, which is the same type that's instantiated for the parms object.

Examining the variables in VS Watch windows gives the following:

Dump from VS 2017 Watch window

As you can see, the AssemblyQualifiedName is the same for the parms object and the körningsparametrarKlass type, but the actual type objects differ (marked in the dump). As far as I know type objects should be comparable using ==, but I have also tested with körningsparametrarKlass.Equals(parms.GetType()) with the same result. Also note that all lines in the Watch window are actually up to date even though some are gray - I refreshed them all before taking the dump.

How can this happen, and how would i fix it?

I should also mention that this seems to happen only if I run tests for both this test project and another test project in the same solution. If I run only the test in question, or the entire test project that contains it, there is no exception.





Dynamically cast delegate to signature with interface at runtime

Context

Currently I am creating an Extract Load and Transform (ETL) application written in C# with .NET Core. The source of the ETL application is a Soap webservice, which contains a multitude of methods. Each entity (Employee, Company, etc) and way of retrieving (ByKey, ByQuery, etc) has its own Soap webservice method. For example if I were to retrieve the entity 'Employee' by executing a query, I would call the GetEmployeeByQuery method. All methods return a string with XML.

Visual Studio generated proxy classes of this webservice by its WSDL file (generated indirectly through dotnet-svcutil). Unfortunately the proxy classes generated for this service seem to be generated according to a message contract pattern. This means that the proxy method GetEmployeeByQuery returns the GetEmployeeByQueryResponse partial class, which has a field Body that contains the GetEmployeesByQueryResponseBody partial class. The actual result is located in a string field on the GetEmployeeByQueryResponseBody that has the name of GetEmployeeByQueryResult.

Ideally the ETL application is able to invoke Soap webservice methods through reflection and on the basis of application configuration. The configuration contains the method and parameters to call, and through some factories this results in a Delegate that will be used as a strategy elsewhere in the application. This delegate should be generic and not tied to any specific entity.

The Problem

Currently I have created a delegate with a signature that solely consists of the concrete type implementations. This is necessary because the Delegate.CreateDelegate method requires this in order to bind the actual method to the delegate. The signature is Func<string, string, string, string, Task<GetEmployeeByQueryResponse>>. This signature however is tied to a specific entity, which is what I am trying to prevent.

Therefore I am trying to cast this delegate to the signature Func<string, string, string, string, Task<IMessageResult<string>>> where the IMessageResult<string> is an interface implemented on the generated proxy code through a partial class.

Method that tries to retrieve more generic delegate

public static TMethodSignatureInterfaced GetMethodDelegate<TMethodSignatureInterfaced>(object classInstance, string methodName, Type methodSignatureTyped)
    where TMethodSignatureInterfaced : class
{
    //Another way of casting, same result.
    //TMethodSignatureInterfaced method = (TMethodSignatureInterfaced)(object)Delegate
    //    .CreateDelegate(methodSignatureTyped, classInstance, methodName) as TMethodSignatureInterfaced;

    TMethodSignatureInterfaced method = Delegate
        .CreateDelegate(methodSignatureTyped, classInstance, methodName) as TMethodSignatureInterfaced;

    if (method == null)
        throw new InvalidCastException($"Method {methodName} could not be cast into a delegate. The given method signature could not be found.");

    return method;
}

Unfortunately it seems that casting the delegate to another signature is not possibly dynamically. The code either throws an error (with the first casting technique) or returns null. In other posts I have seen cases where if the interface is specified casting a delegate is possible. I was wondering whether someone would know a way around this.





lundi 20 août 2018

Unity3D: Overlaying Line Renderer on reflecting Raycast

So I have the Reflecting Raycast up and running. Which is displayed here:

Working Raycast

Here is the Code:

 public int maxReflectionCount = 5;
public float maxStepDistance = 200f;


void Start()
{

}


void Update()
{

    Laser();
}


void Laser()
{
    DrawReflectionPattern(this.transform.position + this.transform.forward * 0.75f, this.transform.forward, maxReflectionCount);
}


private void DrawReflectionPattern(Vector3 position, Vector3 direction, int reflectionsRemaining)
{
    if (reflectionsRemaining == 0)
    {
        return;
    }

    Vector3 startingPosition = position;

    Ray ray = new Ray(position, direction);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit, maxStepDistance))
    {
        direction = Vector3.Reflect(direction, hit.normal);
        position = hit.point;
    }
    else
    {
        position += direction * maxStepDistance;
    }

    Debug.DrawLine(startingPosition, position, Color.white);

    DrawReflectionPattern(position, direction, reflectionsRemaining - 1);


}

What I would like help doing is overlaying a LineRenderer on top of this reflecting Raycast. I have looked up a few things online and watched some tutorials but still cant seem to get it working. Any help would be greatly appreciated!





Python possible to short circuit function call

I am building a function to construct objects with set attributes (similar to a namedtuple); however, the output length must be variable.

I would like to build a function that allows the user to append additional attributes through a function call. Importantly, I would like to find a way to 'short-circuit' parameters and am unsure if Python is powerful enough to do this.

To explain take this trivial example:

def foo():
    print("foo")
    return False

def bar():
    print("bar")
    return True

if foo() and bar():
    pass

Foo's function call returns False, and Bar short-circuits. The output console will only print foo, and bar is never executed.

Is there such a way to mimic this behavior with inspection or reflection in respect to function calls. Here is an example with my implementation is shown below:

from inspect import stack

cache = {}
def fooFormat(**kwargs):
    caller = stack()[1][3]

    if caller not in cache:
        class fooOut(object):
            def __init__(self, **kwargs):
                self.__dict__.update(kwargs)

            def optional(self, opt, **kwargs):
                if (opt):
                    self.__dict__.update(kwargs)
                return self

            def __str__(self):
                return caller + str(self.__dict__)
        cache[caller] = iadsOut
    return cache[caller](**kwargs)

def stdev(nums, avg = None):
    print("\tStdev call")
    if avg is None:
        avg = sum(nums) / len(nums)

    residuals = sum((i - avg)**2 for i in nums)
    return residuals**.5

def stats(nums, verbose=False):
    if verbose:
        print("Stats call with verbose")
    else:
        print("Stats call without verbose")

    total = sum(nums)
    N = len(nums)
    avg = total / N

    return fooFormat(
        avg = avg,
        lowerB = min(nums),
        upperB = max(nums)).optional(verbose,
        stdev = stdev(nums, avg))

In the function 'stats', the return fooFormat should of course yield avg, lowerB, and upperB; additionally, it should yield std if verbose is set to True. Moreover, the function 'stdev' should NOT be called if verbose is set to False.

stats([1,2,3,4], False)
stats([1,2,3,4], True)

Of course, a way around this is:

if verbose:
    return fooFormat(
        avg = avg,
        lowerB = min(nums),
        upperB = max(nums),
        stdev = stdev(nums, avg))
else:
    return fooFormat(
        avg = avg,
        lowerB = min(nums),
        upperB = max(nums))

However, I am hoping there to implement this behavior without a branch.





Serialize and Deserialize domain events to persist and retrieve from Event Store in generic implementation

I am using DDD with CQRS and Event Sourcing. I need to use an Event Store (specifically this event store) within my custom implementation of IEventStore to persist and retrieve domain events but I am having difficulties with the approach to take that deals with serialization/deserialization.

This is the interface I am implementing:

public interface IEventStore
{
    Task<IEnumerable<IDomainEvent>> GetEventsAsync(Identity aggregateIdentity, Type aggregateType);

    Task PersistAsync(IAggregateRoot aggregateRoot, IEnumerable<IDomainEvent> domainEvents);
}

Outside my implementation of IEventStore I can have mappers from every IDomainEvent into some serializable/deserializable EventDto or json string. That's not a problem. But these are my restrictions:

  • my domain events are immutable objects that implement IDomainEvent (i.e: no setters)

  • my domain events are not always easily serializable/deserializable in a generic way. Often they have abstract or interface properties, so the concrete mappers between my domain events and some serializable object such as string json or event DTO are decided outside my IEventStore implementation.

  • My IEventStore implementation needs to be generic in a way that if I add new domain event types, I should not need to touch anything within the IEventStore implementation

  • My IEventStore implementation can receive injected some specific implementations of IMapper<TSource, TDestination>, so that I could use a them to serialize/deserialize between specific types (not interfaces).

    public interface IMapper<in TSource, out TDestination>
    {
        TDestination Map(TSource source); // I have implementations of this if needed
    }
    
    

This below is my attempt:

public class MyEventStore
    : IEventStore
{
    private readonly IStreamNameFactory _streamNameFactory;
    private readonly IEventStoreConnection _eventStoreConnection; //this is the Greg Young's EventStore product that I want to use as database
    private readonly IDomainEventFactory _domainEventFactory;
    private readonly IEventDataFactory _eventDataFactory;

    public EventStore(
        IStreamNameFactory streamNameFactory, 
        IEventStoreConnection eventStoreConnection, 
        IDomainEventFactory domainEventFactory, 
        IEventDataFactory eventDataFactory)
    {
        _streamNameFactory = streamNameFactory;
        _eventStoreConnection = eventStoreConnection;
        _domainEventFactory = domainEventFactory;
        _eventDataFactory = eventDataFactory;
    }

    public async Task<IEnumerable<IDomainEvent>> GetEventsAsync(
        Identity aggregateIdentity, 
        Type aggregateType)
    {
        var aggregateIdentityValue = aggregateIdentity.Value;
        var streamName = _streamNameFactory.Create(aggregateIdentityValue, aggregateType);

        var streamEventSlice =
            await _eventStoreConnection.ReadStreamEventsForwardAsync(streamName, 0, Int32.MaxValue, false);

        var domainEvents = streamEventSlice
            .Events
            .Select(x => _domainEventFactory.Create(x));

        return domainEvents;
    }

    [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")]
    public async Task PersistAsync(
        IAggregateRoot aggregateRoot, 
        IEnumerable<IDomainEvent> domainEvents)
    {
        var numberOfEvents = domainEvents.Count();
        var aggregateRootVersion = aggregateRoot.Version;
        var originalVersion = aggregateRootVersion - numberOfEvents;
        var expectedVersion = originalVersion - 1;

        var aggregateIdentityValue = aggregateRoot.AggregateIdentity.Value;
        var aggregateRootType = aggregateRoot.GetType();
        var streamName = _streamNameFactory.Create(aggregateIdentityValue, aggregateRootType);
        var assemblyQualifiedName = aggregateRootType.AssemblyQualifiedName;

        var eventsToStore = domainEvents.Select(x => _eventDataFactory.Create(x, assemblyQualifiedName));

        await _eventStoreConnection.AppendToStreamAsync(streamName, expectedVersion, eventsToStore);
    }
}

The problems is mainly, as you can imagine, in the IDomainEventFactory implementation. I need a class that implements the following interface:

public interface IDomainEventFactory
{
    IDomainEvent Create(ResolvedEvent resolvedEvent);
}

This class needs to know which specific IDomainEvent does it need to deserialize the resolvedEvent to at runtime. In other words, if the event being retrieved is a json representation of MyThingCreatedEvent maybe I can use a service such as IMapper<ResolvedEvent, MyThingCreatedEvent>. But if the event being retrieved is a json representation of MyThingUpdatedEvent then I would need a service such as IMapper<ResolvedEvent, MyThingUpdatedEvent>.

Some approaches came to my mind.

OPTION 1: I thought I could have the IDomainEventFactory implementation use the autofac IComponentContext so that at runtime I could somehow manage to do some _componentContext.Resolve(theNeededType). But I don't know how to retrieve the IMapper that I need. Maybe this is something possible but I doubt it.

OPTION 2: Maybe I could have some mapping service such as IBetterMapper such as

public interface IBetterMapping
{
    TDestination Map<TDestination>(object source) where TDestination : class;
}

so that my factory can delegate the concern of knowing how to deserialize anything into TDestination. But I would have the same problem: I don't know how to create a type at runtime from a string, for example, to do something like _myBetterMapper.Map<WhichTypeHere> and there is the additional problem of implementing that Map method, which I guess would require some registration table and based on the type choose one or another specific mapper.

I am really stuck with this. Hopefully I get some help from you guys! :)





How do I Use Reflection API getParameters in Android API level 25 and Below?

I am currently building an in-app logger utility for Android that uses the Reflection API to log basic data about the called class/method/parameters.

Method.getParameters() is the call to retrieve an array of parameters for the given method, but this method only works on Android API level 26+. Does anyone know of a workaround that would let me use getParameters() on API level 25 or below?

Alternatively, if there is a decent workaround for this, that would work too! Thanks in advance! Here is the method I will be updating once I have a fix/workaround in place:

private Parameter[] _retrieveParametersForMethod( Method method ) {

    Parameter[] methodParameters;

    // getParameters() only works on API level 26+ (Oreo)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        return methodParameters = method.getParameters();
    } else
        return null;    // TODO: Find a workaround for pre-API level 26

}





VB.NET: Instantiate a nested property by reflection

I want to set the values of the properties via reflection. In this thread they propose a solution. But the problem with the solution is that it is not instantiating the properties. But I want to check and instantiate the properties if necessary. My DTO is:

Public Class root
    Public Property Printing() As rootPrinting
End Class

Public Class rootPrinting
    Public Property Printer() As String
    Public Property PrinterBatch() As String
End Class

Now for setting the properties I have defined the following function:

Public Sub SetProperty(ByVal target As Object, ByVal compoundProperty As String, ByVal value As Object)
    Dim properties As String() = compoundProperty.Split("."c)
    For i As Integer = 0 To properties.Length - 1 - 1
        Dim propertyToGet As PropertyInfo = target.[GetType]().GetProperty(properties(i))
        target = propertyToGet.GetValue(target, Nothing)
        if IsNothing(target) then
            if propertyToGet.PropertyType.IsClass then
                target = Activator.CreateInstance(propertyToGet.PropertyType)
            End If
        End If
    Next

    Dim propertyToSet As PropertyInfo = target.[GetType]().GetProperty(properties.Last())
    propertyToSet.SetValue(target, value, Nothing)
End Sub

Then I call it like this:

Dim configObject as New root
SetProperty(configObject , "Printing.Printer","skjfkd")

If before calling SetProperty(configObject,...) I instantiate configObject.Printing then it will work fine:

Dim configObject as New root
configObject.Printing = new rootPrinting()
SetProperty(configObject , "Printing.Printer","skjfkd") 

Otherwise after calling SetProperty(...), configObject.Printing will be Nothing.
It seems that when calling Activator.CreateInstance(propertyToGet.PropertyType) the reference to the original object is lost. While the object in the function is really initialized, the main object remains Nothing. How can I instantiate the class property correctly?





How to reflect parametes for QT signals slots connection?

I imlemented reflection for signals/slots connections, so my connector class is able to do something like:

QObject::connect (Object1, SIGNAL(Object1->*m_functionMap[SignalName](Params*)), Object2, SLOT (Object2->*m_functionmap[SlotName](Params*));

SignalName and SlotName are string parameters and known. Params* is a pointer to known registered parameter class.

Are there any ideas how to reflect parameters so i can change signature to :

QObject::connect (Object1, SIGNAL(Object1->*m_functionMap[SignalName])(OBject1->parameters[ParamName]), Object2, SLOT (Object2->*m_functionmap[SlotName] (OBject2->parameters[ParamName]));