jeudi 31 mai 2018

Adding an annotation to a class using Javassist

I am trying to add annotation to class dynamically using javassist

My code as follows

private Class addFrequencyAnnotation(String className,String annotationName, int frequency) throws Exception{
    ClassPool pool = ClassPool.getDefault();
    CtClass ctClass = pool.makeClass(className);

    ClassFile classFile = ctClass.getClassFile();
    ConstPool constpool = classFile.getConstPool();

    AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
    Annotation annotation = new Annotation(annotationName, constpool);
    annotation.addMemberValue("frequency", new IntegerMemberValue(classFile.getConstPool(), frequency));
    annotationsAttribute.setAnnotation(annotation);

    ctClass.getClassFile().addAttribute(annotationsAttribute);

    return ctClass.toClass();
  }

But the class returned does not have annotation added. I am not sure what is missing in my code. Could someone help to identify the issue?





mercredi 30 mai 2018

ClassCastException while using Java Reflection

I'm working with a stub that receives data from the skeleton:

MethodCallMessage reply = messageManager.wReceive();
        String returnString = reply.getParameter("result.string");
        int returnInt = Integer.parseInt(reply.getParameter("result.integer"));
        char returnChar = reply.getParameter("result.character").charAt(0);
        boolean returnBool = Boolean.valueOf(reply.getParameter("result.bool"));
        System.out.println("String return value in Invocation Handler: " + returnString);
        System.out.println("Int return value in Invocation Handler: " + returnInt);
        System.out.println("Char value in Invocation Handler: " + String.valueOf(returnChar));
        System.out.println("Bool value in Invocation Handler: " + String.valueOf(returnBool));

Then I try to create an instance of a class which is in a different package:

Class c = Class.forName(method.getReturnType().getName());
c.newInstance();

I can get to the methods so I thought everything was dandy:

Method[] methods = c.getDeclaredMethods();
        System.out.println("size: " + methods.length);
        for(Method method1: methods){
            System.out.println(method1.getName());
            if(method1.getReturnType().equals(String.class) && method1.getReturnType().toString().startsWith("set")){
                System.out.println("heir");
                method1.invoke(c, returnString);
            }
            if(method1.getReturnType().equals(Integer.class) && method1.getReturnType().toString().startsWith("set")){
                method1.invoke(c, returnInt);
            }
            if(method1.getReturnType().equals(Character.class) && method1.getReturnType().toString().startsWith("set")){
                method1.invoke(c, returnChar);
            }
            if(method1.getReturnType().equals(Boolean.class) && method1.getReturnType().toString().startsWith("set")){
                method1.invoke(c, returnBool);
            }

        }

and at the end of it all I return the object:

return c;

But then I get:

java.lang.ClassCastException: java.lang.Class cannot be cast to be.kdg.distrib.testclasses.TestObject

The package is what I pass trough the Class.forName() . How come I can get to the methods and fields but can cast it?





How to get default value of an enum from a type variable

Given an object (unknown at design time), I loop on its properties to do some processes. On each property, I have to check whether its value is different from the default value or not.

foreach(var p in propertyInfos)
{
    if (something) { ... }
    else if (p.PropertyType.IsEnum)
    {
        object oDefault = GetDefaultValueOfThisPropertyByWhateverMethod();
        if (oDefault == null)
            oDefault = default(p.PropertyType); // not valid
        var vValue = p.GetValue(myObject);

        if (!oDefault.Equals(vValue))
            // Do something enum specific when value is not the default one.
    }
}

How could I achieve this, knowing that there may exist enums that do not containt items with value 0?





Code Coverage - Inconsistency between Jacaco and Sonar 7.0

I have a Utility class, which consists of certain Strings and a private constructor. Using Reflections I have tested that constructor as well and these strings are used in turn in other classes for which tests are there. Jacoco shows full code coverage. When I run it in Sonar, the coverage shows these constructors and Strings are not covered. Why is it so? Sonar picks up the Jacoco reports for showing up coverage( If I am right). Then why is this inconsistency. Thanks in Advance





What is the best way to check if two properties are the same

I have to check if two PropertyInfo variables refer to the same property. See example from below: enter image description here I know, that these are the same, because:

  • The one on the right is returned by type.GetProperties()
  • The one on the left is returned by such an expression: (PropertyInfo)((MemberExpression)e.Body).Member, where e is property access expression
  • I can always be sure that both sides come from the same type.

But equality check returns false, as they are the result of different reflection operations.

I know I could rely only on Name in my actual case, but because I want to have a generic approach, I would probably need to check at least DeclaringType also. Would this be enough?

From performance point of view my best guess is comparing MetadataToken property, but from what I could understand from this, I am not sure if scopes could or could not interfere in such a situation.

Thank you for sharing your ideas.





How to create controls dynamically based on their type as string?

I know I can create controls using the following code:

var type = typeof(MyControl).Assembly.GetType("MyNamespace.MyControl", true);
MyControl t = Activator.CreateInstance(type) as MyControl;    

However, I have quite a few different controls that I need to create dynamically. All I have is a list of the types as string and I would like to loop through the list and create each control. So I have to remove strong-typing from the above code.

Is it possible?





mardi 29 mai 2018

How to create an Angular 6 service dinamically?

I'm looking for a transparent way to make HTTP requests using my ApiService classes. In the code below QuestionService, AuthService and RegisterService are children of ApiService.

The idea is to inject Api into a component in order to make a call like api.request('auth').get().

Basically, what I need is to remove the SERVICES map below and replace its reference by something like new window[name](this.http). Where name should be a string with the service name (ex: 'AuthService').

The problem is that services are not stored globally and I can't find how to access their classes. I looked at Injector class, but it requires a type, instead of a string ( https://angular.io/api/core/Injector ) .

const SERVICES = {
    'questions': QuestionService,
    'login': AuthService,
    'register': RegisterService,
};

@Injectable()
export class Api {
    public service: ApiService;

    constructor (private http: HttpClient) {

    }

    public request (name: string): Api {
        if (!SERVICES[name]) {
            throw new Error('Unknown service. ' + name + ' could not be found');
        }

        this.service = new SERVICES[name](this.http);
        return this;
    }
}

Any thoughts on how can I accomplish that?





Cannot get Method from assembly at runtime

I'm using the following code to load an assembly at runtime and then get a reference to a specific method and obviously execute it at the end:

var assemblyLoaded = Assembly.LoadFile(absolutePath);
var type = assemblyLoaded.GetType("CreateContactPlugin.Plugin");

var instance = Activator.CreateInstance(type);

var methodInfo = type.GetMethod("Execute", new Type[] { typeof(System.String)});
if (methodInfo == null)
{
    throw new Exception("No such method exists.");
}

Here is the assembly that I'm calling

namespace CreateContactPlugin
{
   public class Plugin
   {

    static bool Execute(string contactName){
        bool contactCreated = false;
        if (!String.IsNullOrWhiteSpace(contactName))
        {
            //process
        }
        return contactCreated;
    }

  }
 }

I can succesfully load the Assembly, the Type. When I highlight the type variable, I see the method listed in the DeclaredMethods array. But when I try to get the Method, it returns always null.

Does somebody see what I might be doing wrong here ?





Custom Annotation not found while unit testing

say i've an Annotation like that:

@Retention(RetentionPolicy.RUNTIME)
public @interface AutoConvert {
    boolean enabled() default true;
}

and class annotated with it:

@AutoConvert
public class ExampleCommandToExample extends BaseConverter{}

On the superclass i'am doing the following:

Annotation annotation = (AutoConvert) this.getClass().getAnnotation(AutoConvert.class);

Everything works fine on runtime!

But! While unit testing it with JUnit: getAnnotation(AutoConvert.class) always returns null.

Has anyone an answer for me? I would really appreciate it.

Thank you in advance.





Manipulating the DeclaringType of a MethodInfo - Is it possible?

Basically, I have a class, let's call it 'Controller', that takes a MethodInfo as a constructor parameter. So, the class that creates this MethodInfo is called 'Descriptor'. The problem is that when 'Controller' calls the MethodInfo, it always fails with:

//MethodInfo creation on Descriptor
var mx = new Func<string>(() => "foo").Method;

//Error caused when Controller runs it
ArgumentException: Method '..anonymous...' declared on type 'Descriptor' cannot be called with instance of type 'Controller'
System.Linq.Expressions.Expression.ValidateCallInstanceType(Type instanceType, MethodInfo method)

The 'Controller' class is completely off limits for me. Do you guys have any suggestion?





Java: Dynamically create object from class name, with arguments

I have a Java class whose name is stored in a database, that I want to load at runtime. I am using reflection to try to do this, but the current code throws an InvocationTargetException:

String classname = "my.test.path.Class";
Class<?> cls = Class.forName(classname);
Constructor<?> cons = cls.getConstructors();
for (Constructor<?> con : cons) {
    System.out.println(con.toString()); // Does find the constructor
}
Constructor<?> constructor = cls.getConstructor(Integer.class, Details.class);
ClassInterface object = (ClassInterface) constructor.newInstance(id, details);





Compare generic-interface-type to given type

I'm trying to dynamically create an instance of a type which inherits from a generic interface.

For example I have the following base-interface, where several other interfaces are derived from:

public interface IDummy { }

And I have two derived interfaces:

public interface IDummyDerived<T> : IDummy
{
  void Foo(T value);
}

public interface ITempDerived<T> : IDummy
{
  void HelloWorld(T value);
}

Now I need a ServiceProvider-Class where I can create find the classes which implementing the given interface. Each interface (IDummyDerived and ITempDerived) is implemented exactly once.

My approach would be:

internal class DummyServiceProvider
{
  public T GetDummy<T>() where T : IDummy
  {
    Type baseType = typeof(IDummy);
    Type[] types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Where(p => baseType.IsAssignableFrom(p) && p.IsClass).ToArray();
    //now I have all classes which implements one of my interfaces
    foreach(Type type in types)
    {
      // here I want to check if the current type is typeof(T)
      // (typeof(T) == type) ->  doesn't work
      // (type.GetGenericTypeDefinition() == type) doesnt work

    }
  }
  return default(T);
}

How can I correctly compare the given typeof(T) to a type in the types-array?





How to instantiate dynamically interface, and use their methods?

I'm working on a simple 2D game in Java. There's 2 Robot: they can move, fight etc.. These classes implement same interface.

Questions are:

  1. How to instantiate Robots in run time? I mean, when the program is running, ask the user to load classes, after that use their methods (Press 1 to get your own shield points..) like a role playing games.. I tried to do with Reflection but it doesn't work on interface.

    My reflection method:

    public void invokeClassMethod(String classBinaryName, String methodName) {
    
        try {
            ClassLoader classLoader = this.getClass().getClassLoader();
            Class<?> loadClass = classLoader.loadClass(classBinaryName);
    
            System.out.println("Loaded class name: " + loadClass.getName());
    
            Constructor<?> constructor = loadClass.getConstructor();
            Object classObject = constructor.newInstance();
    
            Method method = loadClass.getMethod(methodName);
            System.out.println("Invoked method name: " + method.getName());
            method.invoke(classObject);
    
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    
  2. Is it a good way to get enemyPosition()?

Robot interface:

public interface Robot {

    public String getPosition();

    public String getEnemyPosition();

    public String getArenaSize();

    public int getShield();

}

Robot1 class:

public class Robot1 implements Robot {

    private int xCurrent;
    private int yCurrent;
    private int shield;
    private final int attack = 1;

    Robot robot2;

    public Robot1() {
    }

    public Robot1(int x, int y, int shield, Robot robot2) {
        this.xCurrent = x;
        this.yCurrent = y;
        this.shield = shield;
        this.robot2 = robot2;
    }

    @Override
    public String getPosition() {
        return "x: " + xCurrent + " y: " + yCurrent;
    }

    @Override
    public String getEnemyPosition() {
        return robot.getPosition();
    }

    @Override
    public int getShield() {
        return shield;
    }
}

  1. Furthermore the Arena class stores game board informations like arena size, printing etc... If I want to operate on this arena (moving Robot objects [1][1] ---> [3][2]) how to connect Robot interface and Arena with each other?

  2. Where to store their positions (in concrete class or somewhere else)? Is aggregation a best way?How to avoid tight coupling?





lundi 28 mai 2018

Return a class, not an instance, of a concrete class that extends an abstract base class?

If I have a class hierarchy like this

AbstractSuperClass
    ConcreteClassA
    ConcreteClassB

is it possible to have a static method in AbstractSuperClass which returns the class - not an instance - of one of the two concrete classes?

I've tried returning Class<AbstractSuperClass>, but the IDE (Android Studio) says

Incompatible types.
Required: Class <com.example.AbstractSuperClass>
Found:    Class <com.example.ConcreteClassA>

Here's an example of what I'm thinking, but which isn't working:

public abstract class AbstractSuperClass{

    public abstract void someAbstractMethod();


    public static String getSomeText(){ 
        return "This is AbstractSuperClass"; 
    };

    public Class<AbstractSuperClass> getConcreteClass(int x){
        switch( x ){
            case 0: return ConcreteClassA.class;
            case 1: return ConcreteClassB.class;
        }
    }
}


public class ConcreteClassA extends AbstractSuperClass{
    public abstract void someAbstractMethod(){
        // Do something
    }

    public static String getSomeText(){ 
        return "This is ConcreteClassA"; 
    };
}



public class ConcreteClassB extends AbstractSuperClass{
    public abstract void someAbstractMethod(){
        // Do something
    }

    public static String getSomeText(){ 
        return "This is ConcreteClassB"; 
    };
}



AbstractSuperClass.getConcreteClass(1).getSomeText(); // Should return "This is ConcreteClassB"

Is this simply impossible in Java, or am I just doing it wrong?





what will be syntax of getMethod() in Java reflection if parameter of method is of Generic type? [duplicate]

This question already has an answer here:

General syntax for getMethod() is getMethod("method_name",Parameter_types)...what happens if method has generic type as parameter.

Class Example
   {
     void display(T t)
    {     }
    pvsm(String []ar)
    { 
    Class<Example> obj=Example.class;
    Method mth=obj.getMethod("display",?); //what will be in place of ??

    }
   }





Reflection to get if class has an interface that "implements" another interface

I'm currently trying to achieve the following:

I have a interface this interface:

public interface IRepository<TEntity>
{
   //Some Methods
}

Then I have another interface that extends the one above:

public interface IAttractionRepository : IRepository<Attraction>
{
   //More methods
}

Finally, I have an implementation (that also implements other interfaces):

public class AttractionRepository : ISomethingElse, IAnotherSomethingElse, IAttractionRepository
{
  //Implementations and methods
}

What I am trying to achieve is: Provided type AttractionRepository, I want to search it's interfaces and get which one is extending the intercface IRepository.

My code is as follows:

Type[] interfaces = typeof(AttractionRepository).GetInterfaces(); //I get three interfaces here, which is fine.
Type iface = null;

foreach (Type t in interfaces) //Iterate through all interfaces
    foreach(Type t1 in t.GetInterfaces()) //For each of the interfaces an interface is extending, I want to know if there's any interface that is "IRepository<Attraction>"
        if (t1.IsSubclassOf(typeof(IRepository<>).MakeGenericType(typeof(Attraction)))) //Always false
            iface = t;

I have tried several other solutions but with no success.





Get entity by annotation when SpringApplication startup

Who has an idea how can i get all the entities that has specific annotation, for exemple @Table jpa's annotation, when SpringApplication startup





Put reflect.Method to a functional interface

For example, I have a class with a method

public class SomeClass {
    public void someMethod(Object arg) {
        //some code
    }
}

And I obtained method through reflection in another class:

SomeClass instance = new SomeClass();

Method method = someClass.class.getMethod();

Is there any way to put it to a Consumer<Object> and then use with Consumer.accept(), or do I have to use something like this:

Consumer<Object> consumer = object -> method.invoke(instance, new Object())





Java Reflection: Call abstract interface methods without instantiation

I am currently facing problems integrating the existing Piketec TPT Java API (http://javadoc.jenkins.io/plugin/piketec-tpt/com/piketec/tpt/api/package-summary.html) in a Java project by using Reflection.

The TPT Api provides an interface called "TptApi", which contains several abstract methods, that are used to access TPT projects.

I have already integrated other APIs such as the Dox4j-API, where a class instance was used as invokation target. Obvisouly, this is not the correct way for accessing method from an interface.

My goal is to access the method "OpenResult openProject(File f)" from the TptApi interface (http://javadoc.jenkins.io/plugin/piketec-tpt/com/piketec/tpt/api/TptApi.html#openProject-java.io.File-).

My code:

ClassLoader cl = new URLClassLoader(...); Map c = new HashMap();

File file = new File("test.prj");

c.put("TptApi", cl.loadClass("com.piketec.tpt.api.TptApi")); c.put("OpenResult", cl.loadClass("com.piketec.tpt.api.OpenResult"));

//The way I did it with 'normal' classes, not applicable with the interface: //Object target = ((Class) c.get("TptApi")).newInstance();

OpenResult or = (OpenResult)((Class) c.get("TptApi")).getMethod("openProject", new Class[]{File.class}).invoke(target, new Object[]{_file});

So how do I access abstract interface methods by Reflection?





dimanche 27 mai 2018

Golang populate function parameters with struct values

I'm wondering is there is a way to populate a variadic function parameter in golang with all the values of a struct (which will typically be of varying types).

The specific example I'm thinking of is the following snippet to generate a row for a mocked postgres database query using https://github.com/DATA-DOG/go-sqlmock:

rows := sqlmock.NewRows([]string{
        "id",
        "updated_at",
        "created_at",
        "meta",
        "account_id",
        "currency",
        "nickname",
        "scheme_name",
        "identification",
        "name",
        "identification_secondary",
        "servicer_scheme_name",
        "servicer_identification",
        "institution_id",
        "client_id",
    }).AddRow(
        mock.Values.AccountID,
        time.Now(),
        time.Now(),
        "{}",
        "12345678",
        "GBP",
        "Test",
        "Schema",
        "12345676534263",
        "New account",
        "12345",
        "schema",
        "test id",
        mock.Values.InstitutionID,
        mock.Values.ClientID,
    )

Given the parameters always represent a struct (fields and values), I was attempting to use a struct to populate both the fields and values rather than complete each manually. Fields is fairly simple with reflection, however the values are of multiple types with the AddRow function defined as:

AddRow func(values ...driver.Value) *Rows

Is there a way to loop over struct fields and provide typed values to achieve something like?...

account := Account{
        ID:             "ABCD12436364",
        UpdatedAt:      time.Now(),
        CreatedAt:      time.Now(),
        Meta:           "{}",
        AccountID:      "12345678",
        Currency:       "GBP",
        Nickname:       "Test",
        SchemeName:     "Scheme",
        Identification: "12345676534263",
        Name:           "New account",
        IdentificationSecondary: "12345",
        ServicerSchemeName:      "scheme",
        ServicerIdentification:  "test id",
        InstitutionID:           "ABCD123456",
        ClientID:                "ZXCVB12436",
    }

rows := sqlmock.NewRows(account.GetFieldsJSON()).AddRow(account.GetValues())





How to have type reflection in Haskell

I've written a simple Yesod Rest Server that persists entities in JSON files. Entities are stored on disk in files named data/..json. For instance retrieveCustomer "1234" should load data from file data/Customer.1234.json.

I'm using a polymorphic function retrieveEntity that can retrieve instances of any data type that instantiate the FromJSON typeclass. At the moment I fill in the type name hardcoded in type-specific functions like retrieveCustomer.

How do I manage to compute the type name dynamically in the generic retrieveEntity? I think I'm basically looking for a Haskell type reflection mechanism which I did not come across so far?

-- | retrieve a Customer by id
retrieveCustomer :: Text -> IO Customer
retrieveCustomer id = do
    retrieveEntity "Customer" id :: IO Customer


-- | load a persistent entity of type t and identified by id from the backend
retrieveEntity :: (FromJSON a) => String -> Text -> IO a
retrieveEntity t id = do
    let jsonFileName = getPath t id ".json"
    parseFromJsonFile jsonFileName :: FromJSON a => IO a

-- | compute path of data file
getPath :: String -> Text -> String -> String
getPath t id ex = "data/" ++ t ++ "." ++ unpack id ++ ex

-- | read from file fileName and then parse the contents as a FromJSON instance.
parseFromJsonFile :: FromJSON a => FilePath -> IO a
parseFromJsonFile fileName = do
    contentBytes <- B.readFile fileName
    case eitherDecode contentBytes of
        Left msg -> fail msg
        Right x  -> return x





samedi 26 mai 2018

2d circle rect collision with details

I have game with map builded by rectangles, darker rectangles (named "closed") mean its place where balls should be able to move, ball should reflect from the lighter rectangles(named "open") border. In future Ill add more balls and they will reflect from each other.

The problem is with new Vector after collision.

I force function circleRectGetCollisionNormal() to return vector(-1,0) what i think its normal for this case. Ball is starting with deegres and change it simply to vector, this reflection worked for 45 deegres but when I change angle to 10 deegres ball moved into lighter rectangles(named "open").

Here is how it looks like (Picture)

Im doing like this:

1-check is ball collid with lighter rectangle.

2-if it collid, i want to change direction so i return vector for example for right side of ball colliding with rectangle return [-1,0] (I think its normal of vertical line, and its pointing left direction).

3-calculate new ball move Vector from this equation: newMoveVector = oldMoveVector − (2 * dotProduct(oldMoveVector, normalVector) * normalVector)

Here is code for each step:

1.

   circleRect(circlePos, circleSize, rectPos, rectSize) { 
//its rectRect collision but it doesnt matter because reflection surface is always horizontal or vertical
        let r1 = {
            left: circlePos.x - circleSize.x/2,
            right: circlePos.x + circleSize.x/2,
            top: circlePos.y - circleSize.y/2,
            bottom: circlePos.y + circleSize.y/2
        };
        let r2 = {
            left: rectPos.x,
            right: rectPos.x + rectSize.x,
            top: rectPos.y,
            bottom: rectPos.y + rectSize.y
        };  
    return !(r2.left > r1.right || 
        r2.right < r1.left || 
        r2.top > r1.bottom ||
        r2.bottom < r1.top);
    }

    isOnOpenTile(pos: Vector, size: Vector) {
        let openTiles = this.getTiles('open');
        let result = false;
        openTiles.forEach(element => {
            if( this.circleRect(pos,size,element.pos,element.size) ){
                 result = element;
                return;
            }
        });
        return result;
    }

2.

    circleRectGetCollisionNormal(c, r) {
        if(c.pos.y <= r.pos.y - (r.size.y/2)) return new Vector(0,-1);
        //Hit was from below the brick
        if(c.pos.y >= r.pos.y + (r.size.y/2)) return new Vector(0,1);
        //Hit was from above the brick
        if(c.pos.x < r.pos.x) return new Vector(1,0);
        //Hit was on left
        if(c.pos.x > r.pos.x) return new Vector(-1,0);
        //Hit was on right
        return false;
    }

3.

    getNewMoveVector(moveVector, normalVector) {
        normalVector = this.normalize(normalVector);
        let dot = (moveVector.x * moveVector.y) + (normalVector.x * normalVector.y);
        let dotProduct = new Vector(dot, dot);
        return moveVector.sub(dotProduct.mult(normalVector).mult(new Vector(2,2)));
    }

    normalize(v) {
        let length = Math.sqrt((v.x*v.x) + (v.y*v.y));
        return new Vector(v.x/length,v.y/length);
    }

And here is main function for this

        getMoveVectorOnCollision(circle) {
        let coll = this.isOnOpenTile( circle.pos, circle.size );
        if( coll != false) {
            let vector = this.circleRectGetCollisionNormal(circle, coll);
            return this.getNewMoveVector(circle.moveVector, vector);
        } else return false;
    }

Object Vector always contain 2 values all of function (mult, sub, div, add) work like here.

sub(vector: Vector) {
    return new Vector(this.x - vector.x, this.y - vector.y);
}

Please give me advice, actual solution or tell about different way to do this reflection. I waste more than 3 days trying to solve this, I have to move on.





vendredi 25 mai 2018

C# read a class tree path in a string and access a value given an instance of that class

In C#, is it possible to read a class tree path in a string and access programmatically a value, given an instance of that class ?

For example:

public class LogGeometricModel
{
  public double SmallEndDiameter { get; set; }
  public double LargeEndDiameter { get; set; }

public class Log
{
  public Guid Id { get; set; }
  public LogGeometricModel GeometricModel { get; set; }
}

public class Solution
{
  public DateTime TimeStamp { get; set; }
  public double Price { get; set; }
  public Log RotatedLog { get; set; }
}

The strings could be something like this (a path in the class tree):

SmallEndDiameter = "Solution/RotatedLog/GeometricModel/SmallEndDiameter"

LargeEndDiameter = "Solution/RotatedLog/GeometricModel/LargeEndDiameter"

Price = "Solution/Price"

Id = "Solution/Log/Id"

By reading those strings, I would like to access the actual values of SmallEndDiameter, LargeEndDiameter, Price and Id.





Using external code in PowerShell classes

In my PowerShell script I try to access functions from external .NET DLLs. The example is about Aspose.NET which is a utility for office automation and offers access to various fileformats.

Most of the code examples are about high-level compiled .NET languages but I want to use it with PowerShell.

My observation is the following:

$AsposeDll = New-Object "System.IO.FileInfo" ".\Aspose.Pdf.dll"
Add-Type -Path $AsposeDll.FullName
[Reflection.Assembly]::LoadFile($AsposeDll.FullName)

this executes flawlessly and prints out the version of the file and I assume it is loaded by then.

If I put the following in the global space

[Aspose.Pdf.License]$Lic = New-Object "Aspose.Pdf.License"

It also executes fine. If I put the same command into a top-level function like:

function Test
{
    [Aspose.Pdf.License]$Lic = New-Object "Aspose.Pdf.License"
}
Test

It will cause no problems.

But if I write down in a class (It's PowerShell 5.0)

class PdfProvider
{
    [bool]$Loaded
    [Aspose.Pdf.License]$Lic
}

It won't execute because it tells me the type could not be found. Even commands that stand in the code before the class "should get read" are not executed, so my guess is that it screens preemptive to look if there could be an illegal execution (without loading the DLL) happening.

Is there a way you can use external code in your classes in PowerShell or is it forbidden to do so?





Override properties with reflection

I would like to override all properties with custom method calls using reflection.

The only way is by using PropertyBuilder and ILGenerator? I just found documentation about creating a new assembly and new class, but none about override a property in a defined class.

This is a sample class with int only properties.

public class Foo : MyContext
{
    public int Bar { get; set; }
    public int Baz { get; set; }
}

public class MyContext
{
    public MyContext()
    {
        var props = this.GetType().GetProperties();
        foreach(var p in props)
        {
            //...
        }
    }

    protected void CustomSet(string propName, int value)
    {
        //...
    }

    protected int CustomGet(string propName)
    {
        //...
    }
}

And that's de expected behaviour.

public class FooReflected : MyContext
{
    public int Bar 
    {
        get { return CustomGet("Bar"); }
        set { CustomSet("Bar", value); }
    }

    public int Baz
    {
        get { return CustomGet("Baz"); }
        set { CustomSet("Baz", value); }
    }
}





Method .invoke() Java Underlying Code Syntax Errors or Errors in general

I've been using reflection in Java to mark submitted Java code, and I've just noticed that when the the underlying code has an error(syntax etc), the return value will simply default to the last correct invocation of that method. I'm not really sure how to solve this. Is there any way to simply return null if the underlying method has an error?

public static Object runIt(Class[] class_holder, Object[] variable_holders, String methods) {
        try {
          Class thisClass = Class.forName("Test"); //creating a new instance of the class Test
          Object iClass = thisClass.newInstance();
          Method thisMethod = thisClass.getDeclaredMethod(methods, class_holder); //getting the specified method
          Object result = thisMethod.invoke(iClass, variable_holders); //invoking the method
          return result; 
          }
        catch (Exception e) {
          e.printStackTrace();
        }
        return null; 
      }

In this case, result just returns the previous error-free implementation of the underlying method.





jeudi 24 mai 2018

Get the line number on which the request to database ended with an error

I use this code to send sql request:

 SqlBulkCopy bulkCopy = new SqlBulkCopy(Connection);

                foreach (DataColumn column in dt.Columns)
                {
                    bulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
                }
                bulkCopy.DestinationTableName = "nsi." + classifierData.Info.TableName;
                bulkCopy.WriteToServer(dt);

and get an exception : "Received an invalid column length from the bcp client for colid". How can I find an row number with error data?

I've tried to use this, but it does'nt work (values are always the same):

 FieldInfo currentRow = typeof(SqlBulkCopy).GetField("_currentRowLength", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
                    var currentRowNumber = currentRow.GetValue(bulkCopy);

                    FieldInfo _rowsCopiedField = typeof(SqlBulkCopy).GetField("_rowsCopied", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance);
                    var currentRowN = _rowsCopiedField.GetValue(bulkCopy);





Authentication to WEB site with bar code by mobile application when browsing on mobile device?

Mobile application can scan bar code, combine user secret and send request to server to authorize access to web page, showing bar code.

How should we deal with situation when customer wants to authorize to web size via bar code on mobile device itself?

You obviously can't point camera to screen )) User can make screenshot and process it within app but that is not UX friendly.

Are there some web standards to support web page authentication workflow with preinstalled application on mobile device?





Java Reflection override method in StackPane

How can I override a method in that situation using a reflection? I want to change the return value of methodIWantToChange or override the whole method.

public class PublicClass {
    private ProtectedClass priv;

    public PublicClass() {
        priv = new ProtectedClass();
    }

    protected class ProtectedClass extends StackPane {
        private StackPane pane;

        public ProtectedClass() {
            pane = new StackPane() {
                @Override
                protected double methodIWantToChange(double arg1) {
                return 0;
            }
        }
    }
}

I have tried using Class.forName('PublicClass$ProtectedClass'), then getDeclaredField('pane'), I have set accesible and set to field new StackPane class, but all Ive got is: java.lang.IllegalArgumentException: Can not set javafx.scene.layout.StackPane field PublicClass$ProtectedClass.pane to java.lang.Class





Unable to invoke the method with variable arguments using reflection in java

When the method m is ( where m is the method to be invoked using reflection )

public static Optional<JsonNode> concat(ObjectNode entity, String separator, String fieldName1,
          String fieldName2) 

Then i am able to get the computed value ( where computed value is the value obtained using reflection )

While, when the method m is

public static Optional<JsonNode> concat(ObjectNode entity, String ...separatorAndField)

then i am able not able to get the computed value

I am invoking the method as follows:-

   computedValue = (Optional<JsonNode>) m.invoke(null, methodArgs);

Note:- methodArgs is declared as an object array.

Edit:- Added the full code

Object[] inputArgArray = null;
      String functionName = evalExp.substring(0, evalExp.indexOf('('));
      String functionArgsString = evalExp.substring(evalExp.indexOf('(') + 1, evalExp.indexOf(')'));
      if (StringUtils.isNotBlank(functionArgsString)) {
        inputArgArray = functionArgsString.split(",");
      } else {
        inputArgArray = new Object[0];
      }
      Class<?>[] paramTypes = new Class[inputArgArray.length + 1];
      Object[] methodArgs = new Object[inputArgArray.length + 1];
      paramTypes[0] = ObjectNode.class;// pass input entity as argument
      methodArgs[0] = entity;
      for (int i = 1; i < inputArgArray.length + 1; i++) {
        paramTypes[i] = String.class;
        methodArgs[i] = inputArgArray[i - 1];
      }
      Method m = EvalAttributeOperations.class.getDeclaredMethod(functionName, paramTypes);
      computedValue = (Optional<JsonNode>) m.invoke(null, methodArgs);
    } catch (NoSuchMethodException | SecurityException | IllegalAccessException
        | IllegalArgumentException | InvocationTargetException e) {
      log.error(e.getMessage(), e);
      throw new BackendException("Error occured while evaluating function", e);
    }
    return computedValue;
  }





Reflection Class Properties

I have a class and I'm trying to loop through all the objects in the class.

The code below always has a count of 0, is there something I'm missing?

Public Class SomeClass
    Public Value1 As String
    Public Value2 As String
    Public Value3 As String
    Public Value4 As String
End Class

Public Function FindClassValue() As Boolean
    Dim someobj As New SomeClass
    Dim myType As Type = someobj.GetType
    Dim properties As System.Reflection.PropertyInfo() = myType.GetProperties()
    For Each p As System.Reflection.PropertyInfo In properties
        Debug.WriteLine(p.Name)
    Next
    Return Nothing
End Function





How do I create a List

I have an ASP.NET MVC Application.

I have an example class called Example

public class Example
{
    public int Id { get; set; }
    public string Property1{ get; set; }
    public string Property2{ get; set; }
} 

I also have a test method - TestingCallFromSeparateConsoleApp that does some functionality and returns a List of Examples

public List<Example> TestingCallFromSeparateConsoleApp()
{
    List<Example> exampleList = new List<Example>();

    exampleList.Add(new Example
    {
        Id = 1,
        Property1 = "First",
        Property2 = "First",
    });

    exampleList.Add(new Example
    {
        Id = 2,
        Property1 = "Second",
        Property2 = "Second",
    });

    return exampleList;
}

I have a separate console application that is loading the MVC DLL manually.

I can call the TestingCallFromSeparateConsoleApp method and it returns the the result as type object.

I am trying to cast the result to its correct type of List of Examples.

 asm = Assembly.LoadFrom(assemblyFile);
 var smsAppInstance = asm.CreateInstance("EngineeringAssistantMVC.Controllers.TestController", false, BindingFlags.CreateInstance, null, null, null, null);

 var ExampleClass = asm.GetType("EngineeringAssistant.Controllers.Example", true);
 var ec = ExampleClass.GetType();

This gets the Example class details but I still cannot figure out how to actually instantiate and use a class of type "Example"

In my console How do I basically say:

ExampleClass newExampleClass = new ExampleClass();

So I can then say:

var result = smsAppInstance.GetType().GetMethod("TestingCallFromSeparateConsoleApp").Invoke(smsAppInstance, argumentsTopass);

Where result can be cast to List<ExampleClass>





mercredi 23 mai 2018

Get parameters from inherited classes using reflection

I've got a method, that gets parameters of service operations using reflection (based on a URL). The issue I am getting is that when the request of the operation inherits from classes, they are not getting included into the Parameter list.

The point of the below service is to dynamically get details of an WCF service/web service.

Code is below:

public ServiceDiscoveryResponse GetServiceDefinitions(ServiceDiscoveryRequest serviceDiscoveryRequest)
{
    try
    {
        var requestNamspaceList = new List<RequestNamspace>();
        var response = new List<Operation>();
        Type parameterType = null;
        var operationList = new List<string>();

        var wsdl = ServiceDiscoveryHelper.SetupWsdl(serviceDiscoveryRequest);

        ServiceDiscoveryHelper.GetNamespaceValues(wsdl, requestNamspaceList);

        var proxyAssembly = wsdl.ProxyAssembly;
        if (proxyAssembly == null) return null;

        foreach (var type in proxyAssembly.GetTypes())
        {
            if (!TreeNodeProperty.IsWebService(type)) continue;
            var proxy = ServiceDiscoveryHelper.SetupProxy(serviceDiscoveryRequest, type);

            var protocol2 = proxy as SoapHttpClientProtocol;

            if (protocol2 != null)
            {
                protocol2.CookieContainer = new CookieContainer();
                protocol2.AllowAutoRedirect = true;
            }

            foreach (var info in type.GetMethods())
            {
                if (!TreeNodeProperty.IsWebMethod(info)) continue;
                operationList.Add(info.Name);

                if (!(info is MethodInfo)) continue;
                var parameters = info.GetParameters();

                var returnType = (TypeInfo)info.ReturnType;

                var returnTypeFields = returnType.IsArray && ServiceDiscoveryHelper.IsNativeType(returnType) ? ((TypeInfo)returnType.GetElementType()).DeclaredFields : returnType.DeclaredFields;
                var parameterList = new List<Parameter>();
                var returnList = new List<Parameter>();

                if (!ServiceDiscoveryHelper.IsNativeType(returnType))
                {

                    returnTypeFields.ToList().ForEach(returnTypeField =>
                    {
                        if ((returnTypeField).FieldType.IsArray)
                        {
                            returnList.Add(new Parameter
                            {
                                DataType = !ServiceDiscoveryHelper.IsNativeType(returnTypeField.FieldType)
                                    ? returnTypeField.FieldType.BaseType.Name
                                    : returnTypeField.Name,
                                Name = returnTypeField.FieldType.Name,
                                Parameters = returnTypeField.FieldType.IsClass && !ServiceDiscoveryHelper.IsNativeType(returnTypeField.FieldType) ?
                                    ServiceDiscoveryHelper.GetParameterMembers(returnTypeField.FieldType) : new List<Parameter>(),
                            });
                        }
                        else
                        {
                            returnList.Add(new Parameter
                            {
                                Name = !ServiceDiscoveryHelper.IsNativeType(returnTypeField.FieldType)
                                    ? returnTypeField.FieldType.BaseType.Name
                                    : returnTypeField.Name,
                                DataType = returnTypeField.FieldType.Name,
                                Parameters = returnTypeField.FieldType.IsClass && !ServiceDiscoveryHelper.IsNativeType(returnTypeField.FieldType) ?
                                    ServiceDiscoveryHelper.GetParameterMembers(returnTypeField.FieldType) : new List<Parameter>(),
                            });
                        }
                    });
                }

                foreach (var parameter in parameters)
                {
                    if (!parameter.IsOut && !parameter.ParameterType.IsByRef && parameter.IsOut) continue;
                    parameterType = parameter.ParameterType;


                    if (parameterType == typeof(string))

                        if (parameterType.IsByRef)
                        {
                            parameterType = parameterType.GetElementType();
                        }
                    var val = TreeNodeProperty.CreateNewInstance(parameterType);

                    if (val != null && val.ToString() == string.Empty || (parameterType == typeof(int) && (int)val == 0))
                    {
                        if (parameterType.IsClass && !ServiceDiscoveryHelper.IsNativeType(parameterType))
                        {
                            ((TypeInfo)parameterType).DeclaredMembers.Select(item =>
                                new Parameter
                                {
                                    Name = item.Name,
                                    Parameters = null,
                                    DataType = item.DeclaringType.Name
                                });
                        }

                        parameterList.Add(new Parameter
                        {
                            DataType = parameterType.Name,
                            Name = parameter.Name,
                        });
                    }
                    else
                    {
                        var typeInfo = (TypeInfo)val.GetType();
                        var declaredFields = typeInfo.IsArray && !ServiceDiscoveryHelper.IsNativeType(typeInfo.GetElementType()) ? ((TypeInfo)typeInfo.GetElementType()).DeclaredFields : typeInfo.DeclaredFields;

                        var baseType = typeInfo.BaseType;

                        if (declaredFields != null && declaredFields.Any())
                        {
                            declaredFields.ToList().ForEach(item =>
                            {
                                parameterList.Add(new Parameter 
                                {
                                    DataType = item.FieldType.Name,
                                    Name = item.Name,
                                    Parameters = item.FieldType.IsClass && !ServiceDiscoveryHelper.IsNativeType(item.FieldType) ? 
                                        ServiceDiscoveryHelper.GetParameterMembers(item.FieldType) : new List<Parameter>(),
                                });
                            });
                        }

                        if (!parameterType.IsClass && ServiceDiscoveryHelper.IsNativeType(parameterType) && ServiceDiscoveryHelper.IsNativeType(parameterType.BaseType))
                        {
                            if (baseType != null && baseType != typeof(string) && baseType != typeof(Array))
                            {
                                ((TypeInfo)baseType).DeclaredFields.ToList().ForEach(item =>
                                {
                                    parameterList.Add(new Parameter
                                    {
                                        DataType = item.FieldType.Name,
                                        Name = item.Name,
                                    });
                                });
                            }

                            declaredFields.ToList().ForEach(item =>
                            {
                                var fieldInfos = ((TypeInfo)item.FieldType).DeclaredFields;

                                var enumList = new List<string>();
                                fieldInfos.ToList().ForEach(enumValue => { enumList.Add(enumValue.Name); });

                                parameterList.Add(new Parameter
                                {
                                    DataType = item.FieldType.Name,
                                    Parameters = item.FieldType.IsClass && !ServiceDiscoveryHelper.IsNativeType(item.FieldType) ? ServiceDiscoveryHelper.GetParameterMembers(item.FieldType) : new List<Parameter>(),
                                    Name = item.Name,
                                    EnumValueList = item.FieldType.IsEnum ? enumList : new List<string>()
                                });
                            });
                        }
                    }
                }
                var namespaceValue = requestNamspaceList.ToList().Where(namespaceItem => namespaceItem.Name == TreeNodeProperty.CreateNewInstance(parameterType).ToString());
                ServiceDiscoveryHelper.CreateResponse(response, info, parameterType, namespaceValue, parameterList, returnType, returnList, serviceDiscoveryRequest.EndpointUrl);
            }
            return new ServiceDiscoveryResponse { Operation = response };
        }
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception);
        throw;
    }
    return null;
}





How to Dynamically call and setter and getter methods using Reflection class?

Say I have class AccountPojo and GetAccountPojo with its stter and getter methods as below.

public class AccountPojo{

    private String dataList;
    private String dataSet;

    public String getDataList() {
        return dataList;
    }

    public void setDataList(String dataList) {
        this.dataList = dataList;
    }

    public String getDataSet() {
        return dataSet;
    }

    public void setDataSet(String dataSet) {
        this.dataSet = dataSet;
    }
} 

public class GetAccountsPojo{

    private String accountId;
    private int noOfAccounts;

    public String getAccountId() {
        return accountId;
    }

    public void setAccountId(String accountId) {
        this.accountId = accountId;
    }

    public int getNoOfAccounts() {
        return noOfAccounts;
    }

    public void setNoOfAccounts(int noOfAccounts) {
        this.noOfAccounts = noOfAccounts;
    }
}

Now I have class Test.java as below

public Class Test{

 p.s.v.m{

  Class cls = Class.forName("com.org.temp."+ClassName);// ClassName(AccountPojo/GetAccountPojo) here i know already which class is getting called.

  Object clsInstance = (Object) cls.newInstance();

  System.out.println("The cls is==" + cls+" and classInstance is=="+clsInstance);

// Here i want to access getter and setter methods of AccountPojo and GetAcoountPojo dynamically , no hard coding


}   





C# Get full name of data type

I am getting a datatype in code as "int32" however, what I actually need is the full name, "integer". Is this possible?

Here's the code for the data type:

public static List<Parameter> GetParameterMembers(Type parameterType)
        {
            var parameterList = new List<Parameter>();

            var returnTypeFields = parameterType.IsArray ? ((TypeInfo)parameterType.GetElementType()).DeclaredFields : ((TypeInfo)parameterType).DeclaredFields;

            returnTypeFields.ToList().ForEach(item =>
            {
                if (item.MemberType != MemberTypes.Field) return;

                parameterList.Add(new Parameter
                {
                    Name = item.Name,
                    Parameters = item.FieldType.IsClass && !IsNativeType(((FieldInfo)item).FieldType) ? GetParameterMembers(((FieldInfo)item).FieldType) : new List<Parameter>(),
                    DataType = item.FieldType.Name
                });
            });

            return parameterList;
        }





How to check multiple attributes having unique combination within List where attribute names are available as separate collection. [C#]

I have the scenario where I have a List of selected attributes in string format. Based on that list I want to perform an operation on actual object collection to check whether given properties having unique value combination within that list.

Example - Here Name and Type are the selected attributes (given in selectedProductAttributes list) we want to check uniqueness for this attributes with products collection. We might use reflection to retrieve actual properties but I am not sure how to achieve this. Any help appreciated.

public class Product
{
    public string Name { get; set; }
    public string Type { get; set; }
    public string Price { get; set; }
}

private List<string> selectedProductAttributes = new List<string> {"Name", "Type"};

private List<Product> products = new List<Product>
    {
        new Product {Name= "a", Type="t1", Price=10},
        new Product {Name= "a", Type="t1", Price=20},
        new Product {Name= "b", Type="t2", Price=30}
    };





mardi 22 mai 2018

Filtering list of objects in datagridview based on cell value

I am currently unsure on the best way of going about getting a filter to work right on a datagridview that has its datasource set to a list of objects.

So given an object of:

    public class DepositAccountBill
    {
        #region Properties
        public int AccountBillID { get; set; }
        public int AccountID { get; set; }
        public string AccountNumber { get; set; }
        public string ControlNumber { get; set; }
        public DateTime BillDate { get; set; }
        public decimal DepositAmount { get; set; }
}

I have a datagridview table that looks roughly like this:

Account Number  |  Control Number  | Bill Date  |   Deposit Amount 
123456            | AJA1234367     | 5/21/2018 | 12.99 
123456            | PSA1234367     | 5/21/2018 | 5.77 
567332                | HBA1234367     | 5/21/2018 | 1255.99 
769843                | AJA1234367     | 5/21/2018  | 12.99 

So when clicking on a cell. Lets say the first cell on the first column. If I click a button that says filter I need to display the datagridview table with only rows that have the same Account number. In this case, it would be rows 1 and 2. In order for me to do this, I have to access the object that the datagridview table is populated with DepositAccountBill. So what I need to do is look and at the column I'm looking at has the selected cell's value.

So in my method I have tried thus far with no results:

    var collection = (List<DepositAccountBill>)dataGridView1.DataSource;
var filterList = collection.Where ( q => (collection.Select(r => GetPropValue(r, dataGridView1.Columns[clickedCell.ColumnIndex].DataPropertyName))) == (clickedCell.Value);

dataGridView1.DataSource = filterList.ToList();

    public object GetPropValue(object obj, string propName)
    {
        return obj.GetType().GetProperty(propName).GetValue(obj, null);
    }

I don't know is SELECT is the right LINQ method to use here or if this is even possible. I want to use WHERE because it only grabs the list of objects that match the condition. Something like this: var filterList = collection.Where(r => r.AccountNumber == clickedCell.Value);

Only problem is the r.AccountNumber is dependant on the data property of the selected column. The program does not know what the data property is based on a click event on the selected cell. This is why I think reflection might be necessary.





C# parsing to object definition in runtime

This is a somewhat hard understand question, maybe I'm thinking also wrong, don't downvote me for making this question. If you want me to delete this, just comment.

I'm reading some CSV's and trying to convert them to C# objects.

The objects I'm converting need to implement IResult

interface IResult
{
    String TestName { get; set; }
}

class Result : DynamicObject, IResult
{
    public string TestName { get; set; }

}

The Result class has several properties containing results, could be all Objects. Each tested item has one result with it's Properties, which is used to generate the CSV.

Now I need to do the opposite, read the CSV's and convert back to objects. but I want to do it so that I can use one method to load all kinds of items (with different IResult implementations).

So I thought of ExpandoObject or DynamicObject so that I could create the properties and set the values in Runtime.

Is this possible?





What to use instead of `defineClass` in Java10?

I use method defineClass() from the ClassLoader to define a class from the byte array. I fetch this method using reflection:

ClassLoader.class.getDeclaredMethod(
    "defineClass", String.class, byte[].class, int.class, int.class);

Java10 complains about reflective usage of defineClass.

What should I use instead?





CDI bean is not injected but can be looked up

So, I wrote an extension which registers bean I am trying to create. The bean gets scanned by CDI and I can get it using:

MyInterface myInterface = CDI.current().select(MyInterface.class).get();

And I can then access myInterface.myMethod();

However, when I try to inject my bean using:

@Inject
@MyBean
MyInterface myInterface;

it is not injected and is null.

What I want to achieve is that I specify interface, which defines some methods,then my code generates instance of this interface and returns proxy of interface type:

// defined interface
@RegisterAsMyBean
interface MyInterface {
    void myMethod();
}

// usage in code:
@Inject
@MyBean
MyInterface myInterface;

I declared my bean like this:

public class MyExtension implements Extension {
    public void register(@Observes @WithAnnotations(RegisterAsMyBean.class) ProcessAnnotatedType<?> aType) {
        Class<?> typeDef = aType.getAnnotatedType().getJavaClass();

        if(typeDef.isInterface()) {
            proxyTypes.add(typeDef);
            aType.veto();
        }
    }
}

public class BeanCreator implements Bean<Object> {
    @Override
    public Object create(CreationalContext<Object> creationalContext) {
        // my instance building logic
    }
    // ... other overriden methods
}

Also in META-INF/services/javax.enterprise.inject.spi.Extension I put reference to MyExtension





Alternative to passing values as arguments in java

In my project, I am using reflections to invoke a method. The invoked method requires certain values that I am now passing as arguments. But my use case doesn't allow this. Are there any efficient alternatives for this approach?





java.lang.reflect.Proxy and java.lang.reflect.InvocationHandler

What is the purpose of java.lang.reflect.Proxy and java.lang.reflect.InvocationHandler? when we need to create and use these on our application?





lundi 21 mai 2018

Set Object Property of Object Property by Reflection

I used this SO Question to retrieve a property of an object using reflection. The property I retrieved is another object that has a property called Value that I need to access. All of the potential objects that I retrieve using reflection derive from the same class EntityField and therefore all have a Value property. I saw this SO question that hinted at how I might be able to access the Value property, but I couldn't quite put together the correct code. How can I access the Value property on an object retrieved by reflection?

Main

private static void SetValues(JObject obj, EntityBase entity)
{
    // entity.GetType().GetProperty("Property") returns an EntityField Object
    // I need to set EntityField.Value = obj["Value"] 
    // Current code sets EntityField = obj["Value"] which throws an error
    entity.GetType().GetProperty("Property").SetValue(entity, obj["Value"], null);
}

EntityField

public class EntityField<T> : EntityFieldBase
{
    private Field _Field;
    private T _Value;

    public EntityField(Field field, T value){
        this._Field = field;
        this._Value = value;
    }

    public Field Field
    {
        get
        {
            return this._Field;
        }
        set
        {
            if (this._Field != value)
            {
                this._Field = value;
            }
        }
    }

    public T Value
    {
        get
        {
            return this._Value;
        }
        set
        {
            if (!EqualityComparer<T>.Default.Equals(this._Value, value))
            {
                this._Value = value;
                this._IsDirty = true;
            }
        }
    }
}





Dynamically get property from select function using variable

I'm trying to dynamically get all the values of a specific property from all class instances. I've managed to do it with one property

public class fighter
    {
        public string Name { get; set; }

        public double Height { get; set; }
    }

fighter[] roster[5] = new fighter();

string namearray = roster.Select(x => x.Name).ToArray();
int weightarray = roster.Select(x => x.Weight).ToArray();

However I want to reference the property with a variable and put it in a loop so I don't need a select function for every property. Is there anyway to do this, or any other method to get all values of a property from all objects where this could work?





dimanche 20 mai 2018

PropertyCellValueFactory with array values in Java

I am using PropertyValueFactory to get fields from a class that contains a field that is an array. PropertyValueFactory uses reflection in order to get the fields, like so:

IMAGE 1

However, the issue is my values field is an array. I was wondering about how to get the values of the array since it is being grabbed through reflection. Here is the code around where I am trying to access the array value, for more clarity:

IMAGE 2

values is my array in question here. I tried values[0] But it did not work.





Using reflection to obtain list of DisplayNames from Class properties

I'm trying to obtain a List of DisplayNames out of a class that has most of its properties booleans:

public class AccessoriesModel
{
    public int Id { get; set; }

    [Display(Name = "Acc 1")]
    public bool Accessory1 { get; set; }

    [Display(Name = "Acc 2")]
    public bool Accessory2 { get; set; }

    [Display(Name = "Acc 3")]
    public bool Accessory3 { get; set; }

    [Display(Name = "Acc 4")]
    public bool Accessory4 { get; set; }
}

by iterating over the PropertyInfos of the class and seeing which values are true, as below:

    List<string> list = new List<string>();
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
        {
            if (propertyInfo.PropertyType == typeof(bool))
            {
                bool value = (bool)propertyInfo.GetValue(data, null);

                if (value)
                {
                   //add the DisplayName of the item who's value is true to the list named "list"

                   //the following line works fine, but I cannot iterate over the list of items to get dinamicaly build the list
                   string displayName = GetPropertyDisplayName<AccessoriesModel>(i => i.AirConditioning);

                   list.add(displayName)

                }
            }
        }

where GetPropertyDisplayName is a solution suggested by a fellow member in his answer for another question for retrieving the DisplayName of a property: https://stackoverflow.com/a/10048758

The end result that I'm looking for is a list of strings (display names) that will be formed only by the properties that are true.

Thank you, in advance, for your help on this.





samedi 19 mai 2018

How to use reflection to get a method with a ref keyword?

Yeah so I set up a little TestClass to figure out what GetMethod would work to actually find the method Test(ref int i). But so far nothing worked.

[Button(nameof(Method))]
public bool whatever;

private void Test(ref int i)
{
    Debug.Log("Works");
}

private void Method()
{
    Type[] types = { typeof(int) };
    MethodInfo methodInfo = GetType().GetMethod(nameof(Test),
        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
        null, types, null);
    Debug.Log(methodInfo);
}

What am I supposed to do? I couldn't find anything on the web so far (for GetMethod specifically)





Getting a runtimeFieldHandle from an IntPtr

You can easily go from a runtimeFieldHandle to an IntPtr. But how could you get back, e.g. given an IntPtr get a runtimeFieldHandle? I've tried modifying the field directly using an expression tree, but I can't get the fieldinfo for the field which holds the value in a runtimeFieldHandle (maybe it's not called "m_value"?)

General problem is that I want to get a FieldInfo from an IntPtr.

FieldInfo pm_ptr = typeof(RuntimeFieldHandle).GetField("m_value", (BindingFlags)int.MaxValue);

ParameterExpression pParamHandle = Expression.Parameter(typeof(RuntimeFieldHandle), "pHandle");
ParameterExpression pParamPtr = Expression.Parameter(typeof(IntPtr), "ptr");
Expression<Action<RuntimeFieldHandle, IntPtr>> pexChange = (Expression<Action<RuntimeFieldHandle, IntPtr>>)Expression.Lambda(Expression.Block(typeof(void), Expression.Assign(Expression.Field(pParamHandle, pm_ptr), pParamPtr)), pParamHandle, pParamPtr);
    Action<RuntimeFieldHandle, IntPtr> pChange = pexChange.Compile();





Java, Load classes from JAR to use them later

I have a problem loading class from JAR file.

I can load them with URLClassLoader using a JarFile etc etc like in this answer; but if later in code I try to instantiate them with reflection:

Object obj = Class.forName(className).newInstance()

I get a ClassNotFoundException. Can I dinamically load a class to use them later, when I need them, just like classes in ClassPath? Thank you!





external changing implementation of class

Is there a way to change implementation of given class from outside? For example, I have the following implementation:

 public partial class Test
{
    public Interface1 Field = new Class1();
}
public interface Interface1
{
    //implementation    
}
public class Class1 : Interface1
{
    //implementation
}

I would like to define another class:

public class Class2 : Interface1
{
    //implementation
}

and change Test.Field to be object of Class2 class. I cannot modify implementation of Test class. I can only add another file with its partial implementation. I cannot also use any dependency injection libraries.





vendredi 18 mai 2018

Possible create named tuple type using reflection?

I can create a normal tuple type with Tuple.Create or typeof(Tuple<,>).MakeGenericType etc, but how can I make a named tuple? With other property names than Item1, Item2 etc, using reflection in runtime.





c++ reflection: library for calling methods and reading properties

I need a c++ library that make it possible to do such things:

obj = objects.get(id)  // id is some integer value
callmethod(obj, "methodName", pass args)
value = read_property(obj, "propertyName")
set_property(obj, "propertyName", value)
list_of_properties(obj)
list_of_methods(obj)
obj2 = create_object_by_name("name", args)
objects.push(newid, obj2)





How to get a reference to the `Class

For instance, I can have

Class c = Map.class;

But what if I need c to refer to the class Map<String, ValueClass>?

I want to do something which expresses

Class c = (Map<String, ValueClass>).class;

My use case is that I need to do this so that I can pass c to getConstructor





Passing Type to Generic Method C#

I have a method that accepts a generic TViewModel class like so:

Page GetPage<TViewModel>() where TViewModel : class, IViewModelBase;

In my class I get the type of the item that the user selected (from a navigation list) like so:

var viewModel = item.TargetType;

This type will always be a view model that inherits from IViewModelBase

When I call this next line I need to be able to pass in the viewModel type. Im trying to do

var page = Navigator.GetPage<viewModel>();

But I get the following error:

viewModel is a variable but is being used like a type.

Is there anyway I can pass the viewModel type to the GetPage Method?

If not the only way I can see to do this is to have a switch statement that checks the viewModel type name and hard code the correct TViewModel into the GetPage call.

For example something like this:

switch (viewModel.Name)
{
    case "TaskViewModel":
            page = Navigator.GetPage<TaskViewModel>();
       break;
    case "TaskEditViewModel":
            page = Navigator.GetPage<TaskEditViewModel>();
       break;
}





casting reflected value to type in golang?

Is it possible to dynamically cast a reflect.Value back to an arbitrary type?

https://blog.golang.org/laws-of-reflection seems to suggest not (as go is statically typed). That pretty much seems to limit the uses of reflection as far as I can see, as you always need to be aware of the type you are working with.

Here's an example of what I mean:

package main

import (
    "fmt"
    "reflect"
)

type A struct {
    Name string
}

func main() {

    a := &A{Name: "Dave"}
    fmt.Println(a)

    //create a nil pointer of an arbitrary type
    dynamicType := reflect.TypeOf(a)
    dynamicNil := reflect.Zero(dynamicType).Interface()
    a = dynamicNil //is it possible to do this without explicitly casting to A (ie. avoiding `a = dynamicNil.(*A)`)
    fmt.Println(a)
}





Calling a method of generic object without knowing its Type and passing a predicate parameter of this type to this method

Im using reflection and im looping through properties of my entity framework context and i want to call "Where" method on some of those properties. Those properties are DbSet.

var contextPropertyInfo = 
  context.GetType().GetProperties().Where(p=> p.Name.Contains("SewingCards")).ToList();

foreach (var info in contextPropertyInfo)
{
  var sewingCardDbSet = info.GetValue(context);
  var dbSetWhereMethod = sewingCardDbSet.GetType().GetMethod("Where");
  var genericTypes = sewingCardDbSet.GetType().GetGenericArguments().First();                      
}

Im getting the type of T by calling

var genericType = sewingCardDbSet.GetType().GetGenericArguments().First();

now i want to call this DbSet.Where method with

var dbSetWhereMethod = sewingCardDbSet.GetType().GetMethod("Where");
dbSetWhereMethod.Invoke(context, parameters);

Calling this method wont work until in parameters i will form a predicate that is based on "genericType" and i dont really know what to do next. How can i call this method with reflection?





jeudi 17 mai 2018

C#: Pass reflection type into class constructor

I've got a generic method that takes an arbitrary JObject (from JSON.net) and converts it into the generically typed object.

So, let's simplify my conversion method to look like the following:

private async Task<T> ConvertToObject(JObject obj) {
    //Lots of other stuff yielding in the creation of newObj
    var result = newObj.ToObject<T>();
    return result;
}

Now this method works fine as-is, but I want to modify the method so I can properly do the same for complex properties within the generic object that aren't available in my JObject (e.g. I have to look them up separately, do this same conversion and apply to this object result).

My approach so far is to loop through all the properties, identify the complex types, perform the lookup to retrieve their values from my data store, then execute the above against them (potentially recursively if they too have any complex objects), then write that value back out to this complex property, repeat for any others and then as before, return that result.

I'm retrieving the properties via Reflection:

var properties = result.GetType().GetProperties();
foreach (var property in properties) {
  if (IsSimple(property.PropertyType)
    continue;

  //Do external lookup

  var convertedValue = new ConversionTool<>().Lookup(query);
}

Now, that last line is where I'm having my problem. I'm expected to pass a class name into this, not just a type, but I only know the type at runtime per the reflection methods above. I found a post at http://www.paulbatum.com/2008/08/less-fragile-way-to-invoke-generic.html detailing how to make this work if I were simply passing the generic type into a method and he explains the issue with using Activator.CreateInstance in the comments, but it seems like I know the type I'd want to put there - I just don't know it until it runs (and I retrieve it via reflection).

This seems like an issue that ORMs would run into when it comes to populating complex properties of their entities, but I'm having a difficult time finding how they're doing this.

Given that the caller of this method is aware at runtime what the intended type is, how might I go about passing that type into the generic class constructor so I might call it recursively for each complex member of a given type?





Retrieve original object from ObjectContent in DelegatingHandler

I have the following code which works for paging.

I want to pull the method SetupPagingLinks into a handler which is executed after the controller returns it's result:

Controller and paging info:

[Route("v1/endpoint")]
[HttpGet]
public async Task<IHttpActionResult> GetConnectionsAsync([FromUri]int page = 1,
    [FromUri]int pageSize = 20, [FromUri]string orderBy = nameof(ConsumerConnectionGetDto), [FromUri]bool ascending = true)
{
    var id = await AuthorizationService.GetAzureObjectIdentifierAsync();

    PagedResults result = await ConnectionService.GetPagedResultAsync(id, page, pageSize, orderBy, ascending);

    connections.PagingMetaData.PageLinkInfo = SetupPagingLinks(Url, page, pageSize, result.PagingMetaData.TotalNumberOfPages);

    return Content(HttpStatusCode.OK, result);
}

private PageLinkInfo SetupPagingLinks(UrlHelper url, int page, int pageSize, int totalPages)
{
    PageLinkInfo linkInfo = new PageLinkInfo(); 

    var qs = Url.Request.RequestUri.ParseQueryString();

    //Set default params if missing
    if (qs["page"] == null)
    {
        qs.Set("page", page.ToString());
    }
    if (qs["pageSize"] == null)
    {
        qs.Set("pageSize", pageSize.ToString());
    }

    var baseUrl = Url.Request.RequestUri.GetLeftPart(UriPartial.Path);
    linkInfo.CurrentPageUrl = $"{baseUrl}?{qs}";

    //First page
    qs.Set("page", "1");
    linkInfo.FirstPageUrl = $"{baseUrl}?{qs}";

    //Last page
    qs.Set("page", $"{totalPages}");
    linkInfo.LastPageUrl = $"{baseUrl}?{qs}";

    //Next page
    if (page + 1 <= totalPages)
    {
        qs.Set("page", $"{page + 1}");
        linkInfo.NextPageUrl = $"{baseUrl}?{qs}";
    }
    else
    {
        linkInfo.NextPageUrl = null;
    }

    //Previous page
    if (page - 1 >= 1)
    {
        qs.Set("page", $"{page - 1}");
        linkInfo.PreviousPageUrl = $"{baseUrl}?{qs}";
    }
    else
    {
        linkInfo.PreviousPageUrl = null;
    }

    return linkInfo;
}

Classes:

public class PagedResults<T>
{
    public PagingMetaData PagingMetaData { get; set; }

    public IEnumerable<T> Results { get; set; }
}

public class PagingMetaData
{
    public int CurrentPageNumber { get; set; }

    public int PageSize { get; set; }

    public int TotalNumberOfPages { get; set; }

    public int TotalNumberOfRecords { get; set; }

    public PageLinkInfo PageLinkInfo { get; set; }
}

public class PageLinkInfo
{
    public string NextPageUrl { get; set; }
    public string PreviousPageUrl { get; set; }
    public string FirstPageUrl { get; set; }
    public string LastPageUrl { get; set; }
    public string CurrentPageUrl { get; set; }
}

What I'd like to do is the following:

public class PagingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {

        var response = await base.SendAsync(request, cancellationToken);

        if (response.Content != null)
        {
            // If (response.Content.getType() == PagedResults)
            // PagedResult<object> myResult =  response.Content as PagedResult<object>;
            // myResult.PagingMetaData.PageLinkInfo = SetupPagingLinks(request, myResult);
        }

        return response;
    }
}

The problem I'm currently facing is that I can't seem to extract the PagedResults object from the response.Content. I can see in the debugger that my PagedResults object is inside response.Content.Value





Create an object of the class I'm in

I have a bunch of classes let's call them Foo1, Foo2, Foo3. Each of them shares a parent SuperFoo and has a similar main function. Each creates an instance of the class and then calls bar() on it.

Essentially, what I have now is:

class Foo1 extends SuperFoo {
  public static void main(String[] args) {
    new Foo1().bar();
  }
}

class Foo2 extends SuperFoo {
  public static void main(String[] args) {
    new Foo2().bar();
  }
}

class Foo3 extends SuperFoo {
  public static void main(String[] args) {
    new Foo3().bar();
  }
}

Basically, this means I'm writing the same function over and over again.

Could I just have a main in SuperFoo that is inherited and uses reflection to create an instance of the subclass? Or is there some other way to merge these into a single function?





Why the c# Activator can instanciate a struct without providing constructor parameters [duplicate]

This question already has an answer here:

Let's say I have such struct:

public struct Dog
{
    public Dog(string name)
    {
        Name = name;
    }
    public string Name { get; set; }
}

Why does the following code not crash ?

var dog = Activator.CreateInstance<Dog>();

If Dog was a class there would be a runtime error. But with a struct the instance is created with a null Name.





JAVA - Difference between Class class and *.class files?

There's something I don't understand between *.class files and Class class API. Let's me explain :

I have a file A.java representing a java class :

public class A { ... }

Class<?> clazz = A.class;

When I compile A.java, I get a A.class file (the byte code).

Is there any relation between the A.class file (bytecode) and clazz which represents the instance class (A.class) ? Are they the same thing ?

Thank you





How to find a Type that inherits from some BaseClass

I have a class

public class BaseClass
{

}

I have a child class

public class ChildClass : BaseClass
{

}

I want to know what classes/types inherit from BaseClass (find ChildClass for example). I know that i have to use assemble and reflection but don't know how/which function to use.

Edit: ok maybe now you'll get it





Get fields of Delegate class reflection

I have class

public class Car {

    private String name;
    private int year;

    public Car(String name, int year) {
        this.name = name;
        this.year = year;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }
}

Person Class

public class Person {

    private String name;
    private int age;
    private boolean adult;

    private Car car;

    public Person(String name, int age, final Car car) {
        this.name = name;
        this.age = age;
        this.car = car;
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public boolean isAdult() {
        return adult;
    }

    public void setAdult(boolean adult) {
        this.adult = adult;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", adult=" + adult +
                '}';
    }
}

I have to get fields using reflection and set / get values dynamically.

I am keeping them in a map

Map<String, Field> map = new HashMap<>();

        for (Field field : Person.class.getDeclaredFields()) {
            field.setAccessible(true);
            map.put(field.getName(), field);
        }

        System.out.println(map);

I have the map now with all the fields later on I can get/set any attribute

What I cannot get it how do I store Car in the map like

"car.name" , <FIELD> 
"car.age" , <FIELD>

later on I can get from map like mapp.get("car.name", person) that would return the car name





C# Reflection get all classes from different assembly that extends specific class

Get Properties of a concrete class that extends from a specific class and has a specific method that takes a specific param that extends again from a specific class using reflection in C#.





Nullify Generic ObservableCollection inside an object Reflection C#

How to find all the Generic lists of specialized type and set them to null?





Turning Bluetooth Tethering On in Xamarin.Android

I'm currently trying to add some Bluetooth functionality to my app. I want to be able to change the Bluetooth Tethering on or off, as well as check its status.

I found the Java code on StackOverflow: How to check Bluetooth tethering status programmatically in Android

I have translated it into C#, but I don't seem to be able to get any result.

Regardless of the tethering setting, it always shows the toast with "Tethering:false", and the setBluetoothTethering doesn't change anything.

Any idea what I'm missing?

Here's my code:

[...]
        try
        {
            Class classBluetoothPan = Class.ForName("android.bluetooth.BluetoothPan");

            Method mBTPanConnect = classBluetoothPan.GetDeclaredMethod("connect", Class.FromType(typeof(BluetoothDevice)));

            Constructor BTPanCtor = classBluetoothPan.GetDeclaredConstructor(Class.FromType(typeof(Context)), Class.FromType(typeof(IBluetoothProfileServiceListener)));

            BTPanCtor.Accessible = true;

            Java.Lang.Object BTSrvInstance = BTPanCtor.NewInstance(Activity, new BTPanServiceListener(Activity));

            Method isTetheringOnMethod = classBluetoothPan.GetDeclaredMethod("isTetheringOn", null);

            var isTetheringOn = isTetheringOnMethod.Invoke(BTSrvInstance);

            Toast.MakeText(Activity, "Tethering:" + isTetheringOn, ToastLength.Short).Show();

            Method setBluetoothTetheringMethod = classBluetoothPan.GetDeclaredMethod("setBluetoothTethering", new Class[1] { Class.FromType(typeof(bool)) });

            setBluetoothTetheringMethod.Invoke(BTSrvInstance, true);

            // tether = !tether;

        }
        catch (ClassNotFoundException e)
        {
            e.PrintStackTrace();
        }
        catch (Java.Lang.Exception e)
        {
            e.PrintStackTrace();
        }
[...]


public class BTPanServiceListener : Java.Lang.Object, IBluetoothProfileServiceListener
{

    private Activity _activity;

    public BTPanServiceListener(Activity activity)
    {
        _activity = activity;
    }

    public void OnServiceConnected([GeneratedEnum] ProfileType profile, IBluetoothProfile proxy)
    {
        // throw new NotImplementedException();
    }

    public void OnServiceDisconnected([GeneratedEnum] ProfileType profile)
    {
        // throw new NotImplementedException();
    }
}





mercredi 16 mai 2018

How to use java reflection to return a Collection that contains something other then Objects

So my problem is that im currently trying to use java's reflection to traverse a tree like structure. The problem is the only thing i know about each structure is that it can contain one of three things. Strings (the leaf's) Other Objects, Or Lists of other objects. Using reflection i want to do a DFS of the tree until i find a node that im looking for. My problem seems to be that when i use reflection to get a field that happens to be of type List i get back List and i am unable to down cast the the correct type. here are some samples i have tried.

Using Fields

Object returnObj = new Object();
Field field = object.getClass().getDeclaredField(fieldClassName);   
field.setAccessible(true);
List<DistributionPartnerRoleType> test = (List<DistributionPartnerRoleType>) field.get(object);

And using Methods

    String methodName = "get" + Character.toUpperCase(fieldClassName.charAt(0)) + fieldClassName.substring(1);
    Method[] getters = object.getClass().getMethods();
    Method getter = getMethod(getters, methodName);
    Type returnType = getter.getGenericReturnType();
    if(returnType instanceof ParameterizedType){
        Type actualType = ((ParameterizedType) returnType).getActualTypeArguments()[0];
        Class actualClass = (Class) actualType;
        returnObj = getter.invoke(object, null);
        List<Object> newList = new ArrayList<Object>();
        for(Object obj : (List<Object>)returnObj){
              newList.add(actualClass.cast(obj));
        }
        returnObj = newList;
    }

Im aware that the problem is that the objects are truly of type Object but the function and fields are explicitly of type List as declared in the code

protected List<DistributionPartnerRoleType> distributionPartnerRole;

public List<DistributionPartnerRoleType> getDistributionPartnerRole() {
    if (distributionPartnerRole == null) {
        distributionPartnerRole = new ArrayList<DistributionPartnerRoleType>();
    }
    return this.distributionPartnerRole;
}

If anyone knows of a solution for this problem that would be great, Or if i need to go about a different method other then reflection.

edit - code block





C# - Why is Delegate created with `Delegate.CreateDelegate` faster than lambda and method delegates?

All this time I've been reading about reflection, everybody is always saying: "reflection is slow", "reflection is slow".

Now I decided to test how slow, and for my surprise, a delegate created with reflection is actually about twice as fast as a delegate created with lambda, and, also surprisingly, about four times faster than delegates taking declared methods.

See the code

This is a custom class whose property get method will be used in the delegates:

#class to test
class SomeClass
{
    public SomeClass A { get; set; } //property to be gotten
    public static SomeClass GetA(SomeClass c) { return c.A; } //declared getter method
}

There are the three delegates I tested:

PropertyInfo AProp = typeof(SomeClass).GetProperty("A");

//1 - Created with reflection
Func<SomeClass, SomeClass> Getter = (Func<SomeClass, SomeClass>)Delegate.CreateDelegate(typeof(Func<SomeClass, SomeClass>), null, AProp.GetGetMethod());

//2 - Created with a lambda expression
Func<SomeClass, SomeClass> Getter2 = c => c.A;

//3 - Created from a declared method
Func<SomeClass, SomeClass> Getter3 = SomeClass.GetA;

These are the tests:

SomeClass C = new SomeClass();
C.A = new SomeClass(); //same times wheter A is set or null
Stopwatch w;

w = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
    SomeClass b = Getter(C);
}
w.Stop();
Console.WriteLine(w.Elapsed);

w = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
    SomeClass b = Getter2(C);
}
w.Stop();
Console.WriteLine(w.Elapsed);

w = Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++)
{
    SomeClass b = Getter3(C);
}
w.Stop();
Console.WriteLine(w.Elapsed);

And the results:

enter image description here





C# How can I generate a constructor dependency graph for a class or list of classes?

I would like to generate a text output list that traverses my constructor dependencies for a class or list of classes. I assume I would use reflection in some way to do this? And have protection against circular dependencies.

https://stackoverflow.com/a/29704045/254257 This seems to be what I would want, but they provided no code. That question is on a similar track, but they just assume you have start with a dictionary with your dependencies already outlined as strings. So I guess how would I get that to start with.

Say I have the following:

public class UserService(IGroupService groupService, ILoggingService loggingService)
public class GroupService(IUserService userService, IRoleService roleService, ILoggingService loggingService)
public class RoleService(ILoggingService loggingService)

I would want some code to output something like this:

UserService

----GroupService

--------UserService CIRCULAR DEPENDENCY (stops going any deeper)

--------RoleService

------------LoggingService

--------LoggingService

----LoggingService

If I wanted to check dependencies on only the UserService, with the actual concrete implementation of the interfaces.

I know I can var type = typeof(UserService) as a starting point, but I've only ever worked with properties before so not sure what to do next.

I would imagine I would somehow need to get the constructor parameters, the types of those, then get the actual implementations and repeat, somehow also making sure I don't get stuck in a loop if I have any circular dependencies. Not sure how to do any of that so help would be appreciated.





Reflection PropertyInfo SetValue C#

Im using reflection to get a property. I then want to change the value of this property.

For this example I want to get the property of type Task and overwrite that property value with a different Task object. This is my code so far. It's currently getting the Task PropertyInfo but I don't know what to put in the 1st parameter of the SetValue call.

var viewBindingProperty = viewBinding.GetType().GetProperty(typeof(Task).Name);

viewBindingProperty.SetValue(??, pageBinding.Task);

I need to overwrite the value of the Task Property value in the viewBindingProperty with pageBinding.Task





Value class to keep object type for later casting?

I am working on a project that uses ontology to launch algorithm. In other words, the parameters/return value of an algorithm are retrieved from a semantic database so that they can be launched using SPARQL queries.

Let's say I want to get the result of such an algorithm after its execution, which has a specific type, but I have to store it in a very generic way. I would do Object result = myAlgorithm(param1, param2, ...);. This does not allow me to store the type of the result for later casting though. I am thinking of a solution, but I am not sure how legitimate it is in Java:

public class Value {
   Object o;
   Class<?> type;

   public Value(Object o, Class<?> type) {
       this.o = o;
       this.type = type;
   }

   Class<?> getType() { return type; }

   Object getO() { return o; } 
}

The return type of the algorithm is also stored in the database. I know this sounds a bit convoluted, but I hope you understand what I want to do.





mardi 15 mai 2018

Let the user design forms

Is there a way to instantiate the VisualStudio forms toolbox while an application is already deployed? (but with the developer package installed on the PC)

The project itself should be up and running, and I know that code can be compiled by runtime into DLLs.

My goal is, that a user for the product can natively create forms at his own behalf and maybe save them down, in markup or even better compiled to have them available at the next start.

To have them integrated in the best possible manner, my wish would be that the solution shouldn't rely on a third party forms (e-forms) package, but with the help of the in .NET integrated features.





Getting Inner Class Data using reflection

I have One Inner Class and One Outer Class. Using Java Reflection I want to access the data of the inner class instance.

public class OuterClass {
    public OuterClass() {
        super();
    }

    public OuterClass(InnerClass innerClass1, InnerClass innerClass2) {
        super();
        this.innerClass1 = innerClass1;
        this.innerClass2 = innerClass2;
    }

    private InnerClass innerClass1;
    private InnerClass innerClass2;

    public class InnerClass {
        public InnerClass() {
            super();
        }

        public InnerClass(int id, String name, String rollNo) {
            super();
            this.id = id;
            this.name = name;
            this.rollNo = rollNo;
        }

        private int id;
        private String name;
        private String rollNo;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRollNo() {
            return rollNo;
        }

        public void setRollNo(String rollNo) {
            this.rollNo = rollNo;
        }
    }

    public InnerClass getInnerClass1() {
        return innerClass1;
    }

    public void setInnerClass1(InnerClass innerClass1) {
        this.innerClass1 = innerClass1;
    }

    public InnerClass getInnerClass2() {
        return innerClass2;
    }

    public void setInnerClass2(InnerClass innerClass2) {
        this.innerClass2 = innerClass2;
    }
}

Main Class:-

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
    public class Reflection {
        public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException,
                IllegalArgumentException, InvocationTargetException {
            OuterClass outerClass = new OuterClass();
            OuterClass.InnerClass innerClass1 = outerClass.new InnerClass(1, "Iftekhar", "1234");
            OuterClass.InnerClass innerClass2 = outerClass.new InnerClass(2, "Ahmed", "123");
            outerClass.setInnerClass1(innerClass1);
            outerClass.setInnerClass2(innerClass2);

            Field[] fields = outerClass.getClass().getDeclaredFields();
            for (Field f : fields) {
                Method method = OuterClass.InnerClass.class.getMethod("getId", null);
                int id = (int) method.invoke(f, null);
                System.out.println(id);
            }
        }
    }

I am anticipating the output to be 1 and 2. But i am getting the below Exception:-

Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class

I am instantiating the inner Class attributes using the way show above.Can anyone please help where i am doing wrong.





Reason behind the get prefix in c#

Considering that in c# we have a specific syntax for properties with getters and setters, why are some properties accessed with methods (usually prefixed with 'Get') instead of a getter?

for example why is it:

var properties = object
    .GetType()
    .GetProperties();

instead of using a getter like:

var properties = object
    .Type
    .Properties





lundi 14 mai 2018

Get object value inside a nested list using reflection

I have these 2 objects:

public class OpenWeather
{
    //Some properties

    public List<Weather> weather { get; set; }
    public Temp temperaures {get; set;}
    //some other properties
}

public class Weather
{
    public int id { get; set; }
    public string main { get; set; }
    public string description { get; set; }
    public string icon { get; set; }
}
    public class Temps 
    {
        public double temp { get; set; }
        public double temp_min { get; set; }
        public double temp_max { get; set; }
    }

And this method to access nested objects using reflection:

    public object GetPropertyValue(object obj, string propertyName)
    {
        var objType = obj.GetType();
        var prop = objType.GetProperty(propertyName);

        return prop.GetValue(obj, null);
    }

So for example, if I have to get the "temp" value of the "Temps" object nested inside the "OpenWeather" object I do this:

string temp = "Temperature: " + GetPropertyValue(GetPropertyValue(previsione, "temperatures"), "temp");

But how do I get the First object properties from the nested list of "Weather" objects inside the "OpenWeather" object?