dimanche 20 août 2017

Using Simple Injector to register lazy parameters by reflection

I register all implementations of IService interface in Simple Injector by Reflection:

var registrations = assembly.GetExportedTypes()
   .Where(type => type.IsClass && baseType.IsAssignableFrom(IService))
   .Select(type => new { Interface = type.GetInterfaces().First(), Implementation = type });

foreach (var reg in registrations)
{
    container.Register(reg.Interface, reg.Implementation, Lifestyle.Transient);
}

I found Lazy Register solution to registering one instance of an interface. But I want register all implementations in lazy mode by Reflection. my desired solution is:

foreach (var reg in registrations)
{
    container.Register(() => new Lazy<reg.Interface>(container.GetInstance<typeof(reg.Implementation) >), Lifestyle.Transient);
}

Is there any solution to the problem described?





samedi 19 août 2017

Accessing all fields from an instance using composition in Go?

I have a struct named Parent that is designed to be used in composition:

package main

import (
    "fmt"
    "reflect"
)

type Parent struct {
    Field1 int
}

func (p *Parent) Display() {
    t := reflect.TypeOf(p).Elem()
    for i := 0; i < t.NumField(); i++ {
        fmt.Println(t.Field(i).Name)
    }
}

type Child struct {
    Parent
    Field2 int
}

func main() {
    c := &Child{}
    c.Display()
}

I would like the parent to be able to access both Field1 and Field2 using reflection. For example, the code above will only output Field1 since the type of p is Parent.

Is there a way (using reflection) for Display() to determine that the Parent is part of a Child and display all of its fields as well? Unfortunately, I cannot perform a .(*Child) type assertion since many different types will be using Parent.





Sorting with Java 8 by Field given as Input

I have a REST endpoint and I want the UI to pass the field name that they want to sort their result by. 'id', 'name', etc. I came up with below, but was really trying to use Reflection / Generics so this could be expanded to encompass every object in my project.

I feel like this solution isn't easily maintainable if I want to have the same functionality for 100 different classes.

public static void sort(List<MovieDTO> collection, String field){

        if(collection == null || collection.size() < 1 || field == null || field.isEmpty()){
            return;
        }
        switch(field.trim().toLowerCase()){
        case "id": 
            collection.sort(Comparator.comparing(MovieDTO::getId));
            break;
        case "name": 
            collection.sort(Comparator.comparing(MovieDTO::getName));
            break;
        case "year": 
            collection.sort(Comparator.comparing(MovieDTO::getYear));
            break;
        case "rating": 
            collection.sort(Comparator.comparing(MovieDTO::getRating));
            break;
        default: 
            collection.sort(Comparator.comparing(MovieDTO::getId));
            break;
        }
    }

Any ideas on how I could implement this better so that it can be expanded to work for an enterprise application with little maintenance?





vendredi 18 août 2017

Can a WCF duplex service determine if the callback channel of a client has implemented a specific method before the service tries to call it?

I've implemented a WCF duplex service IMyDuplexService with a callback contract IMyCallbackContract.

It was deployed successfully; clients can subscribe to the service and the service can call methods on the client using the callback channel without issues.

I've since added a new method to the callback contract and it can also be deployed successfully; old clients can still subscribe to the service as well as new clients, the service can call the old methods on both the old and new clients using the callback channel, as well as new methods on the new clients without issues.

Is there any way to determine if a specific client is an old or new client without having to implement this "versioning" logic myself?

For example, if the client was implemented using the older version of the callback contract and the service tries to call the new method on the old client, the following exception is thrown: System.ServiceModel.ActionNotSupportedException occurred HResult=-2146233087 Message=The message with Action 'http://domain/virtual_directory/IMyDuplexService/MyNewMethod' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None). Source=mscorlib StackTrace: Server stack trace: at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter) at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at MyService.IMyCallbackContract.MyNewMethod()

Is it possible for the service to determine if the client supports the new method before trying to call it?

I tried to use reflection but the following doesn't return null on an older client: clientCallbackChannelInstance.GetType().GetMethod("MyNewMethod")

Is implementing my own "versioning" scheme the only way?

P.S. I don't need help architecting or implementing my own versioning scheme. I just don't want to "reinvent the wheel." ;)

Thank you.





Autofac WCF injection on reflection

I have N validators on my aplication but a client doesn't use all validators, I got by procedure all classes that my current client will need to instantiate.

My Business layer:

public class MyClass
{
    public void MyMethod(int idClient)
    {
        //This array is returned by a procedure passing idClient
        string[] validatorsName = { "ValidatorName", "ValidatorName2" };

        foreach (string name in validatorsName)
        {

            IValidator validator = (IValidator)Activator.CreateInstance(Type.GetType(name));
            //Error. I need pass the INameDB;

            validator.Process();
        }
    }
}

My Interface:

public interface IValidator
{
    void Process();
}

The Validators:

public class ValidatorName : IValidator
{
    INameDB nameDB;

    public ValidatorName(INameDB nameDB)
    {
        this.nameDB = nameDB;
    }

    public void Process()
    {
        nameDB.AnyThing(pedidoId);
    }
}

public class ValidatorName2 : IValidator
{
    INameDB2 nameDB;

    public ValidatorName(INameDB2 nameDB)
    {
        this.nameDB = nameDB;
    }

    public void Process()
    {
        nameDB.AnyThing2(pedidoId);
    }
}

public class ValidatorName3 : IValidator
{
    INameDB2 nameDB;

    public ValidatorName(INameDB2 nameDB)
    {
        this.nameDB = nameDB;
    }

    public void Process()
    {
        nameDB.AnyThing2(pedidoId);
    }
}

On Global, I could register all validators and with the IList<IValidator>, so I would remove from the list the validators that I will not need.

 string[] validatorsName = { "ValidatorName", "ValidatorName2" };
 validators = validators .Where(p => validatorsName .Contains(p.GetType().Name)).ToList();

but I have a lot of classes, it would register this no need.

My Global:

public class Global : System.Web.HttpApplication
{

    protected void Application_Start(object sender, EventArgs e)
    {
        ContainerBuilder builder = new ContainerBuilder();
        builder.RegisterType<NameDB>().As<INameDB>();
        builder.RegisterType<NameDB2>().As<INameDB2>();

        //builder.RegisterType<ValidatorName1>().As<IValidator>();
        //builder.RegisterType<ValidatorName2>().As<IValidator>();
        //builder.RegisterType<ValidatorName3>().As<IValidator>();

        AutofacHostFactory.Container = builder.Build();
        //AutofacHostFactory.Container.Resolve<IList<IValidator>>();
    }
}

My question is how can I detect the interface INameDB or INameDB2, get the instance on Autofac and use on Activator.CreateInstance?

Thanks.





Performance of Invokemethod

void ExecuteMethodViaReflection(TestObj comm)
{
    var paramNames = comm.paramNames; //of type string array
    var paramData = comm.Data; //of type Object array

    Type t = this.GetType();
    t.InvokeMember(comm.Method, BindingFlags.InvokeMethod, null, this, paramData, null, null, paramNames);
    }

I use above method to invoke method using reflection. I call same method multiple times. Performance of this not great when compared to normal method invocation. Is there a better way i can do to improve performance.





Elegant Reflection Framework in .NET

Is there any open-source C# project available as a replacement for reflection providing an abstraction layer for ease of use and is also effective and useful in terms of performance and working.

I was searching on the web and found many such frameworks, e.g.

But no time to evaluate, so seeking some quick expert opinion on this. My goal is to replace many of the extension methods that I have defined to ease the reflection usage as shown below:

    public static Array CreateArrayInstance(this PropertyInfo propInfo, int length)
    {
        if (propInfo.PropertyType.IsArray)
        {
            var arrayType = propInfo.PropertyType.GetElementType();
            return Array.CreateInstance(arrayType, length);
        }
        return null;
    }

    public static IList CreateGenericListInstance(this PropertyInfo propInfo)
    {
        var type = propInfo.PropertyType.GenericTypeArguments[0];
        var listType = typeof(List<>).MakeGenericType(type);
        var listInstance = (IList)Activator.CreateInstance(listType);
        return listInstance;
    }

OR suggest some good and smart approach to handle instead of creating so many scattered extension methods.