mercredi 21 octobre 2015

Difference between IKVM.Reflection.Emit and Mono.Cecil

IKVM.Reflection.Emit has "the ability to read and emit .NET 1.1, .NET 2.0 and .NET 4.0 assemblies (while running on, for example, .NET 2.0).".

Does Mono.Cecil have the same? Are they interchangable for this use case? Are they both supported nowadays? What are key differences between them (in emitting IL)?





How can I return a super class instance?

I have an api that could have a timeout problem.

The main api method is like this :

public <T extends ApiResponse> T sendMessageSync(final Class<T> expected, final ApiBase apiMsg)

And I am using this method like this :

public <T extends ApiResponse> T send(final Class<T> expected, final ApiBase apiMsg)
{
    return sendMessageSync(expected, username, apiMsg);
}

And then :

public UsersAdmin.GetResponse getUser(final String authToken, final long userId)
{
    return send(UsersAdmin.GetResponse.class, new UsersAdmin.GetRequest(authToken, userId));
}

As you can guess, the UsersAdmin.GetResponse class is declared like that :

public class GetResponse extends ApiBase.ApiResponse

My problem : The ApiResponse class have a status attribute. When I have a timeout, I want to return a new instance of the ApiResponsewith this attribute set a specific value of an enum, like that :

if(result == null)
{
    // we didn't receive response, api timeout
    result = new ApiResponse(CR.API_TIMEOUT);
}

The problem if that fact there is a class cast exception between UsersAdmin.GetResponse and ApiResponse as I want to return a new instance of ApiResponse and this class is a super class of UsersAdmin.GetResponse.

To solved that I want to try to use reflection, but I can't access the constructors of ApiResponse from UsersAdmin.GetResponse class.

How can I acheive that ?





Call C# Method from C# Dll using Reflection

Good day, I got following problem. I'm working on my .dll library in C# and I need to call a method of another C# project from the dll library. For example I create WPF project and I add reference of my .dll library.

There is my WPF class (project):

using dllLibrary;

namespace Tester
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public void MyMethod()
        {
            MessageBox.Show("Test");
        }
    }
}

and There is my .dll project :

Type type = Type.GetType("Tester.MainWindow");
object instance = Activator.CreateInstance(type, null);
MethodInfo method = type.GetMethod("MyMethod");
return method.Invoke(instance, null);

By the way, it works when I call a method inside of the assembly (of the dll project), but When I want to call a method outside of the dll project (Tester.MainWindow - the WPF project) It doesnt work.





mardi 20 octobre 2015

Generic FetchDictionary method for petapoco

PetaPoco has this method :

public List<T> Fetch<T>(string sql, params object[] args) 
    {
        return Query<T>(sql, args).ToList();
    }

I want to create a method like this :

        public Dictionary<Guid, T> FetchDict<T>(string sql, params object[] args)
    {
//What goes here ?
        return Query<T>(sql, args).ToDictionary(x => ???, x => x);
    }

In the stub above, it should use reflection & use the PrimaryKey attribute and set that field as key. How can I do this ?





Self-written facts in Prolog?

How can you write code in Prolog that generates facts in response to the input of the user without you writing them by hand?

For example, i give the input:

Johnny loves Sally. Karen loves Bob.

The program should respond by creating the facts

loves(Johnny, Sally).
loves(Karen, Bob).

How can I do this?





Dynamic Beans with Generics

So i have two database tables which hold different types of beans. The first table named: Export is made up of a number of different bean names which are implement the Exporter interface defined as:

public interface Exporter<ExportType> {
    List<ExportType> export();  
}

The second table, named Export Action is made up of action beans that operate on the exported objects that are returned from the Exporter bean. There are two types of action beans, TRANSFORM beans which basically take as input the output from the exporter bean, and transform it into a different object, as defined by the second generic parameter type. The interface for this bean is defined as:

public interface ExportTransform<ExportType, TransformType> {
    List<TransformType> transform(List<ExportType> exportObjects);
}

The other type of action bean is a PROCESS bean. These beans take the output from the transformation and process them (persists them) and returns the entity objects back. This process interface is defined as:

public interface ExportPostProcess<TransformType, ProcessResult> {
    List<ProcessResult> postProcess(List<TransformType> transformObjects);
}

For this example, here's some example data for these two tables:

Table: Export

|----------------------------------------------------------------------------------|
|   ID    |        Bean Name       |   Creation Time     |    Modification Time    |
|----------------------------------------------------------------------------------|
|    1    |    documentExporter    | 2010-10-09 10:10:09 |   2010-10-10 12:09:10   |
|----------------------------------------------------------------------------------|

Table: Export Action

|------------------------------------------------------------------|
|   ID    |     Type     |          Bean Name          | Export ID |
|------------------------------------------------------------------|
|    1    |  TRANSFORM   | documentRulesetTransformer  |     1     |
|    1    |   PROCESS    |       rulesetProcessor      |     1     |
|------------------------------------------------------------------|

These beans have been implemented the corresponding interfaces as follows:

@Component
public class DocumentExporter implements Exporter<Document> {

    public List<Document> export() {
        // export
        return Collections.emptyList();
    }

}

@Component
public class DocumentRulesetTransformer implements ExportTransform<Document, RulesetVO> {

    public List<RulesetVO> transform(List<Document> transformObjects) {
        // transform
        return Collections.emptyList();
    }

}

@Component
public class RulesetProcessor implements ExportPostProcess<RulesetVO, Ruleset> {

    public List<Ruleset> postProcess(List<RulesetVO> transformObjects) {
        // process
        return Collections.emptyList();
    }

}

Finally... My question is.. what is the best way to manage this in terms of generics without needing a bunch of explicit casts or @SupressWarnings("unchecked") everywhere? Considering this data is dynamic, and so are the bean implementations.

Currently I have code like the following (simplified for readability):

Set<Export> exportBeans = exportRepository.findAll();
exportBeans.forEach(export -> {

    Exporter<?> exporter = applicationContext.getBean(export.getBeanName(), Exporter<?>.class);
    List<?> exportObjects = exporter.export();

    ExportTransform<?, ?> transformer = export.getActions.get(ActionType.TRANSFORM);
    List<?> transformedObjects = transformer.transform(exportObjects);

    ExportPostProcess<?, ?> postProcessor = export.getActions.get(ActionType.PROCESS);
    List<?> processedObjects = postProcessor.postProcess(transformObjects);

});

At the moment, I have to use reflection to validate the bean implementations are supported as per their generic types. I.E the rulesetProcess¬ bean is able to accept the result of thedocumentResultTransformer` bean. Which is cumbersome and nasty. I would love to think there was something I could utilize which takes care of this for me to some degree.

Any help would be greatly appreciated.





InvalidProgramException when trying to create a new type

I have the following code:

AssemblyBuilder newAssembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("CustomAssembly"), AssemblyBuilderAccess.Run);
ModuleBuilder newModule = newAssembly.DefineDynamicModule("CustomModule");
TypeBuilder newType = newModule.DefineType("CustomType", TypeAttributes.Public);
MethodBuilder newMethod = newType.DefineMethod("GetMessage", MethodAttributes.Public, typeof(string), Type.EmptyTypes);
byte[] methodBody = ((Func<string>)(() => "Hello, world!")).GetMethodInfo().GetMethodBody().GetILAsByteArray();
newMethod.CreateMethodBody(methodBody, methodBody.Length);
Type customType = newType.CreateType();
dynamic myObject = Activator.CreateInstance(customType);
string message = myObject.GetMessage();

However, an exception is thrown on the last line when tryingto call myObject.GetMessage():

InvalidProgramException - Common Language Runtime detected an invalid program.

What is wrong with my code and why is this exception being thrown?