jeudi 30 juin 2016

List.Sort by property name - Including subclasses

I have a bit of a challenge. I need to sort a List of objects, and I need to sort it from a string representing the path to the property in any sub class. I need to use the List.Sort() and not OrderBy().

Lest make a simple example. I have a list of persons represented by two sub classes for identification and name

public class NameParts
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
}

public class Identification
{
    public String NiNumber { get; set; }
    public NameParts Name { get; set; }
}

public class Person
{
    public String Email { get; set; }
    public String Phone { get; set; }
    public Int16 Age { get; set; }

    public Identification Id { get; set; }
}

Now I need to sort the list by age. Very simple

 public static void SortByAge(List<Person> listToSort)
 {
     listToSort.Sort((x, y) => x.Age.CompareTo(y.Age));
 }

And even by NiNumber and FirstName it is fairly simple this way

 public static void SortByNiNumber(List<Person> listToSort)
 {
      listToSort.Sort((x, y) => x.Id.NiNumber.CompareTo(y.Id.NiNumber));
 }

 public static void SortByFirstName(List<Person> listToSort)
 {
      listToSort.Sort((x, y) => x.Id.Name.FirstName.CompareTo(y.Id.Name.FirstName));
 }

Now comes the tricky part. I need to perform all the above sorts giving a string that represents the path to theproperty to sort by. Like "Id.Name.FirstName"

So I need

 public static void SortByAny(List<Person> listToSort, String sortBy)
 {
   //??????
 }

That can be called with

 List<Person> theList = new List<Person>();
 SortByAny(theList, "Age");
 SortByAny(theList, "Id.NiNumber");
 SortByAny(theList, "Id.Name.FirstName");

I know I need to use reflection for this, and I have managed to do so but I cannot get further than properties in the Person Class itself, so I probably need to do something else, and this is where I'm stuck.

Does anyone have some brilliant ideas on how to solve this?

Thanks





Instantiate internal class with public constructor in third party assembly

I would like to instantiate an internal class of a third party with a public constructor, the class Microsoft.AnalysisServices.XmlaClient to be exact. Ideally, I would like to end up being able to access the methods like instance.Connect(blabla) etc. Is this possible through Reflection?

namespace Microsoft.AnalysisServices
{
    internal class XmlaClient
    {
        public XmlaClient();

        public ConnectionInfo ConnectionInfo { get; }
        public string SessionID { get; set; }

        public void CancelCommand(string sessionID);
        public void Connect(string connectionString);
        public void Connect(ConnectionInfo connectionInfo);
        public void Connect(ConnectionInfo connectionInfo, bool beginSession);
        public void Connect(ConnectionInfo connectionInfo, string sessionID);
        public void Connect(string connectionString, bool beginSession);
        public void Connect(string connectionString, string sessionID);
        public void Disconnect();
        public void Disconnect(bool endSession);
        public ConnectionState GetConnectionState(bool pingServer);
        public void Reconnect();
    }
}





How to make an annotation where I can set a different value depending on the condition?

I want to make an annotation to use in Test Cases. I have a method that tests methods of an object, and what I want is to use an annotation "grade" with a parameter called "value", and when the condition is right I want to set 10 to the annotation or 0 if it is wrong. For example: I have a method called "test" that receives an object as attribute. Then, knowing that this object has a method "sum", I will write a condition like if(myobject.sum(2,2)==4). If this test pass then the test gets the grade 10. So, what I want is to create a annotation to grade the tests, like @grade(10,0). If the test pass, I set 10 as parameter to the annotation and if didn't I set 0. This test case will execute from another class, so I think I will use reflection to see if there are annotations in the methods or attributes and then get the values but I don't know how to implement this way, if I need to put annotations for methods or for attributes, if I have to create an atribute to put the annotation, etc. Does anybody know how can I implement this?





Modify a value inside a while loop java

I have a runnable with this code inside it

public void run() {
    while(enabled) {
        long wait = 50000000L;
        System.out.println(wait);
    }
}

I have no access to the following code, but I want to modify the wait value(make the it tick faster, this is just a simplified version of it)

Edit: I need to modify it during runtime, and I know about reflection I just don't know if you can use it in this case





EmitCalli .net core alternative

Is there any alternative to .net framework EmitCalli for netcoreapp1.0

if (IntPtr.Size == 4)
    il.Emit(OpCodes.Ldc_I4, ptr.ToInt32());
else if (IntPtr.Size == 8)
    il.Emit(OpCodes.Ldc_I8, ptr.ToInt64()); 

il.EmitCalli(OpCodes.Calli, CallingConvention.Cdecl, returnType, paramTypes);





Is it possible to pass in a Play! Template as a variable?

I am using Play and I have a simple EmailService class that renders a few objects in a Play template. Here is my code:

Content html = views.html.acceptedEmail.render(incomingUBD,relatedUBD,rule);
      email = new Email().setFrom("noreply@elemica.com")
          .setTo(rule.getSuccessEmailValues())
          .setSubject(rule.getFailureNotificationSubject())
          .setBodyHtml(html.toString());

I'm wondering if it's possible to pass in the acceptedEmail template as a variable value so that the template I'm applying could change dynamically based on what value I was passing into the EmailService (Java) class this code is coming from.

I'm fairly new to Scala templating so apologies if the question is a little out there or if more information is required.





Finding method through reflection and return type

After having worked with reflection some and managed to get some data back from GetMethods I've finally hit a wall. I've tried to find any sources on this, but to no avail.

Basically I'm creating a RESTFUL Api in ASP.NET (MVC webapi) and using reflection to find the correct method of a DataComponent class that contains hundreds of views / stored procedures. I've gotten past the basic hurdles, but now when I'm finally attempting to use a parameter to find a specific SQL-view I seem to be getting an error:

Ambiguous match found.

I'm assuming this is because I'm attempting to find a single method through

MethodInfo theMethod = myType.GetMethod(toCheck);

But the result is two different methods.

According to my manager it's due to the fact that we are using two different views that return two different DataTypes (one a DataReader, the other a DataSet).

What I want to ask the HIVEMIND is how I can narrow down these two results to a single result either with the help of manually checking for the resulting returntype being DataSet or any other way?

Thanks





mercredi 29 juin 2016

Import eclipse android project in intellij but not running show following error

Information:30/6/16 11:38 AM - Compilation completed with 22 errors and 0 warnings in 3s 733ms Error:Android Dex: [Sample] Exception in thread "main" java.lang.reflect.InvocationTargetException Error:Android Dex: [Sample] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) Error:Android Dex: [Sample] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) Error:Android Dex: [Sample] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) Error:Android Dex: [Sample] at java.lang.reflect.Method.invoke(Method.java:606) Error:Android Dex: [Sample] at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:130) Error:Android Dex: [Sample] Caused by: java.lang.UnsupportedClassVersionError: com/android/dx/command/dexer/Main : Unsupported major.minor version 52.0 Error:Android Dex: [Sample] at java.lang.ClassLoader.defineClass1(Native Method) Error:Android Dex: [Sample] at java.lang.ClassLoader.defineClass(ClassLoader.java:803) Error:Android Dex: [Sample] at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) Error:Android Dex: [Sample] at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) Error:Android Dex: [Sample] at java.net.URLClassLoader.access$100(URLClassLoader.java:71) Error:Android Dex: [Sample] at java.net.URLClassLoader$1.run(URLClassLoader.java:361) Error:Android Dex: [Sample] at java.net.URLClassLoader$1.run(URLClassLoader.java:355) Error:Android Dex: [Sample] at java.security.AccessController.doPrivileged(Native Method) Error:Android Dex: [Sample] at java.net.URLClassLoader.findClass(URLClassLoader.java:354) Error:Android Dex: [Sample] at java.lang.ClassLoader.loadClass(ClassLoader.java:425) Error:Android Dex: [Sample] at java.lang.ClassLoader.loadClass(ClassLoader.java:358) Error:Android Dex: [Sample] at org.jetbrains.android.compiler.tools.AndroidDxRunner.loadDex(AndroidDxRunner.java:75) Error:Android Dex: [Sample] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:128) Error:Android Dex: [Sample] at org.jetbrains.android.compiler.tools.AndroidDxRunner.main(AndroidDxRunner.java:294) Error:Android Dex: [Sample] ... 5 more





Generic type parameter does not match wildcard variable

I have an interface class EnumIF

public interface EnumIF<T> {
    T getVal();
}

And have a method that is generic for classes implementing this interface

public static <E extends EnumIF> E find(Class<E> type) {
    ...
}

I cannot pass a wildcard generic class from some reflection code;

Class<? extends EnumIF> fieldClazz = (Class<? extends EnumIF>) field.getType();
EnumIF findet = find(fieldClazz) //compiler error

Why can't I pass wildcard generic generated from reflection as regular generic type? How to do this transition?





Using reflection methods that take array parameters efficiently

Currently I'm using some static arrays to avoid creating garbage for reflection methods that take arrays:

public static readonly object[]
    OneObject = new object[1],
    TwoObjects = new object[2];

Then I use them like:

public void Write(BinaryWriter writer, object value)
{
    Reflection.TwoObjects[0] = writer;
    Reflection.TwoObjects[1] = value;
    WriteMethod.Invoke(null, Reflection.TwoObjects);
}

Most of the time this will be fine, but it opens the door to multithreading bugs.

Is there a better way of doing this without allocating tiny arrays all over the place?





casting error while dynamically invoking a function that returns a custom type

I have a custom type, customType, defined under tool1.class1.

I am using some other method, under tool1.class2, with a name routine1, that returns a "List of customType", as follows.

This code returns a list of customtype with no errors:

    List<tool1.class1.customType> result1 = new List<tool1.class1.customType>();
    result1 = tool1.class2.routine1(argsAsStr, p_values);

The following code also works fine and returns an object, as follows:

    Assembly tool1 = Assembly.LoadFrom(@"C:\tool1\tool1\bin\Debug\tool1.dll");
    Type type = tool1.GetType("tool1.class2");
    object instance = Activator.CreateInstance(type);
    object[] parametersArray = new object[] { argsAsStr, p_values};
    MethodInfo method = type.GetMethod("routine1");
    object result2 = method.Invoke(instance, parametersArray); 

However, when I try to use the type List, instead of the object, then I receive the following error:

    Assembly tool1 = Assembly.LoadFrom(@"C:\tool1\tool1\bin\Debug\tool1.dll");
    Type type = tool1.GetType("tool1.class2");
    object instance = Activator.CreateInstance(type);
    object[] parametersArray = new object[] { argsAsStr, p_values};
    MethodInfo method = type.GetMethod("routine1");
    List<tool1.class1.customType> result2 = method.Invoke(instance, parametersArray)

Error message:

Error: Cannot implicitly convert type 'object' to 'System.Collections.Generic.List<tool1.class1.customType>'. 
An explicit conversion exists (are you missing a cast?) 

How can I overcome this casting error, and, hopefully, return "not" an object but "a list of customType" after invoke method??

Thanks in advance for your interest and contributions,

Aykut





Interface from string to use as generic type

I'm using Service Fabric in Azure and set up a proxy to an actor like this:

var proxy = ActorProxy.Create<T>(actorId);

Where T must be specified as the interface of the actor I'm calling.

Let's say I have the name of the interface as a string:

var interfaceName = "IUserActor";

Is there a way to instatiate a generic type by this string name? And if there is, how do I call a method specified in given interface by it's string name?

All actor interfaces inherits from IActor which is a part of Service Fabric.

Now I understand that this is not recommended, the point is to be able to access the actor state for a given actor, from tests and administrative purposes. Speed is insignificant in this case, so any reflection approach will do.

So, a basic usage example, not using the dynamic interface name:

public async Task<string> AdminGetState(ActorId actorId, string interfaceName){
   var proxy = ActorProxy.Create<IUserActor>(actorId);
   var state = await proxy.AdminGetStateJson();
   return JsonConvert.SerializeObject(state);
}





ASP.NET Dynamically Load Implemenations at runtime

I'm writing an ASP.NET API for a client who needs multiple implementations of some specific code to access various versions of a 3rd party API.

Writing a windows application I'd just use reflection but not sure if that's a) the best way to go for IIS or b) why I'm getting so many problems trying to load a type from a dll under the bin directory (copied in rather than a dependency). Using reflection I'm able to get the type but creating an Instance of it using Activator.CreateInstance seems to give be just a system object rather than the type implementation.

So my question is does reflection seem the right way to go or should I take note that ASP doesn't seem to like loading the type in at runtime and instead compile all implementations of the 3rd party wrapper dlls and use a factory to return the right implementation (downside being all versions will be included in the software)

Cheers





How to load .Net Core 1.0 RTM EXE with Assembly.Load from .NET 4.5.2

I have a tool that is written in .NET 4.5.2 that generates proxy output files using reflection. You point the tool to a DLL and it generates the output.

It loads the Assembly or EXE using Assembly.Load, however when pointing it at an ASP.NET Core 1.0 RTM application that is compiled with the 4.5.2 framework (the output in the \bin\Debug\net452 folder), it gets the following exception:

Unhandled Exception: System.BadImageFormatException: Could not load file or assembly 'http://file/C:\Code\Test452Web\bin\Debug\net452\Test452Web.exe' or one of its dependencies. An attempt was made to load a program with an incorrect format.
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at TypeScriptTypingsGenerator.Program.Main(String[] args) in C:\Code\TypeScriptTypingsGenerator\TypeScriptTypingsGenerator\Program.cs:line 31

Since the ASP.NET CORE application is compiled in 4.5.2 as well, I think it should be able to be loaded into the AppDomain. What is the proper way to do this?





Java reflection ClassNotFound Exception

I am trying to dynamically link to a jar file at run time using reflections. I have created the declarations for the main classes and the methods and its all working fine except when I try to invoke a method, I get this exception:

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.myapp.languagedetectorreflection.LangDetectReflectionManager.CreateDetectorFactory(LangDetectReflectionManager.java:73)
    at com.myapp.sharedlibrary.LanguageManager.LanguageDetector.<init>(LanguageDetector.java:40)
    at com.myapp.sharedlibrary.LanguageManager.LanguageDetector.getInstance(LanguageDetector.java:50)
    at com.myapp.tikamanager.MetaParser.<init>(MetaParser.java:66)
    at com.myapp.langtest.LangTest.main(LangTest.java:85)
Caused by: java.lang.NoClassDefFoundError: org/reflections/Reflections
    at com.cybozu.labs.langdetect.DetectorFactory.<init>(DetectorFactory.java:77)
    ... 9 more
Caused by: java.lang.ClassNotFoundException: org.reflections.Reflections
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at com.myapp.languagedetectorreflection.ParentLastURLClassLoader.loadClass(ParentLastURLClassLoader.java:70)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

The line in question is: final Reflections reflections = new Reflections(null, new ResourcesScanner());

I tried declare the reflections jar as a direct dependency to the main application hoping that it will load it but that did not help. I am not sure what else to do? Is there a trick when using reflections to load dependencies?





Using nameof to get name of current method

Have browsed, searched and hoped but cannot find a straight answer.

Is there anyway in C# 6.0 to get the current method name using nameof withouth specifying the method name?

I am adding my test results to a dictionary like this:

Results.Add(nameof(Process_AddingTwoConsents_ThreeExpectedRowsAreWrittenToStream), result);

I would prefer if I would not have to specify the method name explicitly so I can copy+paste the line, a non-working example:

Results.Add(nameof(this.GetExecutingMethod()), result);

If possible I do not want to use Reflection.





JAVA Reflection - JoinPoint

I'm trying to use java reflection to get details about some execution and save it in gray log.

Gray log methods accept join point parameters, but i can't get much information, i'd like to get all information a cast it to JSON, can you help how to do this ?

This is what i've tried:

MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Object[] args = joinPoint.getArgs();
for (Object a : args) {
            if (a.getClass().toString().toLowerCase().contains("request")) {
                Method[] methods = a.getClass().getMethods();
                for (Method m : methods){
                    if (m.getName().substring(0, 3).toLowerCase().equals("get")) {
                        Object result = m.invoke(a);
                        jArray = new JSONArray();
                        jObject = new JSONObject();
                        if (result instanceof List<?>) {
... } } } } }

this implies that i have to test all instanceof that same result, what i want is to get the info and parse it to JSON.





Add objects to list in loop in IL Emit - Common Language Runtime detected an invalid program

The following is my C# code:

List<int> list = new List<int>();
for(int Count = 0; Count < 5; Count++)
    list.Add(Count);
return list;

My corresponding emitted code is as follows:



LocalBuilder list = ILout.DeclareLocal(typeof(List<int>));
            LocalBuilder Count = ILout.DeclareLocal(typeof(int));
            LocalBuilder CmpRes = ILout.DeclareLocal(typeof(bool));
            ConstructorInfo DictConstrctor = typeof(List<int>).GetConstructor(new Type[] { });
            MethodInfo methodinfo_add = typeof(List<int>).GetMethod("Add", new[] { typeof(int) });
            Label IL_001C = ILout.DefineLabel();
            Label IL_000B = ILout.DefineLabel();

            ILout.Emit(OpCodes.Newobj, DictConstrctor);
            ILout.Emit(OpCodes.Stloc_0, list);
            ILout.Emit(OpCodes.Ldc_I4_0);
            ILout.Emit(OpCodes.Stloc_1, Count);

            ILout.Emit(OpCodes.Br_S, IL_001C);
            ILout.MarkLabel(IL_000B);
            ILout.Emit(OpCodes.Ldloc_0, list);
            ILout.Emit(OpCodes.Ldloc_1, Count);
            ILout.Emit(OpCodes.Call, methodinfo_add);

            ILout.Emit(OpCodes.Ldloc_1, Count);
            ILout.Emit(OpCodes.Ldc_I4_1);
            ILout.Emit(OpCodes.Add);

            ILout.Emit(OpCodes.Stloc_1, Count);
            ILout.MarkLabel(IL_001C);
            ILout.Emit(OpCodes.Ldloc_1, Count);
            ILout.Emit(OpCodes.Ldc_I4_2);
            ILout.Emit(OpCodes.Clt);
            ILout.Emit(OpCodes.Stloc_3, CmpRes);
            ILout.Emit(OpCodes.Ldloc_3, CmpRes);
            ILout.Emit(OpCodes.Brtrue_S, IL_000B);

            ILout.Emit(OpCodes.Ldloc_0, list);
            ILout.Emit(OpCodes.Ret);

It is throwing an exception - "Common Language Runtime detected an invalid program.".

What is it that I am doing wrong here? Any help is appreciated.





Class.forName() is not working with a particular class

I am trying to load with java reflection a bunch of classes. Everything seems working fine (I am handling the exception if the class is not found).

However there is a particular class that is raising another exception that is not thrown by call to the Class.forname() but by an internal method and so I cannot even catch it.

Here is my code:

try {
     URL url = Class.forName(qualifiednameOfTheClass);
} catch (ClassNotFoundException ex) {
     // ok class not found can be handled
} catch (Exception e){
     // catch every other exception just to try to get the strange exception
}

So with this code everything is working, I am using it on lots of classes and it's working (sometimes it finds it sometimes it doesn't).

However there is one case that is not working properly and I cannot understand why. If qualifiednameOfTheClass = sun.security.krb5.SCDynamicStoreConfig my code is raising an exception:

Exception in thread "mythread-1" java.lang.UnsatisfiedLinkError: no osx in java.library.path at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1886) at java.lang.Runtime.loadLibrary0(Runtime.java:849) at java.lang.System.loadLibrary(System.java:1088) at sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:67) at sun.security.action.LoadLibraryAction.run(LoadLibraryAction.java:47) at java.security.AccessController.doPrivileged(Native Method) at sun.security.krb5.SCDynamicStoreConfig.(SCDynamicStoreConfig.java:39) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:190) at com.myclass.getJARFromClassForName(JavaId.java:510) at com.myclass.getJARUrl(Id.java:550) at com.myclass.collectInformation(Graph.java:366) at com.myclass.createNode(Graph.java:166) at com.myclass.Graph.(Graph.java:143) at com.myclass2.run(myclass2.java:246) at java.lang.Thread.run(Thread.java:745)

So as you can see in the error we have this strange exception that cannot be catched even with a generic catch like in my code and I cannot understand why it has been raised and what actually is this osx library (I am on linux)

EDIT: The only thing that I found is this link http://ift.tt/29brtgr but is in german and so I read it with google translate and I don't know if I got it right but is basically saying that the classes listed there cannot be reproduced with Class.forname() itself.

Is it true? Is there a reason why this cannot be loaded with reflection or am I doing something wrong?





Creating Func body dynamically

See the sample below:

var factoryType = typeof(Func<>).MakeGenericType(someType);

I would want to create the function body where an instance of someType will be created using a DI container.

The idea is to configure the DI container so that it can inject Func<SomeClass> into other classes.

How can this be done?





mardi 28 juin 2016

In a Swift extension, get the actual calling object?

Say we are in an instance of SomeClass, consider this simple call

NSNotificationCenter.defaultCenter().addObserver(
 self,
 selector: #selector(SomeClass.fixer(_:)),
 name:"FixerNote",
 object:nil)

Say we decide to make an extension to save typing, that will look like this ...

"FixerNote".does( #selector(SomeClass.fixer(_:)) )

Here's the extension...

public extension String
    {
    func does(s:Selector)
        {
        NSNotificationCenter.defaultCenter().addObserver
           .. here, you need the actual SomeClass that called us .. ,
            selector: s,
            name:self,
            object:nil)
        }
}

How to know which object called the extension??

(NB, I realize you could pass it in or use it as the base :) )

Can you do such a thing in Swift? Can you find out who called you?

A similar issue: in the example, could you find out what object a selector ("s" in the example) belongs to ??





Obtain Properties in Child Classes in IEnumerable of Base Class

If I have an collection of a given entity, I'm able to obtain the properties for entity like so:

var myCollection = new List<Foo>(); 
entities.GetType().GetGenericArguments()[0].GetProperties().Dump();

However, I'm having some difficulties listing out the properties if my collection is an IEnumerable of a base class and populated with derived classes.

public class Foo
{
    public string One {get;set;}
}

public class Bar : Foo
{
    public string Hello {get;set;}
    public string World {get;set;}
}

// "Hello", "World", and "One" contained in the PropertyInfo[] collection
var barCollection = new List<Bar>() { new Bar() };
barCollection.GetType().GetGenericArguments()[0].GetProperties().Dump();

// Only "One" exists in the PropertyInfo[] collection
var fooCollection = new List<Foo>() { new Bar() };
fooCollection.GetType().GetGenericArguments()[0].GetProperties().Dump();

Is there anyway to get the types of the items in the collection even though the collection is declared using the base class?





Reflection removal on InfraRed Temp. spatial data in R

I got lots of spatial temperature data as matrix (227 x 454). The data represents temperatures recorded by an IR camera on the water surface. When plotting the data I get two reflections, from the camera and from a tree which was above the camera. In addition, I also get a heat signal which represents warm water patches on the water surface (this is on what I am interested).

So far I have managed to remove the reflection from the camera using SVD. However I cant manage to remove the tree reflection from the image, I have tried SVD, FFT, Klusters...I also wanted to use Wavelets but my data matrix is not squared. Do you know which method should I use in order to get rid of that reflection? or any suggestions or ideas to improve my image?

Here are the original plot and the data after the SVD ( without camera reflection, circle in the middle). On the SVD image, the area that is interesting for me is the warm water on the top right of the plot, the rest (bottom warm area and the yellowish/greenish areas on the most of the left side of the plot) belong to the tree reflection.

original plot

after SVD plot

Thanks a lot for your input :)

cheers!

amaia





Check if a classes Property or Method is declared as sealed [duplicate]

This question already has an answer here:

I've got following derivations:

interface IMyInterface
{
    string myProperty {get;}
}

class MyBaseClass : IMyInterface // Base class is defining myProperty as abstract
{
    public abstract string myProperty {get;}
}

class Myclass : MyBaseClass // Base class is defining myProperty as abstract
{
    public sealed override string myProperty 
    {
        get { return "value"; }
    }
}

I would like to be able to check if a member of a class is declared as sealed. Somewhat like that:

PropertyInfo property = typeof(Myclass).GetProperty("myProperty")

bool isSealed = property.GetMethod.IsSealed; // IsSealed does not exist

Sense of all this is to be able to run a test, that checks the code/project for consistency.

Following test fails:

PropertyInfo property = typeof(Myclass).GetProperty("myProperty")

Assert.IsFalse(property.GetMethod.IsVirtual);





C# Reflection how to get the where clause for a generic type [duplicate]

This question already has an answer here:

(sorry if this question exists, but its proven hard to search)

I'm tasked with writing wrapper code for a 3rd party library full of static methods. (to make it more testable) I've written code that uses reflection to tear apart all the calls (over 3000) and write classes, interfaces and wrapping methods/properties for all of it. We will also get updates on this library from time to time, so I don't want to do this by hand every time.

But I do not know how to get the where clause at the end of the method. Example:

public static T Load<T>(string path) where T : Object
{
  // blah blah blah
}

using only reflection, how do I extract "where T : Object" so I can enter it in my generated code?





A list of all active ThreadLocal

How can I get a list of all references that are currently held in ThreadLocal or ThreadStatic storage?

I.e. all objects that cannot be garbage collected because some thread holds a reference within its thread-local storage.

Can I use reflection to find those instances, or at least their total size, without knowing their names or types?

Or failing that, some way to show them in Visual Studio 2010? (I am looking for something besides a full-blown memory profiler)

My motivation is this: I just had a very nasty memory leak where the contents of a ConcurrentBag where held by various ThreadPool threads, even though the original ConcurrentBag had long been gone out of scope and garbage collected. Although I squashed this particular bug, I want to find out if there are more such bugs lurking around.

Ideally I would like some way to periodically log the number of objects held by thread-local storage, and their size, at runtime.





Why does accessing a private member of an outer class using reflection throw IllegalAccessException?

Given the code example below, why does theAnswer.get( outer ) throw an IllegalAccessException?

Exception in thread "main" java.lang.IllegalAccessException: Class com.dpd.Outer$Inner can not access a member of class com.dpd.Outer with modifiers "private"

According to this SO answer, I'd expect it to work as the access does happen "(...) from a class that is allowed to access it".

import java.lang.reflect.Field;

public class Outer
{
   private int theAnswer = 42;

   public static class Inner
   {
      public void accessDirectly( Outer outer )
      {
         System.out.println( outer.theAnswer );
      }

      public void accessUsingReflection( Outer outer ) throws NoSuchFieldException,
                                                      SecurityException,
                                                      IllegalArgumentException,
                                                      IllegalAccessException
      {
         Field theAnswer = Outer.class.getDeclaredField( "theAnswer" );
         // Of course, uncommenting the next line will make the access using reflection work.
         // field.setAccessible( true );
         System.out.println( theAnswer.get( outer ) );
      }
   }

   public static void main( String[] args ) throws NoSuchFieldException,
                                           SecurityException,
                                           IllegalArgumentException,
                                           IllegalAccessException
   {
      Outer outer = new Outer();
      Inner inner = new Inner();
      inner.accessDirectly( outer );
      inner.accessUsingReflection( outer );
   }
}





check interface value nil in go lang with out using reflect

I need to check an interface value nil .

But ,by using reflect it is giving error as reflect: call of reflect.Value.Bool on struct Value.

Through nil it is not giving an error for nil value.





Call a method by reflection in java

I want to call a method which is given to me as a string: "methodnam" and i know it's class name Aclass.

I have object(ObInp) as an input to the method and an object(ObOut) which will be the output.

I am not getting how i will call this method by reflection. I got many links related to this but i am not able to solve this.





How to check if a method overrides a method of a given interface?

Assume we have the following interface and implementations:

interface Matcher<T>{
     boolean matches(T arg);
}

class NumberMatcher<T extends Number> implements Matcher<T>{
    @Override
    public boolean matches(T arg){...}
}

class StringMatcher extends Matcher<String>{
   @Override 
   public boolean matches(String arg){ ...}
}

class CustomMatcher extends NumberMatcher<Integer> {
    public boolean matches(String arg){...}

    @Override
    public boolean matches(Integer arg){...}
}

What I need is the type of the parameter of the matches(T) method of a given Matcher implementation.

NumberMatcher numberMatcher = new NumberMatcher<Long>();
StringMatcher stringMatcher = new StringMatcher();
CustomMatcher customMatcher = new CustomMatcher();
Matcher<Date> dateMatcher = new Matcher<Date>(){...};

getArgumentType(numberMatcher) // should return Number.class
getArgumentType(stringMatcher) // should return String.class
getArgumentType(customMatcher) // should return Integer.class
getArgumentType(dateMatcher ) // should return Object.class

Here is a implementation that works except of the CustomMatcher case, cause it fails to detect the overriden matches(..) method and returns String.class instead of Integer.class.

Class<?> getArgumentType(Matcher<?> matcher) {
    Method[] methods = matcher.getClass().getMethods();
    for (Method method : methods) {
        if (isMatchesMethod(method)) {
            return method.getParameterTypes()[0];
        }

    }
    throw new NoSuchMethodError("Method 'matches(T)' not found!");
}

private boolean isMatchesMethod(Method method) {
    if (!isPublic(method.getModifiers()))
        return false;

    if (method.getParameterCount() != 1)
        return false;

    return method.getName().equals("matches");

}





lundi 27 juin 2016

Difference betwwen type.GetProperties and type.GetProperty

Can you please explain the difference between type.GetProperties and type.GetProperty with an implementation





Passing parameters dynamically into Method.Invoke

I have methods in a class

public class ReflectionClass {
    public int add(int a, int b) {
        return a + b;
    }
    public int add(int a, int b, int c) {
        return a + b + c;
    }
    public String concatenate (String a, String b, String c){
        return a + b + c;
    }
}

I'm trying to call these methods through reflection. All I have in hand are - the method name and the parameters. Is there a way to pass the parameters into the Method.Invoke() method dynamically based on the number/type of parameters I have in hand?





Getting a PropertyInfo of a dynamic object

I have a library that is doing a bunch of reflection work relying on the PropertyInfo of the classes it receives (to get and set values).

Now I want to be able to work with dynamic objects, but I can't find how to get the PropertyInfo of a dynamic's properties. I've checked the alternatives, but for those I'd need to change everywhere I use PropertyInfo to get/set values.

public void Mapping(dynamic entity)
{
    // - Always null
    PropertyInfo p = entity.GetType().GetProperty("MyID");
    // - Always null
    PropertyInfo[] ps = entity.GetType().GetProperties();
}

Is it possible to get or create a PropertyInfo somehow just to be able to use it's GetValue() and SetValue() on a dynamic object?





Internal class masked by object

I have below in C# 4.0

Assume that a class (B)'s public function has the return line

return (object)(new List<A>{Some elements})

where A is an internal and sealed class. I cannot change the code of A or B.

After I call this function in B, how do I find the first element of that list. C# does not let me cast that list back into List<A> because A is internal.

If this doesn't make sense, I can provide more detail. Thanks!





How to get files in resources folder using system.reflection's GetManifectResourceNames

I have migrated my application from VS2008 to VS2015.I have a requirement to fetch resources which are there in my Resources folder in the application.

var assembly = System.Reflection.Assembly.GetExecutingAssembly();
string[] names = assembly.GetManifestResourceNames();

Above code returned all the Xls files in Resources folder in my application Before migration.Now its not returning the same files.Do i need to configure anything.





Get static property through reflection .NET

I've seen this answered already, but it hasn't worked for me. I'm trying to access a (non-static) class static property from the base class, from an derived instance.

In the base class:

Type type = this.GetType();
PropertyInfo propInf = type.GetProperty("DirectoryCode", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);

Here propInf is null (type is the derived class type).

In the derived class:

public class DTGCSMissonParameters : ModelBase
{
   public static ushort DirectoryCode = (ushort) DIR.MISSION_PARAMETERS;

Thanks





How to create an instance of the EntityDescriptor class

For testing purposes I need to create an instance of the EntityDescriptor class. This cannot be done directly, cause the constructor is not public.

That's why I try use reflection to create the instance.

EdmModel model = new EdmModel();
var constructors = typeof(EntityDescriptor).GetConstructors(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
var entityDescripto = constructors[0].Invoke(new object[] { model }) as EntityDescriptor;

I know, that the single constructor of the class takes one argument of type EdmModel. But when I call the above code I the following exception:

System.ArgumentException : Das Objekt mit dem Typ "Microsoft.Data.Edm.Library.EdmModel" kann nicht in den Typ "System.Data.Services.Client.ClientEdmModel" konvertiert werden.

But I cannot find anywhere the class ClientEdmModel. Does anybody has an idea?





dimanche 26 juin 2016

Remove a delegate from an event

I have an event as follows:

public event EventHandler<CustomEventArgs> RaiseCustomEvent;

Here is some code to remove a delegate from the above event that I have working:

public void RemoveDelegate(Delegate del)
{
    RaiseCustomEvent -= (EventHandler<CustomEventArgs>)del;
}

Here is some code that I have written to remove a delegate where I know the event name:

public void RemoveRaiseCustomEventDelegate(Delegate del, string eventName)
{
    var field = this.GetType().GetField(eventName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField);

    var fieldValue = field.GetValue(this) as EventHandler<CustomEventArgs>;
    fieldValue -= (EventHandler<CustomEventArgs>)del;
}

In the above code, the fieldValue is set to null, however, when the event is raised, there is still a subscriber.

Can I please have some help to remove a delegate from an event, where I only have the event name?





Passing list values as parameters to getdeclaredmethod in reflection java

I have a method name given as a string.I have to call that function through reflection.

I know we can use getDeclaredMethod(). I have input as list of objects to the method.But i am not getting how to pass the parameters to the function.





ClassCastException thrown when calling .newInstance

I have a program in which I am loading classes dynamically in order to pick which libraries to use at runtime. For some reason, when attempting to instantiate a direct implementer of the interface needing implementation, it throws a ClassCastException. The buggy line can be found here, but reference for below is the process which I use to load the class:

  1. The program starts, unaware of the separate .jars (held in another folder).
  2. The Collector class loads all the separate .jars' classes and dumps their references in an ArrayList.
  3. Another class, Prioritizer, looks in a .json file for the name of what classes to load to do which job, referring to the interface as a caster. This class then queries the Collector class for the object reference.
  4. The main class calls on the Prioritizer to find the right class reference for an implementation of LanguageDetail, which it then attempts to cast, then instantiate, and call a method from.

In step four, however, the cast fails and an exception is thrown.

The offending line is this:

Collector.prioritizer.get(LanguageDetail.class).newInstance().reportLanguageDetails();

However, this throws the following exception:

java.lang.ClassCastException: com.VTC.laura.test.TestLangDetails cannot be cast to com.VTC.langlib.data.LanguageDetail
    at com.VTC.laura.core.Main.main(Main.java:23)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)

Even though TestLangDetails is a direct implementation of LanguageDetail.

What am I doing wrong to cause this error, and how can I fix it?





Invoke Method with reflection pass through parameters and receive a return value

Hello as the question describes im trying to invoke a method through reflection, which is fine and all if it was a void type. but string, bool, etc is not working. also with a return type. i haven't been able to find any useful references.

i have a Test Class which i used to call some test methods. all the void ones had worked fine. but the others were not calling at all.

internal class Test
{
    public static void Print()
    {
        Console.WriteLine("Test");
        Console.WriteLine("Testing an invoke method");
    }

    public static void CalcData()
    {
        Console.WriteLine("Test");
    }

    public static void DoSomething(int c, float f)
    {
        Console.WriteLine("Test");
    }

    public static string TestString(string s, int p, char f)
    {
        return "Happy Days";
    }
}

in my Main Method i would call t.GetMethod("Print").Invoke(t, null);

but i am unsure how i would call to pass in a parameter or even obtain a return type.

some insight on this would be greatly appreciated.





Set data by response from a server

I need implement a command (part of our protocol), after sending the request I am getting 130 parameters as one string divided by special character. I want to implement an efficient way in creating several objects depending on this response. I thought about it and there are two methods I could think of:

  1. The naive way, just define 130~ variables and assign them to the constructors of the objects.
  2. I thought of a way to use reflection, each parameter will be assigned by the definition of the object that I want to create. But there are two main issues with this approach:

    1. From my experience I know it would take more time than usually assign variables and allocate objects.
    2. By getting the fields of the object using data.getClass().getDeclaredFieldsthe declared files are returned in different order than I am expecting them to be. Is there a way the fields could be returned as declared in the class?

This is the code I done so far:

private Object getExamClassData(Class<?> examClass, String[] examFileFrags, int startIndex, int endDataIndex)
{
    ARRefraction data = null;
    try
    {
        Constructor<ARRefraction> ctor = (Constructor<ARRefraction>) ARRefraction.class.getConstructor();
        data = ctor.newInstance();    
        Field[] fields = data.getClass().getDeclaredFields();
        int fIndex = 0;
        for (fIndex = 0;fIndex<fields.length;fIndex++)
        {
            try
            {
                Field field = fields[fIndex];
                field.setAccessible(true); 
                if(field.getType().isAssignableFrom(Float.TYPE))
                {
                    field.set(data, Float.parseFloat(examFileFrags[fIndex+startIndex]));
                }
                else if(field.getType().isAssignableFrom(Integer.TYPE))
                {
                    field.set(data, Integer.parseInt(examFileFrags[fIndex+startIndex]));
                }
                else if(field.getType().isAssignableFrom(String.class))
                {
                    field.set(data, examFileFrags[fIndex+startIndex]);
                }

            }
            catch (IllegalArgumentException e1)
            {
                e1.printStackTrace();
            }
            catch (IllegalAccessException e1)
            {
                e1.printStackTrace();
            }
        }
        return data;
    }
    catch (java.lang.InstantiationException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IllegalAccessException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (NoSuchMethodException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IllegalArgumentException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (InvocationTargetException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;

}

ARRefraction object

 public class ARRefraction implements Parcelable
{
    private float   _sFar;
    private float   _cFar;
    private int     _aFar;
    private float   _pFar;
    private float   _puFar;

    private float   _sNear;
    private float   _cNear;
    private int     _aNear;
    private float   _puNear;
    private float   _pNear;

    private String  _vaFar;
    private float   _hoFar;
    private float   _qFar;
    //
    private String  _vaNear;
    private float   _hoNear;
    private float   _qNear;

    private float   _add;
}





samedi 25 juin 2016

Dynamic Import - Python - Call function

I am having some trouble with dynamically importing Classes and attempting to run functions in said classes. This is my problem, specifically.

I have a python script dyn_imports.py in a director called dynamic_imports. Inside this folder is a subdir called scripts. In this scripts directory there is an __init__.py and a python class called AbhayScript.py. In the class AbhayScript, there is a function called say_hello()

My objective is: From dyn_imports.py, I would like to be able to import scripts.AbhayScript and call the function say_hello() in AbhayScript

So far, I have attempted a variety of options including __import__, importlib.import_module and pydoc.locate. All of these options give me access to the module AbhayScript but when I try a getattrs() or try to call the object, I get an error stating that its not callable or has no attribute.

dyn_imports.py - One of my experiments

myclass = 'scripts.AbhayScript'

import importlib
mymod = importlib.import_module(myclass)
mod,newclass = myclass.rsplit('.',1)
ncls = getattr(mod,newclass) #throws an AttributeError that 'str' object has no attribute

AbhayScript.py code

class AbhayScript(object):

    def say_hello(self):
        print 'Hello Abhay Bhargav'

The directory structure is as follows

Directory Structure of Project

The init.py in the scripts folder is empty.

I have attempted nearly all the solutions in Stackoverflow, but I am a little flummoxed by this one. What am I doing wrong?





Reflection assembly load error (RuntimeBinderException)

I need to load DLL in runtime and call TXMod.Init()
This exception is throwing every time:

An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll
Additional information: Member 'Mod1.TXMod.Init()' cannot be accessed with an instance reference; qualify it with a type name instead

error screenshot

Can you help me?





Why does my list of PropertyInfo shows count=0 [duplicate]

This question already has an answer here:

I have a class called "summoners" with properties :

public string Name;
public string Id;
public int summonerLevel;
public string division;

public string tier;
public int leaguePoints;

To debug, i wanted to create a List<PorpertyInfo> and store every property name in it, i have :

        public void listProperties()
    {
        List<PropertyInfo> t = new List<PropertyInfo>();

        foreach (var attr in this.GetType().GetProperties())
        {
            t.Add(attr);
        }
    } //-> breakpoint

I placed a brakepoint and it tells me that there is no value in "t"





Calling public static method at runtime calling Mono.Cecil created assembly does not work

I'm using Mono Cecil to create a new assembly at runtime. When calling the public static MyMethod() method on the created assembly if does not return anything, but the contructor of the new assembly type does output to the console. Any idea what I'm doing wrong here since there is no output from calling MyMethod() in my created assembly? There are no errors when I call the newly created static, I expected "New Result!" after "Loaded" and before the two "Do Something".

using System;
using System.Linq;
using System.Reflection;
using Mono.Cecil;
using Mono.Cecil.Cil;
using MyLib;

namespace MonoCecil_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var assembly1 = AssemblyDefinition.ReadAssembly("MyLib.dll");
            TypeDefinition type1 = assembly1.MainModule.Types.Single(x => x.Name == "TestClass");
            MethodDefinition foundMethod = type1.Methods
                .OfType<MethodDefinition>().Single(m => m.Name == "MyMethod" && m.Parameters.Count == 0);
            ILProcessor worker = foundMethod.Body.GetILProcessor();
            foundMethod.Body.Instructions.Clear();
            Instruction ins1 = worker.Create(OpCodes.Ldstr, "New Result!");
            Instruction ins2 = worker.Create(OpCodes.Ret);
            worker.Append(ins1);
            worker.Append(ins2);
            assembly1.Write("Test.MyLib.dll");

            Assembly assembly2 = Assembly.LoadFrom("Test.MyLib.dll");
            Type type2 = assembly2.GetType("MyLib.TestClass");
            object instanceOfMyType = Activator.CreateInstance(type2); 

            // Mock public static
            MethodInfo method = type2.GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Static);
            method.Invoke(null, null);

            // Normal call
            string result = TestClass.MyMethod();
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }

}

MyLib.dll:

using System;

namespace MyLib
{
    public class TestClass
    {
        public TestClass()
        {
            Console.WriteLine("Loaded");
        }

        public static string MyMethod()
        {
            string result = "Do Something";
            Console.WriteLine(result);
            return result;
        }
    }
}

Output is:

Loaded
Do Something
Do Something





Dynamic Binding of Dropdownlist value and Key Value pair value from XML, Using XMLparser and reflection

I have to parse and dynamically load and set the values from XML, using xml parser and reflection. The sample XMl is like below:

Test XML :

<?xml version="1.0" encoding="utf-8"?>
<form>
      <ID>123456</ID>
      <Name>Test</Name>
          <UIControls>
              <Control>
                  <FullyQualifiedClass>TextBox</FullyQualifiedClass>
                  <ID type="STRING">tb1</ID>
                  <Name type="STRING">ActivityCode</Name>
                  <Value/>
                  <DataType type="FieldDataTypes">STRING</DataType>
                  <HtmlAttributes collection="KeyValuePair[string, string]">b</HtmlAttributes>
              </Control>
               <Control>
                  <FullyQualifiedClass>DropdownListownList</FullyQualifiedClass>
                  <ID>ddl1</ID>
                  <Selection item="CollectionItem">
                      <CollectionItem>
                          <Value>one</Value>
                          <DisplayText>ONE</DisplayText>
                          <Selected>FALSE</Selected>
                      </CollectionItem>
                      <CollectionItem>
                          <Value>two</Value>
                          <DisplayText>TWO</DisplayText>
                          <Selected>true</Selected>
                      </CollectionItem>
                  </Selection>
              </Control>
          </UIControls>
</form>

Now, I need to iterate Dropdown list value and KeyValue pair value and set it into Form's Controlls dynamically using reflection. I can't set the value statically, since the value of the xml will be changed and I can use the same concept every where in the application. waiting for your valuable and earliest response. Thank you





Android reflection access layout

Hello I am just want to know if I can access the layout of original class using reflection

i.e if I have a method like this

public void setData(int id){
editText1.setText(id+"");

}

and in refliction class , where c is the .class which I send(original class)

Object obj = c.newInstance();
        Method method1 = c.getMethod("setData", new Class[]{Integer.TYPE});
        method1.setAccessible(true);
        method1.invoke(obj, 3);

this code is working in the inside class(reflection one) but outside in the original it's like I didn't change anything





Get static field from nested class via expression tree

I have these classes:

public class Entity
{
    public static readonly EntitySchema Schema = new EntitySchema();
}

public abstract class BaseSchema
{
    public abstract string Name {get;}
}

public class EntitySchema : BaseSchema
{
    public override string Name => "Schema";
}

Now, I want to access EntitySchema.Name from a method, which does not know anything about Entity (cannot access the static field).

I could do this with reflection:

static BaseSchema GetSchema<T>()
{
    var pr = typeof(T).GetField("Schema");
    var schema = pr.GetValue(null);
    return schema as BaseSchema;
}

but compared to a direct call Entity.Schema.Name the reflection version is 50x slower.

Is there a way to convert the reflection version into a Expression Tree and precompile the call?





vendredi 24 juin 2016

Go, Why shouldn't use "this" for method receiver name

I use VS Code Go extension.

Here's my code

func (this *MyClass) Xxx() error {}

And It's mention me this

exported method MyClass.Xxx should have comment or be unexported receiver name should be a reflection of its identity; don't use generic names such as "me", "this", or "self";





Nested reflection

I'm trying to set a value that's nested within another class. There are a lot of levels, which are starting to confuse me, and I need a second (or third) opinion.

The two named classes at the bottom are third party classes from Ivi.Visa.Interop.dll (a VISA communication library). I do not have access to their source code.

Visually, it looks like this:

Parent (A)

temp = new B();
temp.session = new FormattedIO488();
temp.session.IO = ...
temp.session.IO.TerminationCharacterEnabled = ...

Subclass (B) : Parent (A)

...
public dynamic session
...

FormattedIO488: IFormattedIO488

...
IMessage IO { get; set; }
...

IMessage: IBaseMessage

...
    [DispId(1610743814)]
    bool TerminationCharacterEnabled { get; set; }
...


The problem: I want to set TerminationCharacterEnabled, but during Runtime, the system can't find the property. It can find FormattedIO488.IO, but it can't find any sub-properties.

I have observed that IO is null after creating a new FormattedIO488, but I can't create a new instance of the abstract class IMessage.

I do not have the issue when I do something like this:

FormattedIO488 temp = new FormattedIO488()
temp.IO = ...
temp.IO.TerminationCharacterEnabled = ...


I've scoured the internet and StackOverflow, trying a bunch of different solutions to get something, but so far I haven't found a solution. Any help or tips would be highly appreciated.





How to iterate over methods of a class and then iterate over returned object and call another method ?

Lets say I have following class:

public class ExampleList{
  // fields

  List<A> getAList(){}
  List<B> getBList(){}
  List<C> getCList(){}
  //A, B and C all extends class X with field num
}

public class Example{
  ExampleList getExampleList(){}
}

public class Test{
  main(){
    Example example = //from somewhere I get object;

    List<A> lA = example.getExampleList().getAList();
    List<B> lB = example.getExampleList().getBList();
    List<C> lC = example.getExampleList().getCList();

    //Currently I am doing
    if(lA != null) { 
      //iterate and call getCount(num)

    if(lB != null) { 
      //iterate and call getCount(num)

    if(lC != null) { 
      //iterate and call getCount(num)

  }

  getCount(int num) { //do something }
}

What I would like to do is dynamically iterate over all the methods of ExampleList and call getCount(num) only once. like:

main(){
  for ( Methods mList : Methods)
     for ( X x: mList )
       getCount(x.getNum);
}

I know I can create a generic method which takes List of anything that extends X and I can iterate each List there and call getCount(). But I also want to be able to iterate over methods of a class. Is there a way I can achieve this ?

I know I can get list of getter methods via reflection. But I don't know how I can use it in this situation.

BTW this question is not about how to get list of methods from using reflection. It is more about how to use it or how reflection works.





How to compare instances of Type for equality

Given two instances of Type:

Type type1;
Type type2;

How to can I check if they are equal?

I'm calling toString and comparing their values, as such:

if (type1.toString().equals(type2.toString())) {
    ....
}

I tested it with multiple and nested parameterized types and so far it seems to be consistent. But I would like to know if there is a formal way to do it.





C# Reflection Additional information: Object reference not set to an instance of an object. (NullReferenceException)

I'm working on stream data operators and need to check if object from List haves field named like content

string field1

public ResultList joinLists<T, U>(List<T> categories, List<U> products, string field1, string field2)
    {
        ResultList resList = new ResultList();
        bool headeres = false;

            List<T> result1 = new List<T>();
            foreach (var cat in categories)
            {
                if (cat != null)
                {
                var name = cat.GetType().GetField(field1, BindingFlags.DeclaredOnly |
                                  BindingFlags.Public | BindingFlags.NonPublic |
                                  BindingFlags.Instance | BindingFlags.GetField).Name;
                    if (name == field1)
                    {
                        result1.Add(cat);
                    }
                }
            }

Debugger shows that exception appears on line

var name = cat.GetType().GetField.....

I've looked for that problem for quite a bit of time and i really don't know what to do, I've double checked if good List is passed, so as if field1 corresponds to that exect object type, everything looks fine, but it'll probably be some hyper newbie mistake.

Thanks for reading & comments





Getting parameter names and parameter types through reflection

I'm attempting to write a utility method which should be capable of executing any method. Consider this for example. I have a class with the following methods:

ClassA
   void Method1 (int a)
   void Method2 (int b, string s, long l)
   Object Method3 (string a, Object o)
   List<string> Method4 (double d, List<string> sList)

Now, in a different class, I have a method execute

ClassB
   void execute (string methodName, Map<string, object> params)

methodName will contain the required method's name (Method1/Method2/Method3/Method4) and params will have the parameters to be passed into the method. params will be a dictionary object like these for Method1 to Method4 respectively:

<Key>                     <Value>
"int"                     1

Or

"int"                     2
"string"                  "test"
"long"                    1234567896557

Or

"string"                  "abc"
"object"                  someClassObject

Or

"double"                  456.764
"List<string,string>"     someListObject

I know we can get the class and the methods through reflection, but is it possible to get the parameters to those methods? Along with the methods, I need to know what parameters (types and values) need to be passed into that method, so that I can lookup the params dictionary object and pass the correct parameters into the method. I have heard about paranamer, but want to know if this is possible without any external jars?





Loop through all controls on form and if event exists on control add handler to control

Pseudo code of how I expect it to work but I am not sure what .net methods I need to call to accomplish this.

    Dim specifiedEvent = "MouseDown"
    Dim handler = handler
    For Each control As Control in form.controls
      If control has specifiedEvent Then

        control.specifiedEvent addhandler handler

      End If 
    Next

c# is linked because it can be easily converted to vb





Change Base class field value from Derived

I have a question if it is possible to change field value of the base class, from derived class. In my case, i have two classes base class with windows form RichTextBox, and I want use derived class to clear RichTextBox.

Base class:

    class Program : Form
{
    public System.Windows.Forms.RichTextBox rtfCode;

    public Program()
    {
        rtfCode.Text = "some text";
    }
    static void Main(string[] args)
    {
        Program a = new Program();
        Console.WriteLine(a.rtfCode.Text);
        DerivedClass f = new DerivedClass();
        Console.WriteLine(a.rtfCode.Text);

    }

}

My Derived class

    class DerivedClass:Program
{
    public DerivedClass()
    {
        base.rtfCode.Clear();
        Console.WriteLine(base.rtfCode.Text);
    }
}

when i execute program on console i see only old tex.





Java: Changing a method at runtime from outside

First the situation:
I have a foreign jar-File, let's say a game. I, myself, am located in another jar-File, the injector.
I have managed hooking to the game-jar's JVM, thus sharing the same space etc. I have also managed that my injector gets called at injection, thus being able to interact.

Let's say the game has a class and method named Game#foo(). I want to inject own code into the method of such an object.
For example a method bar() should be called everytime foo() gets called.

I face several problems:

  • How can I retrieve the Game-object, as I'm already at runtime?
  • How to manipulate the method?

In the end it could look like:

Game game = getGameObject();
game.injectBarIntoFoo();

The situation is strict, the foreign game-jar already is at runtime, I can not load it myself. My injector must start in Java, however, I would have no problem switching to C via JNA/JNI if there's an easy solution.

One could say I'm trying to do something like a DLL-Injection for jar-Files.

Remarks:
I already have heard of hotswapping, JRebel, JavaAssist and of course the Reflection API. But it seems that they all require the Game-object to be created by myself, while setting up a special environment. However, the Game-jar already is at runtime when my stuff comes into play.
Please note that patching the Game-jar prior to execution via ByteCode-Manipulation is also not a favorable solution for me, though possible.





How to call wcf service with out added service reference using channel factory

Can any one help me on this. "How to call wcf service with out added service reference using channel factory".

I have used this code :

        BasicHttpBinding binding = new BasicHttpBinding();
        EndpointAddress address = new EndpointAddress("");
        ChannelFactory factory = new ChannelFactory<IUnityServiceChannel>(binding, address);
        UnityServiceClient channel = new UnityServiceClient();
        string token = channel.GetSecurityToken(svcUsername, svcPassword);

But I want to create the IUnityServiceChannel run time. I don't have any information about the IUnityServiceChannel.

So can you help me how to crate interface using reflection or some thing else.





Checking loaded class has annotations in web application

I wrote my class annotation:

@Documented
@Target(ElementType.METHOD)
@Retention(RUNTIME)
public @interface CAnnotation {
   String name();
}

Next i wrote my lib:

public class Customized implements Serializable{

@CAnnotation(name="getCustomer")
public String getCustomer(int id){
    return "ABCABC";
} 
}

Now I read in web application Customized.jar like this:

public void inir(){
        System.out.println("---------------");
        System.out.println("---------------");
        for (Method metoda : getUserClass().getMethods()) {
            System.out.println("---------------"
                    + "\n" + metoda.isAnnotationPresent(CAnnotation.class)
                    + "\n" + metoda.getName()
            );
            for (Annotation annotation : metoda.getAnnotations()) {
                System.out.println("---------------"
                        + "\n" + annotation
                );
            }
            if (metoda.getAnnotation(CAnnotation.class) instanceof CAnnotation) {
                System.out.println("---------------");
                System.out.println(":" + metoda + " " + metoda.getAnnotation(CAnnotation.class).name());
                System.out.println("---------------");
            }
        }
    }


    public  Class getUserClass() {
        File file = new File("./Customized.jar");
        try {
            JarFile jarFile = new JarFile(file.getPath());
            Enumeration e = jarFile.entries();
            URL[] urls = {new URL("jar:file:" + file.getPath() + "!/")};
            URLClassLoader cl = URLClassLoader.newInstance(urls);
            while (e.hasMoreElements()) {
                JarEntry je = (JarEntry) e.nextElement();
                if (je.isDirectory() || !je.getName().endsWith(".class")) {
                    continue;
                }
                String className = je.getName().substring(0, je.getName().length() - 6);
                className = className.replace('/', '.');
                Class c = cl.loadClass(className);
                return c;
            }
            return null;
        } catch (IOException | ClassNotFoundException ex) {
            System.out.println("" + ex);
            return null;
        }

    }

And in console I get this:

Info:   ---------------
Info:   ---------------
Info:   ---------------
false
getCustomer
Info:   ---------------
...

I checked it in desktop application and i get "true" So what is a difference between web and desktop app, in the web appliction dont have my annotations? What am I doing wrong? I checked a file on server using the jd-gui(Java Decompiler) and customized.jar have annotations. I didn't add anythjing in web or faces-config.





jeudi 23 juin 2016

Java: Can we iterate over all methods of the class?

Lets say I have following class:

public class ExampleList{
  // fields

  List<A> getAList(){}
  List<B> getBList(){}
  List<C> getCList(){}
  //A, B and C all extends class X with field num
}

public class Example{
  ExampleList getExampleList(){}
}

public class Test{
  main(){
    Example example = //from somewhere I get object;

    List<A> lA = example.getExampleList().getAList();
    List<B> lB = example.getExampleList().getBList();
    List<C> lC = example.getExampleList().getCList();

    //Currently I am doing
    if(lA != null) { 
      //iterate and call getCount(num)

    if(lB != null) { 
      //iterate and call getCount(num)

    if(lC != null) { 
      //iterate and call getCount(num)

  }

  getCount(int num) { //do something }
}

What I would like to do is dynamically iterate over all the methods of ExampleList and call getCount(num) only once. like:

main(){
  for ( Methods mList : Methods)
     for ( X x: mList )
       getCount(x.getNum);
}

I know I can create a generic method which takes List of anything that extends X and I can iterate each List there and call getCount(). But I also want to be able to iterate over methods of a class. Is there a way I can achieve this ?





Java: determine if a static method is called from an instance or statically

In Java, is it possible to determine whether a static method is called from either an instance of the object, or statically (SomeClass.method())?

To give you an a better idea of what I'm talking about, take look at this code below:

public class SomeClass {

    public static void staticMethod() {

        if (/*called from instance*/) {
            System.out.println("Called from an instance.");
        } else if (/*called statically*/){
            System.out.println("Called statically.");
        }
    }

    public static void main(String[] args) {
        new SomeClass().staticMethod();//prints "Called from an instance."
        SomeClass.staticMethod();//prints "Called statically."
    }

}

I understand it isn't good practice to call a static method from an instance, but still, is it possible to differentiate between these two calls? I was thinking that the Reflection API probably holds the key to this.





Set property value of Dictionary

I'm building a Firebase client that Synchronize Firebase tree with C# object. Firesharp is returning JSON data that represent the Firebase object, finally casting JSON into C# using NewtonSoft. I've done the casting and having a problem updating properties, here is C# object structure:

public class FirebaseObject
{
    public string Path { get; set; }
    public ServerTree Data { get; set; }
}

public class ServerTree
{
    public Dictionary<string, Agent> Agents { get; set; }
    public Dictionary<string, Report> Reports { get; set; }
    public Dictionary<string, Store> Stores { get; set; }
    public Dictionary<string, Dictionary<string, UserReport>> UserReports { get; set; } // <UserID, <ReportID, ReportData>>
    public Dictionary<string, User> Users { get; set; }

    public void ClearTree()
    {
        Agents = new Dictionary<string, Agent>();
        Reports = new Dictionary<string, Report>();
        Stores = new Dictionary<string, Store>();
        UserReports = new Dictionary<string, Dictionary<string, UserReport>>();
        Users = new Dictionary<string, User>();
    }
}

public class Store
{
    public string Id { get; set; }
    public string Name { get; set; }
    public int Order { get; set; }
}

public class Agent
{
    public string Id { get; set; }
    public string FingerPrint { get; set; }
    public DateTime TimeStamp { get; set; }
}

public class User
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public DateTime LastLogin { get; set; }
}

public class Report
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string SqlQuery { get; set; }
    public Parameters Parameters { get; set; }
    public int Order { get; set; }
}

public class Parameters
{
    public bool DateRange { get; set; }
    public bool MultipleSource { get; set; }
    public bool TimeRange { get; set; }
}

public class UserReport
{
    public string UserId { get; set; }
    public string ReportId { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public DateTime LastExecution { get; set; }
    public Dictionary<string, Store> Stores { get; set; }
    public bool Processed { get; set; }
}

When I update Firebase database tree Config.UserReport.Stores[].ID, Firesharp will fire an even giving the path of modified property and the value as following:

//userReports/ufHJ739MxccrJvXjxU4nfZArDY13/KKpgPGL2vDXSIo38dNd/stores/NYC-BDWY-121/id

What I want to achieve is to update the Id property dynamically using reflection, here is what I've done but it's not working. Where src is the C# object to synch and propName is the path received from Firesharp. The function should recursively go through the objects until it find the property Id and set its value. So far, it can go deep to first dictionary.

    public static object GetDeepPropertyValue(object src, string propName)
    {
        if (propName.Contains('/'))
        {

            var Split = propName.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
            string RemainingProperty = propName.Substring(propName.IndexOf('/') + 1);
            var property = src.GetType().GetProperties().FirstOrDefault(p => string.Equals(p.Name, Split[0], StringComparison.CurrentCultureIgnoreCase));
            if (property != null) // Its a property 
                return GetDeepPropertyValue(property.GetValue(src, null), RemainingProperty);
            else // Its a Dictionary Item
            {
                var prop = src.GetType().GetProperties().FirstOrDefault(p => string.Equals(p.Name, "Values", StringComparison.CurrentCultureIgnoreCase));
                if (prop != null)
                {
                    var mm = prop.GetValue(src, null);
                    return GetDeepPropertyValue(mm, RemainingProperty);
                }
                else
                {
                    if (string.Equals(src.GetType().Name, "ValueCollection",
                        StringComparison.CurrentCultureIgnoreCase))
                    {
                        var collprop =
                            src.GetType().GetGenericArguments()[1].GetProperties()
                                .FirstOrDefault(
                                    p => string.Equals(p.Name, "Values", StringComparison.CurrentCultureIgnoreCase));
                        var tm = collprop.GetValue(src, null);

                        if (collprop != null)
                            return GetDeepPropertyValue(tm, RemainingProperty);
                        else
                            return null;
                    }
                    else
                    {
                        return null;
                    }
                }

            }
        }
        else
        {
            var tt = src.GetType().GetProperties().FirstOrDefault(p => string.Equals(p.Name, propName, StringComparison.CurrentCultureIgnoreCase))?.GetValue(src, null);
            return tt;
        }
        //GetProperty(propName).GetValue(src, null);
    }

Thanks.

UPDATE

I think it would help to have the JSON data received from Firebase:

{
"config": {
"agents": {
    "NYC-BDWY-121": {
        "fingerprint": "375C-1E1E-D003-65D7-11D3-5A47-9165-FFZF",
        "id": "NYC-BDWY-121",
        "timestamp": "2016-6-21"
    },
    "NYC-BDWY-90": {
        "fingerprint": "375C-1E1E-D003-65D7-11D3-5A47-9165-EE2F",
        "id": "NYC-BDWY-90",
        "timestamp": "2016-6-21"
    }
},
"reports": {
    "KKpgPGL2vDXSIo38dNd": {
        "description": "Define report description here",
        "id": "KKpgPGL2vDXSIo38dNd",
        "name": "Sales Summary",
        "order": 1,
"parameters": {
  "dateRange": true,
  "multipleSource": false,
  "timeRange": false
},
        "sqlQuery": "SELECT I.store_id..."
    }
},
"stores": {
    "NYC-BDWY-121": {
        "key": "NYC-BDWY-121",
        "name": "NYC Broadway 121st",
        "order": 2
    },
    "NYC-BDWY-90": {
        "key": "NYC-BDWY-90",
        "name": "NYC Broadway 90th",
        "order": 1
    }
},
"userReports": {
    "ufHJ739MxccrJvXjxU4nfZArDY13": {
        "KKpgPGL2vDXSIo38dNd": {
            "endDate": "2016-6-1",
            "lastExecution": "2016-6-16",
            "processed": false,
            "startDate": "2016-5-1",
            "stores": {
                "NYC-BDWY-121": {
                    "id": "NYC-BDWY-121"
                },
                "NYC-BDWY-90": {
                    "id": "NYC-BDWY-90"
                }
            }
        }
    }
   }
  }
}





How to get the name of the dll that a `Type` comes from while in a portable class library

In the process of porting a project to a Portable Class Library (PCL).

Previously, I have been able to get the Module of a Type directly in order to access the name of the DLL using...

private static bool isSystemType(Type service) {
    var moduleName = service.Module.Name.ToLower();//eg: system.dll
    //other code removed for brevity
}

System.Type.Module does not exist in the PCL project so it does not compile.

I've gone down the Type.Assembly.Fullname route but would prefer not having to parse the string just to get the name of the dll.

The PCL project targets

  • .Net Framework 4.5
  • Silverlight 5
  • Xamarin.Android
  • Xamarin.iOS
  • Xamarin.iOS (Classic)

Any other ways of getting the name of the dll that a Type comes from while in a portable class library with the above targets?





Get a lambda argument from annotation

Assume we have an annotation:

@scala.annotation.meta.field
class MyAnnotation(param: String => String) extends StaticAnnotation

According to Remi T's answer here, if param was just a String, we could extract it this way:

a.tree.children.tail.collect({ case Literal(Constant(id: String)) => id }).headOption

But how can we extract and use a lambda expression? It is a Function(params, body) where params is an arguments list and body is a Tree representing function's body.

It's possible to convert the whole function's Tree to String and then use an interpreter, but it is SO ugly solution (and I couldn't do even this due to some problems with classpath during instantiating the interpreter, none of advices I found worked).





Backwards compatibility with C# Reflection and NUnit Versions

I am using C# on the .NET 4.5 framework with Visual Studio 2015. I am attempting to plug NUnit support into an automated test system that was built around MSUnit tests. As part of the system, I need to find methods marked with TestAttribute and TestCaseAttribute in provided .dll files using Reflection. Currently this system has NuGet packages installed for NUnit version 3.2.1.

Question: is there a way to detect these attributes on tests that were created using older versions of NUnit? For example, I have some tests that were created using NUnit version 2.6.4, but their corresponding attributes are not found because the system is looking for attributes from NUnit 3.2.1.

Here is a snippet of code used to detect the test classes marked with TestFixtureAttribute in the provided .dll:

var testClasses = testAssembly
            .SelectMany(a => a.GetTypes())
            .Where(a => a.IsDefined(typeof(TestFixtureAttribute), false));

Again, this snippet doesn't find any test classes on the provided .dll because the older TestFixtureAttribute is not the same as the one in NUnit 3.2.1

I have successfully run older NUnit tests on the nunit3-console.exe, so discovering the tests is the big roadblock for now.

Thanks in advance for any help!





Can you set HttpContext.Current.UserIdentity.Name with reflection?

I am trying this:

typeof(FormsIdentity)
    .GetField("Name", BindingFlags.Instance | BindingFlags.NonPublic)
    .SetValue(HttpContext.Current.User.Identity, newUsername);

but typeof(FormsIdentity).GetField("Name", BindingFlags.Instance | BindingFlags.NonPublic) returns null. What I am trying to do is allow a user to change their username.





C# Reflection unable to find NUnit attributes

Using C# on the .NET 4.5 Framework with Visual Studio 2015, I'm attempting to use Reflection to find NUnit tests and testcases from a provided .dll file. The problem I'm running into is that reflection query methods (such as IsDefined and GetCustomAttributes) require that attributes directly inherit from System.Attribute.

In NUnit 3.2.1 (Latest stable version as of June 2016), attributes inherit from an NUnitAttribute class, which in turn inherits from System.Attribute. This prevents Reflection from finding marked NUnit tests. As a temporary work around, I've downgraded to NUnit 2.6.4 where attributes directly inherit from System.Attribute. In the future, I would like to build in support for newer versions of NUnit.

Does anyone have solutions or suggestions for this issue? I've searched around, but cannot seem to find a way to make Reflection methods "realize" that System.Attribute is further up the inheritance chain.





Programmatic compilation invocation through maven-embedder, but reflection fail on compiled class

In my current project, I need to compile few classes, provided by client. I am using maven-embedder to invoke the programmatic compilation of new client classes. The .class files of the new classes gets generated in the target folder in the first call. But then I am not able to get the class through Class.forName("fully.qualified.class.name") in the same call. It gives a ClassNotFoundException.

However in the next call, it runs successfully and all the properties of the new class is available through reflection. Why reflection fails in the first call?





isAnnotationPresent() is not working with @Repeatable annotations

It turns out that calling method.isAnnotationPresent() is not working properly if you use repeatable annotations.





mercredi 22 juin 2016

Is there a way to know what Types are implemented in child object using reflection

I have a super class

class A<X,Y,Z> {
}

Then I have the child class B (P, Q, R are another set of classes)

class B extends A<P,Q,R> {
}

in my JUnit test case I want to know the classes P,Q,R when given an object B. Is this possible using reflection?





Calling Math function dynamically in C#

I have an issue which I don't quite understand. I am learning the architecture of C# and I gave myself a small project to practice on. One of the things I wished to do is to create a function that receives (string action, double x, double y) and activate a Math (the built in class of C#) function which name is @action on @x and @y dynamically. I read posts about how to do this using Reflection but it simply fail. It seems to work for classes I build but not for Math. the compiler rejects any method I tried claiming that "Math is a type and cannot be used in that context" whenever I tried to do so. There are plenty of examples on calling functions dynamically using Reflection. Here are a couple:

Calling a function from a string in C#

how to dynamically call a function in c#

Now for my questions:

A. What does the compiler screaming about? What does this error mean?

B. Why doesn't it work for Math but does so for classes I develop?

C. How do I make it work?

D. Is there a way to do so without using Reflection?

PS: If my question isn't clear I can give you an equivilent in JavaScript. You could easily achieve what I want by simple writing the following line:

return Math[action](x,y);

Thanks for any help.





Create a matrix based in Objects Class acquire by Class Loader method

In my code, I load class in .loadClass method. This work.

NewUnit = myClassLoader.loadClass(classNameToBeLoaded);

Now I need create a matrix based of instances of this class, like this:

NewUnit[][] units = new NewUnit[8][5];

Help!





C# - Graphable Data Class - Best method for performing calculations on properties

I would like to have an object that represents graphable data. I couldn't find anything that exists that meets the requirements, so I started implementing it.

The class contains properties which represent values at increments along the x-axis, and a property for current units (two are possible). I used properties because I would like to access by name (instead of just a list of numbers). This seems like it could be overkill and slow things down.

I need to perform various calculations which are done at each x-axis increment. So far, I have tried using Reflection and just performing the calculation on all properties (except units). This seems repetitive.

I am not totally versed with lambda functions, but it seems like that is an option too.

Is there a better way to approach this? Is there something that exists already that I missed?

Below is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Reflection;

namespace CustomDataType
{
    // two units for x-axis values
    public enum Units
    {
        Power = 1,
        dB = 0
    }

    public class GraphableData
    {
        // values along x-axis
        public double A50 { get; set; }
        public double A63 { get; set; }
        public double A80 { get; set; }
        public double A100 { get; set; }
        public double A125 { get; set; }
        public double A160 { get; set; }
        public double A200 { get; set; }

        // More values of the same...

        public Units units {get; set;}

        // Constructor for DataRow
        public GraphableData(DataRow Row)
        {
            try
            {
                //Retrive row information
                A50 = Convert.ToDouble(Row["A50"].ToString());
                A63 = Convert.ToDouble(Row["A63"].ToString());
                A80 = Convert.ToDouble(Row["A80"].ToString());
                A100 = Convert.ToDouble(Row["A100"].ToString());
                A125 = Convert.ToDouble(Row["A125"].ToString());
                A160 = Convert.ToDouble(Row["A160"].ToString());
                A200 = Convert.ToDouble(Row["A200"].ToString());

                // More values....


            }
            catch (Exception Ex)
            {
                // not sure what to do yet
            }

            units = TLUnits.dB;

        }

        // Constructor for emtpy dataset
        public GraphableData(TLUnits _units = TLUnits.dB)
        {
            A50 = 0;
            A63 = 0;
            A80  = 0;
            A100 = 0;
            A125 = 0;
            A160 = 0;
            A200 = 0;

            units = _units;
        }

        // Method 1:
        // Calculation on x-axis values using Reflection
        public void convertToPower()
        {
            if (units == TLUnits.Power)
            {
                return;
            }

            // run through properties and apply conversion
            PropertyInfo[] properties = typeof(GraphableData).GetProperties();

            foreach (PropertyInfo property in properties)
            {
                // skip units property
                if ( property.PropertyType == typeof(double) )
                {
                    double value = (double)property.GetValue(this, null);
                    double Power =  Math.Pow(10d, -0.1 * value);

                    property.SetValue(this, Power, null);
                }
            }
            units = TLUnits.Power;
        }


        // Method 2: 
        // Perform calculations on every property.
        public void convertTodB()
        {
            if (units == TLUnits.dB)
            {
                return;
            }

            A50 = Math.Round(-10 * Math.Log10(A50));
            A63 = Math.Round(-10 * Math.Log10(A63));
            A80 = Math.Round(-10 * Math.Log10(A80));
            A100 = Math.Round(-10 * Math.Log10(A100));
            A125 = Math.Round(-10 * Math.Log10(A125));
            A160 = Math.Round(-10 * Math.Log10(A160));
            A200 = Math.Round(-10 * Math.Log10(A200));

            units = TLUnits.dB;
        }

        // Method 3: (not implemented)
        // Perhaps use lambda functions to operate on
        // individual x-axis data. Pass in specific
        // calculation.


        // Other examples of calculations that will be done
        public static GraphableData addPaths(GraphableData Path1, GraphableData Path2)
        {
            GraphableData sumData = new GraphableData();

            // Add two datasets based on x-axis values

            return sumData;
        }

        public static GraphableData addPaths(GraphableData Path1, GraphableData Path2, GraphableData Path3)
        {
            GraphableData sumData = new GraphableData();

            // Add three datasets based on x-axis values

            return sumData;
        }

    }


}





Using reflection to test methods of inner private class

Is there a way to test the methods of a private inner class using reflection? In the code below, how can we test func-1 and func-2

public class Outer extends AbstractOuter {
private final Properties properties;

public Outer(Properties properties) {
    this.properties = properties;
}

private class Inner extends AbstractInner {

    private int numOfProperties;

    @Override
    void func-1() throws Exception {
        //
    }

    private int func-2(long l)  {
        //
    }
}
}





DRF: get allowed filters

I'va a django-rest-framework viewset like this:

class MyFilterSet(django_filters.FilterSet): 

    class Meta:
        model = MyModel

    fields = {
        'code': ['exact', 'icontains', 'istartswith'],
        'name': ['exact', 'icontains', 'istartswith'],
        'status': ['exact'],
        ...
    }


class MyViewSet(viewsets.ModelViewSet):

    serializer_class = MySerializer
    model = MyModel

    filter_backends = (filters.OrderingFilter, filters.SearchFilter, filters.DjangoFilterBackend)

    # for DjangoFilterBackend
    filter_class = MyFilterSet

    # for SearchFilter
    search_fields = (
        'code',
        'name',
        'description',
        ...
    )

    # for OrderingFilter
    ordering_fields = ('code', 'name', 'status', ...)

How can I inspect this API to get allowed filters (needed by my frontend page)?





Is it possible to get List of Classes in a package for Reflection

i wrote code to get the list of methods in a class as following

Code

package checking;

import java.lang.reflect.Method;

public class Test {

    public static void main(String[] args) {
        Class<CrossBrowserScript> obj = CrossBrowserScript.class;
        Method[] meth = obj.getMethods();
        for (Method method : meth) {
            String Mname = method.getName();
            System.out.println(Mname);
        }
    }
}

But i want to get the List of class names in a package using reflection.





Get Message list from notification

Starting from Android N, it's possible to retrieve a list of Message objects. The extra key is EXTRA_MESSAGES. However you need to convert Parcelable[] array. There is a package static private method but the problem is that the invoke method doesn't understand the array that should be wrapped into another one. This is my code:

private List<Notification.MessagingStyle.Message> extractMessages(Notification notification) {
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) {
            return null;
        }
        List<Notification.MessagingStyle.Message> list;
        Parcelable[] parcelables = notification.extras.getParcelableArray(Notification.EXTRA_MESSAGES);
        Method m;
        try {
            m = Notification.MessagingStyle.Message.class.getDeclaredMethod("getMessagesFromBundleArray",
                    Parcelable[].class);
            m.setAccessible(true);
            list = (List<Notification.MessagingStyle.Message>) m.invoke(null, parcelables);
        } catch (NoSuchMethodException | InvocationTargetException |
                IllegalAccessException e) {
            return null;
        }
        return list;
    }

And the error:

java.lang.IllegalArgumentException: Wrong number of arguments; expected 1, got 2
    at java.lang.reflect.Method.invoke(Native Method)
    at com.foo.bar.app.service.NotificationService.a(Unknown Source)
    at com.foo.bar.app.service.NotificationService.onNotificationPosted(Unknown Source)
    at android.service.notification.MyAppService.onNotificationPosted(MyAppService.java:237)
    at android.service.notification.MyAppService$MyHandler.handleMessage(MyAppService.java:1441)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6044)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)





Invoke method on static filed using IL generator in C# reflection

I'm generating a new Type via TypeBuilder from C# reflection. The problem that I have right now is how to build method body to invoke method on static filed.

Right now my generated (at runtime) class looks like this:

public class Generated
{
    static private MyObject obj;

    public MyResponse Hello(MyRequest req1)
    {
        return obj.Hello(req1); // this part need to be grnerated
    }
}

So right now I'm generating method like this:

MethodBuilder mb = tb.DefineMethod(
    methodInfo.Name,
    MethodAttributes.Public | MethodAttributes.Final,
    CallingConventions.HasThis | CallingConventions.ExplicitThis,
    methodInfo.ReturnType,
    arguments);

ILGenerator il = mb.GetILGenerator();
il.Emit(OpCodes.Ldnull); // right now I'm just simply returning null
il.Emit(OpCodes.Ret);

So please tell me how can I load static field on stack in Il generator and then invoke certain method on it.