samedi 22 juillet 2017

Safely importing external libraries during runtime in C#

I am building a program where I intend to provide an API, allowing other developers to build .dll libraries that are placed in a folder which my program can find at runtime and import them. I find the files and load them with Assembly.load(), then find the classes using Assembly.GetExportedTypes() which implement a particular interface.

This code is functioning correctly, but frankly I have some concerns about what developers could be importing, particularly with regard to actions such as running executables from their code, trying to access or delete files on the system outside of the program's folder structure, or potentially even establishing some sort of network connection and passing data forward.

I understand that I must accept some level of risk when allowing this sort of feature, but what can I do to harden the program from malicious activity while still allowing the import of external libraries for extensibility?





java getSuperclass().toString() not running my custom toString() (reflection)

[Hi, guys. I'm learning Java with Cay Horstmann's 'Java SE8 for the Really Impatient'. Studying chapter 4]

I want to call the toString() method of the parent class and add something to it. Unfortunately, the call to the toString() method of the parent class seems not to be working.

So far I've got these classes:

public class Point {
    private double _x = 0;
    private double _y = 0;

    public Point(double x, double y) {
        _x=x;
        _y=y;
    }

    @Override
    public String toString() {

        String theString = getClass().getSuperclass().toString() + " => " + getClass().getCanonicalName();

        theString += "[";
        int i=0;
        for (Field theField : getClass().getDeclaredFields()) {
            theField.setAccessible(true);
            try {
                if (i>0) theString += ", ";
                theString += theField.getName() + ": " + theField.get(this).toString();
                i++;
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(Point.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("err1");
            } catch (IllegalAccessException ex) {
                Logger.getLogger(Point.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("err2");
            }
        }
        theString += "]";
        return theString;
    }
    ...        
}

public class LabeledPoint extends Point {
    private String _label = "";

    public LabeledPoint(String label, double x, double y) {
        super(x, y);
        this._label = label;
    }

    ...

}

And I call them with this main method:

public static void main (String[] args) {
    LabeledPoint lp1 = new LabeledPoint("FirstPoint", 10.5, 30);
    System.out.println("The new point is:");
    System.out.println(lp1);
}

So, I was expecting to get something like this:

Point[_x: 10.5, _y:30.0]=>LabeledPoint[_label: FirstPoint]

But instead, I'm getting :

Point=>LabeledPoint[_label: FirstPoint]

That is, the getClass().getSuperclass().toString() is not executing Point.toString(), but it's just printing out the canonical name.

Why is that?





Using reflection, is there a way to load a .NET type with generic parameters without having to append the number of them to the name?

I am working on my own language and for the sake of .NET interop I've been using the Reflection methods to query the .NET types and method signatures.

open System
let asm = Reflection.Assembly.Load("mscorlib")
let dic = asm.GetType("System.Collections.Generic.Dictionary`2")

The above is how I would load the type of Dictionary directly from mscorlib. Note that unlike in standard code, the 2 at the end separated by the grave character is necessary.

Since C# and F# do not require specifying the number of generic parameters as a part of the name, I've been wondering whether there is a better way of doing this?

This is awkward because right now, I have to write out the full name in my language's code as well.





vendredi 21 juillet 2017

Finding annotated methods in application code from maven integration test

I have a custom annotation in my program that I apply to methods. I would like to find all methods with a particular annotation. From my application code, I can use the Reflections package to do so:

new Reflections(
    new ConfigurationBuilder().setUrls(
        ClasspathHelper.forPackage("com.my.package")
    ).setScanners(new MethodAnnotationsScanner())
    ).getMethodsAnnotatedWith(MyAnnotation.class);

However, when I try to do the same from an integration test invoked via failsafe, no methods are found. How can I get my annotated methods from an integration test?





Int Type vs scala.Int Type

I'm using scala reflections to get all fields of a case class that are not methods. I then want to see if the type is a primitive type or string (or an option of these things). Here's a simple working example that checks if a field is a String.

scala> case class SimpleCase(val1: String)
defined class SimpleCase

scala> val members = typeOf[SimpleCase].members.filter(!_.isMethod).toList
members: List[reflect.runtime.universe.Symbol] = List(value val1)

scala> members.head.typeSignature
res57: reflect.runtime.universe.Type = String

scala> members.head.typeSignature == typeOf[String]
res58: Boolean = true

Works exactly the way that I would expect it to. Here's where things get weird - when I do the same thing with an Int, or any primitive type for that matter, the type checking test fails. Here's an example of said failure:

scala> case class SimpleCase(val1: Int)
defined class SimpleCase

scala> val members = typeOf[SimpleCase].members.filter(!_.isMethod).toList
members: List[reflect.runtime.universe.Symbol] = List(value val1)

scala> members.head.typeSignature
res59: reflect.runtime.universe.Type = scala.Int

scala> members.head.typeSignature == typeOf[Int]
res60: Boolean = false

scala> members.head.typeSignature == typeOf[scala.Int]
res61: Boolean = false

Also, typeOf[Int] prints out

scala> typeOf[Int]
res62: reflect.runtime.universe.Type = Int

The type signature of SimpleCase's val1 states that it is a scala.Int rather than typeOf[Int]'s type signature, which is Int. So I tried comparing val1 to both typeOf[Int] and typeOf[scala.Int] (even though I'm pretty sure they're the same thing) to no avail.

What's going on here? Is there a way around this?





How to convert an Object by the type name and pass it as an argument to another method

here is my code:

using System.Reflection;
Public class ClassA
{
    public ClassA()
    {
        ClassB classB = new ClassB();
        classB.UsingType = "ClassD";
        ClassB.Do();
    }
}
Public class ClassB
{
    public string UsingType { get; set; }
    public void Do()
    {
        ClassC classC = new ClassC();
        Type type = Type.GetType(UsingType);
        Object obj = Activator.CreateInstance(type);
        classC.Do(obj); // Error : cannot convert from 'object' to 'ClassD'
    }
}
public class ClassC
{
    public void Do(ClassD classD) // If I change "ClassD" to "Object" It works!!
    {
        //Do something with classD
    }
}

I get this error: "cannot convert from 'object' to 'ClassD'."

If I change "Do" method argument of "ClassC" from "ClassD" to "Object" the error goes away and then I can cast it to "ClassD" and use that parameter. But that's not what I want.

Is there a way to cast "obj" by "UsingType" string to "ClassD" (in "Do" method of "ClassB") and get rid of the compile time error?

In other words: (since "ClassA" knows the type name string and passes it to "ClassB") how can I cast from "Object" to the type that "ClassC" asks for?





OOP Pattern - using abstract with reflection a lot. Is this a bad pattern I'm falling into?

Lately I've been using this sort of pattern a lot:

abstract class myBaseClass
{
    //some common methods/properties/etc that all inheritors would share
    //some abstract methods/properties/etc that inheritors must implement

    protected abstract bool DoIHandleThisSortOfRequest(...);

    public static myBaseClass GetHandler()
    {
        // some reflection to enumerate through classes
        // that inherit from myBaseClass, and use
        // something like DoIHandleThisSortOfRequest() on each
    }
}

... and, I mean, the code is nice and neat... but it does mean I'm using reflection quite a bit.

For example, I'm currently working on a new process that works via command line than needs to handle a lot of different request types, and found myself using this sort of pattern, kinda like this:

abstract class FunctionRequest
{
    protected abstract string RequestName { get; }
    public abstract void Run();
    public static FunctionRequest GetHandler(string requestName)
    {
        // use reflection to get list of classes deriving from FunctionRequest
        // find one that has instance.RequestName equals requestName
    }
}
public class QueryRequest : FunctionRequest
{
    protected override string RequestName { get { return "Query"; } }
    public override void Run()
    {
        // ... code ...
    }
}

Is there a better way to structure this? I'm not too worried about the overhead of Reflection on this... but I realize if there's a better way to do it, I should get in the habit of doing it the right way :-)