lundi 20 août 2018

how to get the updated or modified list record by comparing 2 list using linq or reflection

List<NeWClient> ListofNewClient = new List < NeWClient >{
                new NeWClient {   ClientID = 1, ClientName = "Nilesh", companyLocation = "Mumbai", companyName = "CG" },
                 new NeWClient {   ClientID = 101, ClientName = "Rahul", companyLocation = "USA", companyName = "TATA" }
               };

        List<OldClient> ListofOldClient = new List<OldClient>{
            new OldClient {   ClientID = 1, ClientName = "Nilesh", companyLocation = "Mumbai", companyName = "CG" },
            new OldClient {   ClientID = 3, ClientName = "Mary", companyLocation = "UK", companyName = "KG" },
            new OldClient {   ClientID = 7, ClientName = "jhon", companyLocation = "USA", companyName = "TG" },
            new OldClient {   ClientID = 9, ClientName = "Tom", companyLocation = "India", companyName = "PG" }
           };

    var  Common = ListofNewClient.Where(n => ListofOldClient.Any(o => o.ClientID == n.ClientID)).ToList();
    var  Deleted = ListofOldClient.Where(o => !ListofNewClient.Any(n => n.ClientID == o.ClientID)).ToList();
    var  NewlyAdded = ListofNewClient.Where(n => !ListofOldClient.Any(o => o.ClientID == n.ClientID)).ToList();

Above works fine for common , deleted, NewlyAdded but i am not able to find the updated or modified the newClinet by comparing with oldClient

        List<NeWClient> ListofNewClient1 = new List<NeWClient>{
            new NeWClient {   ClientID = 200, ClientName = "Dinesh", companyLocation = "Surat", companyName = "nts" },
           };

        List<OldClient> ListofOldClient1 = new List<OldClient>{
            new OldClient {   ClientID = 200, ClientName = "Dinesh", companyLocation = "Mumbai", companyName = "nts" },
            new OldClient {   ClientID = 3, ClientName = "Mary", companyLocation = "UK", companyName = "KG" },
           };

Required Result : ListofNewClient1 values are changed here when we compare with ListofOldClient1 so required result will be from ListofNewClient1 which is given below

ClientID = 200, ClientName = "Dinesh", companyLocation = "Surat", companyName = "nts"





dimanche 19 août 2018

Quickly editing private varriables

In my project I want quickly read from and make modifications to a private-ish variable. I was initially going to do reflection, but my thinking was that it would be too inefficient.

public class SomeControllerInALibraryThatICantEdit {

    //I can easily get an instance of the controller
    public static final SomeControllerInLargeLibrary instance;

    //I need to read from and make changes to the data object quickly.
    //It is final, so I don't need to worry about this object changing or being reset.
    private final Subclass dataClass = new Subclass();

    private class Subclass {

        //I can get this once then treat it like any other array.
        public float[] arr;


        //This is the problematic part. I need to be able to quickly check changes and 
        //set this every update. Keeping in mind there are multiple dataPoints.
        public short dataPoint;

    }

}

What is a quick and efficient way to get and set dataPoint? I can use reflection, but I am hoping there is a better way to approach this problem. Can I in some way make a Pojo that represents Subclass and link their pointers together?

If I just fork the library and make it work better with what I am doing, then that defeats the purpose of my project.





Using native library in external classes loaded dynamically (with reflection)

In my application, I'm using DexClassLoader to load a class of an external apk as follow:

DexClassLoader dexClassLoader = new DexClassLoader("path/to/someApkfile.apk", myOptimizedDirectory, null, myContext.getClassLoader());
Class<?> MyClass =  dexClassLoader.loadClass("its.package.name.MyClass");

Then invoking a method using reflection as follow:

Object myInstance = MyClass.newInstance();
MyClass.getDeclaredMethod("foo").invoke(myInstance);

here is the method foo:

public void foo() {
 System.Load("path/to/arch/specific/native/lib/libname.so");
 // I know that this native library loaded successfully because JNI_OnLoad is called.

 // here is the problem
 myNativeMethod("arg");
}

Here is the log message:

mMessages: uncaught exception
    java.lang.UnsatisfiedLinkError: No implementation found for int its.package.name.MyClass.myNativeMethod(java.lang.String) (tried Java_its_package_name_MyClass_myNativeMethod) ...

I am sure that the method signature in my native code is correct and nothing is wrong there.

Also, I'm sure that it successfully loaded native library, so why I does it say No implementation found?


Please don't say why are you doing this? or it is error prone or it is a bad practice, just point out what is the problem.

Thanks in advance :)





samedi 18 août 2018

How to safely get the a particular base type of a control?

I have a user control A which inherits from a concrete base type B which in turn inherits from a generic control C.

I need to check if A inherits from C and currently I'm doing the following:

var cType = typeof(C<>);
var aType = typeof(A);

if (aType.BaseType.BaseType?.FullName == cTye.FullName) {}

The above works but I was wondering if there's a cleaner way to do this?





Why does my generic type method think T is system.object when I'm passing in a HashSet

So I'm trying to figure out why my generic method is losing type information.

When I pass in reflected data (in this example T = HashSet) the code thinks T = system.object. When I pass in non-reflected data, my T is correctly typed as HashSet type.

The only difference in my example is that in my first call I am passing directly a HashSet, and in my second call I am passing in an object with a HashSet property, and using reflection to get the HashSet and pass it in.

Both HashSets get executing by the exact same code, yet T is different each time.

I've managed to hack together a "workaround" where I pass in as a second parameter, the correct type, and from there I can get my desired results.

However, this seems hacky and I'd like to know why I have to do this workaround to get my desired results.

Can anybody explain why I am observing what I'm observing and how I can get my T type to be correct each and every time without passing in the type twice?

using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        var simple = new HashSet<string>();
        simple.Add("1");
        simple.Add(" 1 ");
        Console.WriteLine("Simple Before => " + JsonConvert.SerializeObject(simple));
        simple = simple.DeepTrimAll();
        Console.WriteLine("Simple After => " + JsonConvert.SerializeObject(simple));
        Console.WriteLine();
        var complex = new Complex();
        complex.HS = new HashSet<string>();
        complex.HS.Add("1");
        complex.HS.Add(" 1 ");
        Console.WriteLine("Complex Before => " + JsonConvert.SerializeObject(complex));
        complex = complex.DeepTrimAll();
        Console.WriteLine("Complex After => " + JsonConvert.SerializeObject(complex));
    }
}

public class Complex
{
    public HashSet<string> HS
    {
        get;
        set;
    }
}

public static class Ext
{
    public static T DeepTrimAll<T>(this T context, Type t)where T : class
    {
        if (context is IEnumerable<string>)
        {
            var type = typeof (T);
            Console.WriteLine("T = " + type.ToString() + " , t = " + t.ToString());
            var list = new List<string>(context as IEnumerable<string>);
            for (int i = 0; i < list.Count(); i++)
            {
                list[i] = list[i].Trim();
            }

            var res = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(list), t);
            return (T)res;
        }

        var properties = typeof (T).GetProperties().Where(x => x.CanRead && x.CanWrite).ToList();
        foreach (var propertyInfo in properties)
        {
            var propType = propertyInfo.PropertyType;
            var value = propertyInfo.GetValue(context, null);
            if (propType == typeof (string))
            {
                if (!string.IsNullOrWhiteSpace(value.ToString()))
                {
                    propertyInfo.SetValue(context, value.ToString().Trim());
                }
            }
            else if (!propType.IsEnum && !propType.IsPrimitive)
            {
                var newValue = value.DeepTrimAll(propType);
                propertyInfo.SetValue(context, newValue);
            }
        }

        return context;
    }

    public static T DeepTrimAll<T>(this T context)where T : class
    {
        return context.DeepTrimAll(typeof (T));
    }
}

This example produces the following results:

Simple Before => ["1"," 1 "]
T = System.Collections.Generic.HashSet`1[System.String] , t = System.Collections.Generic.HashSet`1[System.String]
Simple After => ["1"]

Complex Before => {"HS":["1"," 1 "]}
T = System.Object , t = System.Collections.Generic.HashSet`1[System.String]
Complex After => {"HS":["1"]}

dotNetFiddle





vendredi 17 août 2018

How to get static fields from another class using reflection?

We have a static class called VisualizationSettings that has ~20 instances of a struct we made called VisualizationSetting (singular).

I want to have another class pull in all the individual instances of VisualizationSetting from VisualizationSettings, and modify them.

I added a method to VisualizationSettings that should get and return all instances of VisualizationSetting, like so:

    public static FieldInfo[] GetFields(){
        Type myType = typeof(VisualizationSetting);
        FieldInfo[] myField = myType.GetFields();
        return myField;
    }

Then, in my other class, I access this FieldInfo[], iterate through it, and modify it, like so:

    FieldInfo[] myField = VisualizationSettings.GetFields();

    foreach (FieldInfo setting in myField) {
        VisualizationSetting value = (VisualizationSetting)setting.GetValue(null);

        /* A bunch of stuff to modify value */

        setting.SetValue(null, value);
    }

However I get an error on the line VisualizationSetting value = (VisualizationSetting)setting.GetValue(null); saying TargetException: Non-static field requires a target

My confusion is that as far as I'm aware, setting should static, since VisualizationSettings is a static class. Is there something I'm missing here?





Dynamic expression tree with method 'Select'

I'm trying to build the following lambda expression using the expression tree ->

info => info.event_objects.Select(x => x.object_info.contact_info)

I researched a lot and find some answers on the StackOverflow. This one helped me to build the

info => 
     info.event_objects.Any(x => x.object_info.contact_info.someBool == true)

As you can see, the method 'Any' is easy to get.

var anyMethod = typeof(Enumerable).GetMethods().Single(m => m.Name == "Any" 
&& m.GetParameters().Length == 2);
anyMethod = anyMethod.MakeGenericMethod(childType);

The main problem is with the method 'Select'. If you will try to change the Name "Any" to "Select", you will get the following exception:

var selectMethod = typeof(Enumerable).GetMethods().Single(m => m.Name == 
"Select" && m.GetParameters().Length == 2);
selectMethod = selectMethod.MakeGenericMethod(childType);

Additional information: Sequence contains more than one matching element

Another way I've tried:

MethodInfo selectMethod = null;
foreach (MethodInfo m in typeof(Enumerable).GetMethods().Where(m => m.Name 
  == "Select"))
    foreach (ParameterInfo p in m.GetParameters().Where(p => 
           p.Name.Equals("selector")))
        if (p.ParameterType.GetGenericArguments().Count() == 2)
            selectMethod = (MethodInfo)p.Member;

It seems work, but then I get the exception here:

navigationPropertyPredicate = Expression.Call(selectMethod, parameter, 
navigationPropertyPredicate);

 Additional information: Method 
 System.Collections.Generic.IEnumerable`1[TResult] Select[TSource,TResult] 
 (System.Collections.Generic.IEnumerable`1[TSource], 
 System.Func`2[TSource,TResult]) is a generic method definition> 

After that, I've tried to use:

selectMethod = selectMethod.MakeGenericMethod(typeof(event_objects), 
typeof(contact_info));

In fact, it doesn't help.

Here is my full code

 public static Expression GetNavigationPropertyExpression(Expression parameter, params string[] properties)
    {
        Expression resultExpression = null;
        Expression childParameter, navigationPropertyPredicate;
        Type childType = null;

        if (properties.Count() > 1)
        {
            //build path
            parameter = Expression.Property(parameter, properties[0]);
            var isCollection = typeof(IEnumerable).IsAssignableFrom(parameter.Type);
            //if it´s a collection we later need to use the predicate in the methodexpressioncall
            if (isCollection)
            {
                childType = parameter.Type.GetGenericArguments()[0];
                childParameter = Expression.Parameter(childType, "x");
            }
            else
            {
                childParameter = parameter;
            }
            //skip current property and get navigation property expression recursivly
            var innerProperties = properties.Skip(1).ToArray();
            navigationPropertyPredicate = GetNavigationPropertyExpression(childParameter, innerProperties);
            if (isCollection)
            {
                //var selectMethod = typeof(Enumerable).GetMethods().Single(m => m.Name == "Select" && m.GetParameters().Length == 2);
                //selectMethod = selectMethod.MakeGenericMethod(childType);
                MethodInfo selectMethod = null;
                foreach (MethodInfo m in typeof(Enumerable).GetMethods().Where(m => m.Name == "Select"))
                    foreach (ParameterInfo p in m.GetParameters().Where(p => p.Name.Equals("selector")))
                        if (p.ParameterType.GetGenericArguments().Count() == 2)
                            selectMethod = (MethodInfo)p.Member;

                navigationPropertyPredicate = Expression.Call(selectMethod, parameter, navigationPropertyPredicate);
                resultExpression = MakeLambda(parameter, navigationPropertyPredicate);
            }
            else
            {
                resultExpression = navigationPropertyPredicate;
            }
        }
        else
        {
            var childProperty = parameter.Type.GetProperty(properties[0]);
            var left = Expression.Property(parameter, childProperty);
            var right = Expression.Constant(true, typeof(bool));
            navigationPropertyPredicate = Expression.Lambda(left);
            resultExpression = MakeLambda(parameter, navigationPropertyPredicate);
        }
        return resultExpression;
    }


    private static Expression MakeLambda(Expression parameter, Expression predicate)
    {
        var resultParameterVisitor = new ParameterVisitor();
        resultParameterVisitor.Visit(parameter);
        var resultParameter = resultParameterVisitor.Parameter;
        return Expression.Lambda(predicate, (ParameterExpression)resultParameter);
    }

    private class ParameterVisitor : ExpressionVisitor
    {
        public Expression Parameter
        {
            get;
            private set;
        }
        protected override Expression VisitParameter(ParameterExpression node)
        {
            Parameter = node;
            return node;
        }
    }


    [TestMethod]
    public void TestDynamicExpression()
    {
        var parameter = Expression.Parameter(typeof(event_info), "x");
        var expression = GetNavigationPropertyExpression(parameter, "event_objects", "object_info", "contact_info");
    }