vendredi 21 juillet 2017

Sample Code to Demonstrate Bug with Reflection API

I've a Java 8 code that heavily uses Reflections API. While going through the known issues in JDK 8, I came across this bug. The synopsis of the bug is as follows:

Area: Core Libs / java.lang.reflect

Synopsis

The array returned from the Class.getMethods() method may include methods that are not members of the class. The array may include methods from superinterfaces that have a more specific match in a different superinterface.

Could somebody demonstrate this bug with a simple code, just for me to check if my code is a victim of this bug?





Reflection in C#

In Java I have:

Reflections reflections = new Reflections("my.project.methods"); 
Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(SomeAnnotation.class);

How can I achieve it in C#? I need use namespace where my classes with methods are? But how to do that?





Unboxing values of F# discriminated unions

Some functions of my F# code receive values boxed as object even though the underlying values are typed. If the value is a discriminated union, it's not possible to unbox it back to its F# type. Here is a simple example:

type Result<'TOk,'TError> = 
| Ok of 'TOk 
| Error of 'TError

type ResultA = Result<string, int>

let a = Ok "A"
let o = box a

match o with
| :? ResultA -> printfn "match ResultA"
// | :? ResultA.Ok -> printfn "match" // doesn't compile
| _ when o.GetType().DeclaringType = typedefof<ResultA> -> printfn "match via reflection"
| _ -> printfn "no match"

The output from this example is "match via reflection", ResultA is never matched because the boxed value is of a different CLR type - Result.Ok. Since F# discriminated union cases are represented as its own types, the boxed value doesn't match the type ResultA. Moreover, it's not possible to match it to ResultA.OK because inside F# code it's not a legal type. The only option seems to be manual instantiation of a value using reflection, which is inefficient and silly because the value is already instantiated, it's here, it just can not be accessed in F# code once it's boxed.

Am I overlooking something? Is there a more straightforward way of unboxing an F# discriminated union value?





How do I show required rest parameters to the client and validate them?

I am creating a notification tool which supports multiple notifications. Each notification type has some mandatory fields. Ex:

class EmailParam {
  @NotEmpty
  private List<String> emailIds;
}

class JiraParam {
  @NotNull
  private String issueType;
  @NotNull
  private String project;
  private List<String> watchers;
}

My Rest API would take the notification type and the parameters as the JSON request body. What would be the best way to show the client, which are the mandatory parameters with their field types for a notification type? I am confused on whether I should use Jackson to get the fields and expose them via an API. Sample rest api:

POST /alert/1
  {
    notificationTypes: [email, jira],
    emailIds: [test@domain.com],
    issueType: task,
    project: notify,
    watchers: []
  }

POST /alert/2
  {
    notificationTypes: [email],
    emailIds: [test@domain.com]
  }

Also, do I have to use a custom validator, or can I use somehow use Hibernate's validator in this case?





workaround for `java.lang.SecurityException: Prohibited package name` on regex Pattern

java.util.regex.Pattern has a method Map<String, Integer> namedGroups(). For some reason they decided to make it private, and so there is no way to obtain this very useful information! :(

I've tried accessing this information (read-only) with this helper class:

package java.util.regex;

import java.util.Collections;
import java.util.Map;

public class PatternHelper {
    public static Map<String, Integer> getNamedGroups(Pattern pattern) {
        return Collections.unmodifiableMap(pattern.namedGroups());
    }
}

But Java8 complains with java.lang.SecurityException: Prohibited package name: java.util.regex.

How can I access this information (read-only)? maybe by reflection?





jeudi 20 juillet 2017

Create Dynamic properties from Datatable

I have below class with one property.

  public class MfrYearEqpType
  {   
    public string EqpType { get; set; }

    public MfrYearEqpType()
    {
    }
  }

I wanted to create dynamic properties(Datatable column names) to my class "MfrYearEqpType" and set the values from below Datatable.

DataTable dt = getData();

This table contains 26 rows and 10 columns of data.

I have gone through the below link. But I am not sure how to handle my case.

Dynamically adding properties to an Object from an existing static object in C#

And also I have used ExpandoObject. I have done below sample.

  DataTable dt = getData();

  List<dynamic> expandoList = new List<dynamic>();

  foreach (DataRow row in dt.Rows)
  {
    //create a new ExpandoObject() at each row
   var expandoDict = new ExpandoObject() as IDictionary<String, Object>;
   foreach (DataColumn col in dt.Columns)
   {
      //put every column of this row into the new dictionary
      expandoDict.Add(col.ToString(), row[col.ColumnName].ToString());
   }

   //add this "row" to the list
   expandoList.Add(expandoDict);
   }

But my aim is to create the List of MfrYearEqpType. So that I can bind List of MfrYearEqpType to Gridview.

Please help me on this.





c# - How to set the correct order of the parameters invoking with reflection?

I need to call any method from any class (in the same assembly) and passing trought the parameters. So far so good (I believe), but Invoke ask me for an object array (which I can get) but in the same order that is predefined in the method.

I made this class for the parameters:

public  class Parametros {
    public string type { get; set; }
    public string name { get; set; }
    public object value { get; set; }

}

and my method to "invoke" is the following:

    public static void Executar(string namespaceClass, string metodo,List<Parametros> parametros) {
        Type type = Type.GetType(namespaceClass);
        Object obj = Activator.CreateInstance(type);
        MethodInfo methodInfo = type.GetMethod(metodo);
        List<object> myParams = new List<object>();
        foreach (Parametros myparam in parametros) {
            //Get and order the params
            myParams.Add(myparam.value);
        }

        methodInfo.Invoke(obj, myParams.ToArray());
    }

Without the solution of specify the order in my class Parametros, there is any way to accomplishment this, getting the names of the parameters and send it to the invoke method?

Thanks in advance, is the first time I use invoke and this is I get so far.