samedi 31 octobre 2015

Programmatically get method of XML button onClick attribute in Android

In Android, specifying a method in a button's XML onClick property causes that method to get called on button click. Given the button view, is there a way to find out what method is going to get called programmatically? I've looked at the available public methods for Views, but I can't find anything in regards to getting view properties that might help. I know that Android creates an onClick listener in the android.view.View$1 class for buttons defined in this way, and I was hoping there might be a way to use reflection to find the method I'm after.





Issues in calling generic method through reflection with a delegate parameter

I've been messing around with this for over an hour and just cannot seem to get it right. Here's one of the exceptions I am getting:

Error: Object of type 'System.Func1[System.Object]' cannot be converted to type 'System.Func1[System.Collections.Generic.IEnumerable1[System.Collections.Generic.IEnumerable1[System.Object]]]'.

Basically I have a generic factory method which looks like this

ReturnItem<TResult> CreateOutput<T, TResult>(Func<IEnumerable<T>> postBack,
    Processor manager) where TResult : class;

and I am trying reflect into, but the Func> is causing me problems. Here's the code I have in trying to call it:

var infer = Factory.CreateReturnInference(); //Keypair value (type, type) is NOT an NormalOutputFactory in this instance
Func<object> callBack = () => subTypes;

var toRun = Factory.GetType()
            .GetMethod("CreateOutput", BindingFlags.Public | BindingFlags.Instance)
            .MakeGenericMethod(infer.Key, infer.Value)
            .Invoke(Factory,
                new object[] {callBack, Manager}) as
            ReturnItem<object>;

The keypair value returned from Factory.CreateReturnInference is used to specifiy the generic parmeters, and just to provide clarity on it's implementation: (Warning very ugly code, violates open-close amount other stuff :)):

public KeyValuePair<Type, Type> CreateReturnInference()
    {
        return this is NormalOutputFactory
            ? new KeyValuePair<Type, Type>(typeof (object), typeof (Log))
            : new KeyValuePair<Type, Type>(typeof (IEnumerable<object>), typeof (Enum));
    } 

The general question is: When calling a generic method through reflection how do I specify a Func parameter?





sort list using property variable

Suppose I have this list of process or any other object

List<Process> listProcess = new List<Process>();

I can sort it using this line listProcess.OrderBy(p => p.Id); But what if I have only string name of property obtained in runtime. I assume, I should use reflection to get the property object. Can I use orderby method or I should use Sort and then pass own comparer?





why am I getting null value when trying to get a property value based on the name?

I have this code for getting value of the property based on string name of the property

    public class Person
{
    public String LastName;
}    
static void Main()
{
    Person person1 = new Person { Born = new DateTime(1989, 10, 7), FirstName = "John", LastName = "Smith" };
    string propertytoGet = "LastName";        
    object wantedProperty = person1.GetType().GetProperty(propertytoGet).GetValue(person1, null);    
}  

I am getting null reference exception, since GetProperty(propertytoGet) returns null. I have found this solution on stackoverflow, it was marked as an answer, but it doesn't work for me.





Activator.CreateInstance can't find the constructor

I got an error in BaseRenderModel<TBaseEntity> class that says Constructor on type 'Jahan.Nuts.Model.UModel.HomePage' not found.

I double checked the code and read some solutions in Internet about it but I couldn't solve my problem. I've used Umbraco 7.3 (ASP.NET MVC) at my project

How can I solve this problem?

namespace Jahan.Nuts.Model.UModel.URenderModel
{
public class BaseRenderModel<TBaseEntity> : RenderModel where TBaseEntity : BaseEntity
{

    public TBaseEntity Model { get; set; }
    public BaseRenderModel(IPublishedContent content, CultureInfo culture) : base(content, culture)
    {
        object args = new object[] { content, culture };
        Model = (TBaseEntity)Activator.CreateInstance(typeof(TBaseEntity), args); //Constructor on type 'Jahan.Nuts.Model.UModel.HomePage' not found.
    }
}
}

Class BaseEntity:

public class BaseEntity
{
   public BaseEntity()
    {

    }
    public BaseEntity(IPublishedContent content, CultureInfo culture)
    {
       // some codes
    }
    public BaseEntity(IPublishedContent content)
    {
       // some codes
    }
}

Class HomePage:

public class HomePage : BaseEntity
{
    public List<Photo> PhotoList { get; set; }

    public HomePage(IPublishedContent content, CultureInfo culture) : base(content, culture)
    {
        Initialize(content, culture);
    }
    public HomePage(IPublishedContent content) : base(content)
    {
        Initialize(content, null);
    }
    protected HomePage()
    {
    }
}

Class HomePageController:

public class HomePageController : RenderMvcController
 {
    public override ActionResult Index(RenderModel model)
    {
        BaseRenderModel<HomePage> instance = new BaseRenderModel<HomePage>(model.Content, model.CurrentCulture);
        return base.Index(instance);
    }
}





vendredi 30 octobre 2015

Efficient way to access a property of a class by the string name

I want access to a property value by its name. The only way i know it's by reflection with a code like this:

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

Are there others ways to do it (using ex. codegen, etc.)?





How to switch on reflect.Type?

I have managed to do this, but it does not look efficient:

var t reflect.Type
switch t {
case reflect.TypeOf(([]uint8)(nil)):
    // handle []uint8 array type
}





Add attribute on property of a runtime created type using reflection

I'm trying to create a type at runtime sticking a StuckAttribute attribute on every property I add on this type.

Type Builder:

private TypeBuilder getTypeBuilder()
    {
        var typeSignature = "IDynamicFlattenedType";
        var an = new AssemblyName(typeSignature);

        AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicDomain");
        TypeBuilder tb = moduleBuilder.DefineType(typeSignature
                            , TypeAttributes.Public |
                            TypeAttributes.Interface) |
                            TypeAttributes.Abstract |
                            TypeAttributes.AutoClass |
                            TypeAttributes.AnsiClass
                            , null);

        return tb;
    }

Property Builder:

    private void createProperty(TypeBuilder tb, string propertyName, Type propertyType)
    {
        Type[] ctorParams = new Type[] { typeof(string) };
        ConstructorInfo classCtorInfo = typeof(StuckAttribute).GetConstructor(ctorParams);

        CustomAttributeBuilder myCABuilder2 = new CustomAttributeBuilder(
                            classCtorInfo,
                            new object[] { DateTime.Now.ToString() });

        PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
        propertyBuilder.SetCustomAttribute(myCABuilder2);

        MethodBuilder getPropMthdBldr = tb.DefineMethod("get_" + propertyName,
            MethodAttributes.Public |
            MethodAttributes.Abstract |
            MethodAttributes.Virtual |
            MethodAttributes.HideBySig |
            MethodAttributes.NewSlot,
            CallingConventions.HasThis,
            propertyType,
            Type.EmptyTypes
        );
        getPropMthdBldr.SetImplementationFlags(MethodImplAttributes.Managed);

        MethodBuilder setPropMthdBldr =
            tb.DefineMethod("set_" + propertyName,
                MethodAttributes.Public |
                MethodAttributes.Abstract |
                MethodAttributes.Virtual |
                MethodAttributes.HideBySig |
                MethodAttributes.NewSlot,
                CallingConventions.HasThis,
                null, new[] { propertyType });
        setPropMthdBldr.SetImplementationFlags(MethodImplAttributes.Managed);

        propertyBuilder.SetGetMethod(getPropMthdBldr);
        propertyBuilder.SetSetMethod(setPropMthdBldr);
    }

I've created a simple test in order to check the StuckAttribute is on the properties. As you can see, I'm trying to get the attributes call GetCustomAttributes() over each PropertyInfo element.

[Test]
public void test()
{
    Type flattenedType = Reflection.Classes.FlattenClassBuilder.flattenType<TestClass>(this.classes);

    flattenedType.Should().NotBeNull();

    PropertyInfo[] properties = flattenedType.GetProperties();
    properties.Should().NotBeEmpty().And.HaveCount(4);

    IEnumerable<Attribute> attrs = properties[0].GetCustomAttributes();
    attrs.Should().NotBeEmpty();
}

However it fails. It fails onthe last assert:

 attrs.Should().NotBeEmpty();

What am I doing wrong?





Java ObjectProperty dynamically get setter function

Say I have a SimpleObjectProperty, and has a setter function named set. Is there another way to get the setter function from the object than searching for a function with the right name?

I figured, since Oracle says a property called firstName should have a setter called setFirstName, perhaps there is a faster and more convenient way of finding it? I would prefer calling object.setValue to call the setter, but that would require overriding of the SimpleObjectProperty class I guess.





Create Anonymous object from Dictionary

Today I got stuck at one point where I need to convert a Dictionary<String,String> to an anonymous object. Is there any one who has tried this before. Below is the example what I actually need.

var dict = new Dictionary<string, object> 
{
    { "CourseId", "XDX123BH" }, 
    { "PersonID", "JIHJ98KH" } 
};

Though this object I want to create is an anonymous object like:

new {CourseID = "XDX123BH", PersonId = "JIHJ98KH" }

Is it possible to do this?





[haxe]: Is there more neat design for requesting static fields in class successors?

I'm implementing network controller that sends requests to the server with integer command type id and binary serialized block of other command data. Prototype of all commands looks like:

class NetCommand {

    public static var typeId; // type must be set in successors!

    function new() {
    }

    public function typeGet():Int {
        return Reflect.field(Type.getClass(this), "typeId");
    }

}

All this mess in typeGet() function done just for access to the static variables with type ids of all successors. I can't simply write

return typeId;

because statics are not inheritable and this method will return 0 as a value of prototype's variable. Is there any neat solution? Is my solution cross-platform?





jeudi 29 octobre 2015

Get rails association from foreign key?

What I want: for a given foreign key name, and the model class, I can get the association (to know which model it can be resolved to).

For example:

# model: product.rb
class Product < ActiveRecord::Base
  belongs_to :category
end

# resolution:
association = Product.get_association('category_id')

So I need this get_association function.

What I know now:

  1. from Product.reflections I can get a list of reflections / associations
  2. for one reflection, I can get the foreign key
  3. I can build a map for this foreign key, to get the association

However, I want to ask if there is a simple method I can call directly?





KVC Swift 2.1 Reflection

I'm attempting to implement a KVC equivalent is Swift (inspired by David Owens) using reflection.

valueForKey is fairly trivial, using reflection to get all the children names and retrieve the appropriate value. setValueForKey has proved to be quite tricky however, as Swift reflection appears to be read-only (since readwrite would break reflections dogma)

protocol KVC {
    var codeables: [String: Any.Type] { get }
    mutating func setValue<T>(value: T, forKey key: String)
    func getValue<T>(key: String) -> T?
}


extension KVC {
    var codeables: [String: Any.Type] {
        var dictionary: [String: Any.Type] = [:]
        let mirror = Mirror(reflecting: self)
        for child in mirror.children {
            if let label = child.label {
                 dictionary[label] = Mirror(reflecting: child.value).subjectType
             }
         }
        return dictionary
    }

    mutating func setValue<T>(value: T, forKey key: String) {
        if let valueType = self.codeables[key] where valueType == value.dynamicType {

        }
    }

    func getValue<T>(key: String) -> T? {
        let mirror = Mirror(reflecting: self)
        for child in mirror.children {
            if let label = child.label, value = child.value as? T where label == key {
                return value
            }
        }
        return nil
    }
}

Is there anyway in Swift at all to set a dynamic keypath value without using the Objective-C runtime or enforcing that the conformer is a subclass of NSObject? It seems like the answer is no but there are some clever workarounds such as ObjectMapper, although I'm not a fan of the responsibility its on the conformer.





How to forbid create Object via reflection?

Prologue

I have a class :

public final class Session {

    private int userId;
    private String token;

    Session(int userId, String token) {
        this.userId = userId;
        this.token = token;
    }

    public String getToken() {
        return token;
    }

    public int getUserId() {
        return userId;
    }
}

As you see, we can create object via reflection.

  • I know that i can forbid access to methods via reflection with final modificator. But, this modificator can not be applicable to constructor.

  • I know that i can forbid access to constructor via private or package-private modificators.

The goals

  • Forbid creating of object even via reflection way to preserve security.
  • Make access to fill object fields only package-private.

P.S. Maybe it can be complete via OOP/OOD way?





Get all members of a class along with name, type and value in C#

I need to read an external project and get all members with their type and value, function names and their parameter names and in general anything that has a name a type and a value and list them in a simple cmd window.

I tried with this but don't know where to start grabbing function names and parameters.

Any guidance would be appreciated.





c# Reflection get dynamic members

I have an issue on reflection.

I Do have an ComObject's named Item (NewItem-> Instance). (interface)

For some reason I need some properties of this object.

var Item = typeof(IItem);
var props = Item.GetProperties();
foreach (var prop in props)
{
  var property = Item.GetProperty(prop.Name);
  var Propertytype = property.GetType().Name;
  if (Propertytype == "RuntimePropertyInfo")
  {
      var method = property.GetGetMethod();
      var  spesific = method.Invoke(NewItem, null);// spesific has dynamic Members...
  }
}

And I don't know how to get the Dynamic members.

Any ideas? Best regards Oliver





How to get name parametr in List with reflection [duplicate]

This question already has an answer here:

I have a Lot List like this:

..
public java.util.List<ComId> comIds;
public java.util.List<Notification> notifications;
public java.util.List<ProductItem> productItems;
..

And i using java reflection to read this.

Input:

for (Field f : fields) {
    Class<?> type = f.getType();
    String genName = f.getGenericType().getTypeName().toString();
}

I get such a result:

java.util.List<my.package.Customer.ComId>
java.util.List<my.package.Customer.Notification>
java.util.List<my.package.Customer.ProductItem>
..

I just want get only:

ComId
Notification
ProductItem
..

How i can do that?





Access "autos" in process (at runtime)

Is it somehow possible to access the debuggers "autos" from code/in-process? E.g. to create a dump of all members/variables and their respective values from the current scope?

autos





Design Consideration : Using reflection versus interfaces in golang

I'd like to know if one may prefer the use of either reflection or interface definition versus the other. I am particularly interested in tradeoff between lines of code written and the performance of a system.

Let me illustrate the particular case that plagues me. There are multiple structures that contain some mandatory fields, and some optional fields.

type Common struct {
    X int
    Y string
}

type A struct {
    common Common
    optionalA OptionalA
}

type B struct {
    common Common
    optionalB OptionalB
}

Approach 1: Using reflect (as many functions as parameters in Common):

//obj is A or B type or any other type for that matter
func GetX(obj interface{}) (int, bool) {
    reflectData := reflect.ValueOf(obj).Elem()
    if reflectData.IsValid() == false {
        return 0, false
    }   

    myCommon := reflectData.FieldByName("common").Interface().(Common)
    return myCommon.X, true
}

func GetY(obj interface{}) (string, bool) {
    reflectData := reflect.ValueOf(obj).Elem()
    if reflectData.IsValid() == false {
        return "", false
    }   

    myCommon := reflectData.FieldByName("common").Interface().(Common)
    return myCommon.Y, true
}

Approach 2: Using interfaces (as many functions as parameters in Common * Number of possible objects):

type SomeInterface interface {
    GetX() int
    GetY() string
}

func GetXFromCommon(c Common) int {
    return c.X
}

func GetYFromCommon(c Common) string {
    return c.Y
}

func (obj A) GetX() int {
    return GetXFromCommon(obj.common)
}

func (obj B) GetX() int {
    return GetXFromCommon(obj.common)
}

func (obj A) GetY() string {
    return GetYFromCommon(obj.common)
}

func (obj B) GetY() string {
    return GetYFromCommon(obj.common)
}

Similar code duplication for for all common fields and all possible objects. Fairly straightforward, no complexity like in the case of reflection, and perhaps faster processing times. However, all that duplicate code and code-maintainability problems! Imagine if there were 100s of such structures to deal with, and lot more parameters in Common.





How to get Type of object from it's String value using reflection in java Only

I want to get type of an input value (which is in String) Ex. "12345" it should return Integer(Name of wrapper class). It can be done using loops and using parseInt etc. methods but i want to do it with Reflection in java only.





Tying to create an instance of an object dynamically [duplicate]

This question already has an answer here:

Getting The following Error...

Error 1 Cannot implicitly convert type 'object' to 'CSV_OOP_Convert.FileConverter'. An explicit conversion exists (are you missing a cast?) \server\UserShares\DBell\VSC\CSV_OOP_Convert\CSV_OOP_Convert\Form1.cs 44 39 CSV_OOP_Convert

String className = cmbConversionAlgorithm.Text;
string namespaceName = "CSV_OOP_Convert";

FileConverter myObj =Activator.CreateInstance(Type.GetType(namespaceName + "." + className));
ConvertFile(myObj);

the cmbConversionAlgorithm contains the the correct name of the class i wish to create an instance of.

it works fine whe i create it normally...

CSV_OOP_Convert.TFConverter tfc = new CSV_OOP_Convert.TFConverter();





Create a Dynamic Linq to EF Expression to Select IQueryable into new class and assign properties

I am trying to dynamically create the equivalent of the following Linq.

IQueryable<TypeOne> ones;
ones.Select(i => new TypeTwo { TwoProp = i.OneProp });

So far I have the following code but it isn't.

public class TypeOne
{
    public string OneProp { get; set; }
}

public class TypeTwo
{
    public string TwoProp { get; set; }
}

public static IQueryable<TypeTwo> Tester(IQueryable<TypeOne> data)
{
    ConstructorInfo constructor = typeof(TypeTwo ).GetConstructor(new Type[] { });
    Expression body = Expression.New(constructor);

    ParameterExpression oneParam = Expression.Parameter(typeof(TypeOne), "one");
    Expression prop1 = Expression.Property(oneParam, "OneProp");

    ParameterExpression twoParam = Expression.Parameter(typeof(TypeTwo ), "two");
    Expression prop2 = Expression.Property(twoParam, "TwoProp");

    Expression assign = Expression.Assign(prop2, prop1);
    body = Expression.Block(body, assign);

    return data.Select(Expression.Lambda<Func<TypeOne, TypeTwo >>(body, oneParam));
}

However I get the following exception-:

Additional information: Expression of type 'System.String' cannot be used for return type 'TypeTwo'





Dynamic type-hinting in Laravel

I was wondering if it is possible to use type-hinting dynamically.

Example:

class Foo {
    __construct(Baz $baz) {
    }
}

class Bar {
    __construct() {
    }

    action() {
        $baz = new Baz;
        return new Foo($baz);
    }
}

class Baz {
    __construct() {
    }
}

I am intending to do it in a generic way so the class will be reusable but in the same time to keep the type hinting:

class Foo {
        __construct(Object $object) {
        }
}





Calling a generic method with interface instances

As a followup question to this one

public interface IFeature  {  }

public class FeatureA : IFeature { }

IFeature a = new FeatureA();
Activate(a);

private static void Activate<TFeature>(TFeature featureDefinition) where TFeature : IFeature
{

}

I undestand, that once the FeatureA is casted to IFeature the generic method will always get IFeature as type parameter.

We have a service with provides us with a list features (List<IFeature>). If we want to iterate over those features, passing each in the generic method, I guess there is no way to get the concrete type in the generic method other than

Since reflection is very costly, I would like to use the dynamic cast. Is there any downside to call the method that way? Somehow I feel dirty when doing that :-)





mercredi 28 octobre 2015

Automatically determine MaxLength and use it for padding

I have a model with a bunch of fields defined like this:

public class Transaction
{
    public DateTime R03DateFrom { get; set; }
    public DateTime? R03DateTo { get; set; }
    [MaxLength(80)]
    public string R03Place { get; set; }
    [MaxLength(20)]
    public string R03Code { get; set; }
    // And so on....
}

At a certain point I need to export some of this data to fixed width files, and if a string has a MaxLength of x, then in the output file it should always be output right-padded with spaces up to x characters.

I'm hoping to re-use the fact that the string's MaxLength is always defined in the Model in order to flow this information through to the export.

At the moment, a typical export row function looks like this (ExDateTime is an extension method that formats the date in yyyyMMddhhmm format):

    private string GetR03Row()
    {
        return GetRowCode() + "03" +
               R03DateFrom.ExDateTime() +
               R03DateTo.ExDateTime() +
               (R03Place??"").PadRight(80) +
               (R03Code??"").PadRight(20);
    }

I'd like to replace the line

(R03Place??"").PadRight(80)

with something that uses the MaxLength attribute.

Every string will have a MaxLength.





Java Reflection, and Searching for fields

I am trying to search for specific fields (int[] type) that are loaded into memory from an applet that contain specific data. I know I can use reflection to this but there are hundreds of classes with many fields within each one. I have tried to recursively do this but the stack size is too small. I am capable of using find the memory addresses using cheat engine, but I believe the garbage collector is moving the data around so I can't use Unsafe. Does anybody know of any other way I can find the fields I am looking for given the data contained within them?





What is the fastest way to get the value of a property of an object of unknown type?

Need a function which returns the value of a property of an object of unknown type. Currently I have the following.

public static object GetValue(object item, PropertyInfo myproperty)
{
     return myproperty.GetValue(item);
}

This github repository works faster but is there a smaller and/or faster way? thanks.





How can I use Reflection to get all fields of particular interface type

Consider following interfaces

public interface ISample 
public interface ISample2 : ISample

public class A
{
    [Field]
    ISample SomeField {get; set;}

    [Field]
    ISample2 SomeOtherField {get; set; }
}

Suppose there are various classes like class A and various Fields like SomeField and SomeOtherField. How can I get a list of all such Fields which are of type ISample or other interfaces derived from ISample (like ISample2)





Create an Instance of a Type, via Emit(Opcodes.Call, methodinfo)

I'm using Reflection, and ilGenerator, to create a .Exe, that calls a method from a dll. My problem is when it is an instance method, i have to put in stack the instance before calling the method. Therefore i have a method in c#, that creates and returns this instance. it is throwing System.MethodAccessException.

My question is, is this even possible?, and how does it work? by doing this in IL, il.Emit(Opcodes.call, methodInfo), in the call that creates the .exe, when in runtime, how does he know what method to call? does the method that i want to call, go to the .exe assembly? im very confused by this.. thanks in advance, sorry for my stuppidity, im very new to this reflection





Using of reflection in Android Istrumentation tests

I'm using ActivityInstrumentationTestCase2 for testing activities in android application and inside my tests I'm trying to assess private fields. But the matter is every time trying it via reflection as

Field f = activity.getClass().getDeclaredField("dateSelector"); 
f.setAccessible(true);
EditText iWantThis = (EditText) f.get(activity);

or (WebView) FieldUtils.readDeclaredField(activity, "currentWebView", true)

my tests stop, not fail and I get

Disconnected from the target VM, address: 'localhost:8605', transport: 'socket'

Thought the same code worked well in unit tests. Any ideas?





C#: which Dlls are declared in the assembly manifest after the build

When I build a C# project that references many projects, I get in the output my dll. I opened it with DotPeek to see its references and I get that some projects references are not there.

My question is : How the compiler decide to put the reference in the assembly ?





Java Reflection : avoid fields with default values

I have the following class structure:

public Class A{
private int a;
private String b;
private B binst;
}

public Class B{
private int x;
private String y;
}

All the getters and setters are defined. I use Java reflection to invoke as follows :

method.invoke(ClassAObj, ClassBObj);

Now, before invoking this, I had only set y and not x. I convert this ClassAObj into JSON and find that the default value of 0 is set for x, and it appears in the JSON. I don't want x field to appear in the JSON. How should I avoid this?

Interestingly, if I set x and not y, the tag y doesn't appear in the JSON.





How can I get the internal "message" value of a System.Exception?

I have an FTP exception thrown from a third-party assembly which is quite generic:

Exception of type 'JSchToCSharp.SharpSsh.jsch.SftpException' was thrown.

On inspection of the Exception, I see there is a private/internal member called message (lower-case m) that contains my error message:

FTP Exception

How can I get the value of this message member?

I have tried to use reflection to get it but null is returned from GetValue:

    BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
        | BindingFlags.Static;
    FieldInfo field = type.GetField(fieldName, bindFlags);
    var value = field.GetValue(instance);

    return value.ToString();

It doesn't appear to be Non-Public or Static so I'm a little unsure as to what to use as my BindingFlags.

Thanks





mardi 27 octobre 2015

c# 6.0 and reflection, getting value of Property Initializers

I've been trying to experiment with reflection and I have a question.

Lets say I have a class, and in this class I have a property initilized with the new feature of c# 6.0

Class MyClass()
{
   public string SomeProperty{ get; set; } = "SomeValue";
}

Is there any way of getting this value, with reflection, without initilizating the class?

I know I could do this;

var foo= new MyClass();
var value = foo.GetType().GetProperty("SomeProperty").GetValue(foo);

But what I want to do is something similiar to this ;

typeof(MyClass).GetProperty("SomeProperty").GetValue();

I know I could use a field to get the value. But it needs to be a property.

Thank you.





System.StackOverflowException when cloning an object using reflection

I am coding a C# forms application, and I am using the following code to clone on object:

public static class ObjectExtension
{
    public static object CloneObject(this object objSource)
    {
        //Get the type of source object and create a new instance of that type
        Type typeSource = objSource.GetType();
        object objTarget = Activator.CreateInstance(typeSource);

        //Get all the properties of source object type
        PropertyInfo[] propertyInfo = typeSource.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

        //Assign all source property to taget object 's properties
        foreach (PropertyInfo property in propertyInfo)
        {
            //Check whether property can be written to
            if (property.CanWrite)
            {
                //check whether property type is value type, enum or string type
                if (property.PropertyType.IsValueType || property.PropertyType.IsEnum || property.PropertyType.Equals(typeof(System.String)))
                {
                    property.SetValue(objTarget, property.GetValue(objSource, null), null);
                }
                //else property type is object/complex types, so need to recursively call this method until the end of the tree is reached
                else
                {
                    object objPropertyValue = property.GetValue(objSource, null);
                    if (objPropertyValue == null)
                    {
                        property.SetValue(objTarget, null, null);
                    }
                    else
                    {
                        property.SetValue(objTarget, objPropertyValue.CloneObject(), null);
                    }
                }
            }
        }
        return objTarget;
    }
}

Some of my objects have parent objects and these parent objects have collections. As such, I am getting the following exception:

An unhandled exception of type 'System.StackOverflowException' occurred in CustomWebpageObjectCreator.exe

How can I prevent this from happening?

Is it possible to decorate some specific properties in an object with an attribute, such that the CloneObject code will not try and clone the property? If so, can someone please help me with the code to do this? If not, how should I modify my code?





java.util.ServiceLoader.load() function is useless and only returns empty result

I'm trying to use Java ServiceLoader in Scala 2.10 to find all my test classes by reflection:

  val services = ServiceLoader.load(classOf[MyClass])
  for (service <- services.asScala) {
    test(service.getClass.getCanonicalName) {
      println(service)
      ... test code
    }
  }

I'm very sure 'MyClass' has several subclasses which contains test cases, as I can use 'classOf[]' function to find them in the same code snippet

However, my test always ends with

Empty test suite.

Is the ServiceLoader not working in Scala? How to fix or circumvent this problem?





How can I make this reflect based GO code simpler?

I am encoding a rather complex structure using a very complicated protocol that's a mix of ASN and a variant of XDR and other encodings.

I based the implementation on xdr encoder available on github. The code is reflection based and it works, but I don't like how I implemented target type switch:

st := ve.Type().String()
    switch st {
    case "time.Time":

I think the following approach might be better, but I could not get it to work properly:

switch ve.(type) {
case time.Time:

The reason it does not work is that ve is of the same reflection type and not the target type.

The following function provides full context of the code:

func (enc *encoderState) encode(v reflect.Value) {

ve := enc.indirect(v)

st := ve.Type().String()
switch st {
case "time.Time":
    log.Println("Handling time.Time")
    t, ok := ve.Interface().(time.Time)
    if !ok {
        enc.err = errors.New("Failed to type assert to time.Time")
        return
    }
    enc.encodeTime(t)
    return
case "[]uint8":
    log.Println("Handling []uint8")
    enc.writeOctetString(ve.Bytes())
    return
default:
    log.Printf("Handling type: %v by kind: %v\n", st, ve.Kind())
}

// Handle native Go types.
switch ve.Kind() {
case reflect.Uint8: // , reflect.Int8
    enc.writeUint8(uint8(v.Uint()))
    return
case reflect.Uint16: // , reflect.Int16
    enc.writeUint16(uint16(v.Uint()))
    return
case reflect.Bool:
    enc.writeBool(ve.Bool())
    return
case reflect.Struct:
    enc.encodeStruct(ve)
    return
case reflect.Interface:
    enc.encodeInterface(ve)
    return
}

// The only unhandled types left are unsupported.  At the time of this
// writing the only remaining unsupported types that exist are
// reflect.Uintptr and reflect.UnsafePointer.
enc.err = errors.New(fmt.Sprintf("unsupported Go type '%s'", ve.Kind().String()))

}

If you know of a better example that can switch by type and kind better, please, let me know.

Thank you





How can i get Class from Generic Type

I do not know how I will explain, I have a class something like

public class MyClass<T>{
    private Class <?> type;
    public MyClass(string className){
        this.type = Class.forName(className);
        Field[] fields = type.getDeclaredFields();//why i need type
    }
}

Then i create an object of that class:

MyClass<Person> persons = new MyClass<>("packageName.Person");

Is there anyway to do this like

MyClass<Person> persons = new MyClass<>();





Create slice of pointers using reflection in Go

I've seen a few examples of reflection around this topic, but I can't find anything that solves this issue. It feels a little convoluted, but the alternative is a massive amount of repetition so I thought I'd give it a try.

I have a function that returns a function (handler). The wrapping function passes in an instance of a struct. I need the inner function to create a slice of pointers to that struct type:

func createCollectionHandler(app *appSession, record interface{}, name string) func(res http.ResponseWriter, req *http.Request) {
    return func(res http.ResponseWriter, req *http.Request) {
        res.Header().Set("Content-Type", "application/json")

        // This line needs to be dynamic:
        var result []*Person

        err := meddler.QueryAll(app.MysqlDB, &result, "select * from "+name)
        if err != nil {
            log.Fatal(err)
        }
        json, err := json.MarshalIndent(result, "", " ")
        if err != nil {
            log.Println(err)
        }
        res.Write([]byte(json))
        return
    }
}





Reference to a property of class in predicate using reflection

I have a simple class with many DateTime properties:

public class MyClass
{
    public DateTime Created {get; set;}
    public DateTime LastChanged {get; set;}
    public DateTime LastAccessed {get; set;}
    ...
}

Later, somewhere in my code I would like to filter collection of MyClass based on these properties. For each property I would like to do something like this:

myQueryableOfMyClass = myQueryableOfMyClass.Where(a => ((begin == null) || (a.Created >= begin)) && ((end == null) || (a.Created <= end));

If I had to do this for each of my DateTime property, it would be a lot of code with some risk of a typo, so I would like to do something like this:

myQueryableOfMyClass = Filter(myQueryableOfMyClass, begin, end, MyClass.Created);
myQueryableOfMyClass = Filter(myQueryableOfMyClass, changebegin, changeend, MyClass.LastChanged);
myQueryableOfMyClass = Filter(myQueryableOfMyClass, accbegin, accend, MyClass.LastAccessed);
...

where the Filter method is implemented using the LINQ Where as in the first example.

The code above does not compile, of course, because MyClass.Created is a nonsense.

There must be some solution using reflection, but I have little very experience with reflection. Could you please help me?





Type.GetTypeFromProgID returns null

My application connects to third party COM components and make use of the APIs exposed by the COM component.

var instanceType = Type.GetTypeFromProgID("EXTERNALAPPLICATION");
if(instanceType!=null)
var workSet= Activator.CreateInstance(instanceType, false) as IWorkSet; 

The GetTypeFromProgID return null and I am unable to create any instance out of that.

But, If I enable visual studio hosting process at project properties--> Debug menu, .vshost.exe is created. After that, It returns the instanceType properly. Am I missing something?





Get parameter(as Object) passed to method

How can I get an Object from a method parameter of given type? Assuming I have:

public void methodWithParameters(MyClass object, OtherClass otherObject) {
    //...
}

now i'm trying to get the object of MyClass type.

public Object getObject() {
    Method method = //get methodWithParameters
    Parameters[]parameters = method.getParameters();
        for (Parameter parameter : parameters) {
            if (parameter.getType().equals(MyClass)) {
                return //object that was passed to methodWithParameters
            }
        }
}





Object Reflection & Enumeration - JavaScript

I am currently reading "JavaScript The Good Parts" by Douglas Rockford and I came across the following two topics:

  1. Reflection
  2. Enumeration

According to the book:

It is easy to inspect an object to determine what properties it has by attempting to retrieve the properties and examining the values obtained.The typeof operator can be very helpful in determining the type of a property.

Although I understand what is being said, that we can use object reflection to basically view all the properties and values it contains. Something like reading ingredients from the back of product to see what is it exactly made of.

My Question is Why and How? Why would I need to use object Reflection, in what scenario and what are advantages of using it and How does Enumeration connect with? What is the link between Reflection & Enumeration?

Thanks in advance.





Java - How to instantiate inner class with reflection?

I have been having problems with the instantiating the inner class using reflection. Heres an example.

public final class Cow {

    public Cow (Bufallo flying, Horse swimming, int cowID, int numCows) {
        //This is where the part I really dont know what the cow is doing
    }

    public Bull eatGrass(String grassName, AngusCattle farmName, JerseyCattle farmName){
        Ox newBreed = new Ox(australiaFarm, somewhereOutThere);
        //Something that has to do with cow eating grass
        return Bull;
    }

    private static final class Ox extends BigHorns {

        public Ox (AngusCattle farmName, ChianinaOx farmName) {
            //Something about mating
        }

    }

}

all I want is to get the constructor or just instantiate the inner class. My code so far...

CowManager cowManager = (CowManager) this.getSystemService(Context.COW_SERVICE);
final Class MainCowClass  = Class.forName(cowManager.getClass().getName());
final Class[] howManyCows = MainCowClass.getDeclaredClasses();
Class getCow = null;
for (int i=0; i < howManyCows.length; i++) {
    if (! howManyCows[i].getName().equals("Cow$Ox")) {
        continue;
    }
    getCow = Class.forName(howManyCows[i].getName());
}
Constructor createCow = getCow.getDeclaredConstructor();

as of the moment I cant seem to find the constructor of ox inside the cow





lundi 26 octobre 2015

Is it possible to compare two .java files methods and fields in all cases?

I am currently taking a project management class and the professor gave this assignment to compare two .java files methods and fields in all cases programmatically. I don't think it's actually possible to do but maybe I am wrong!

The assignment spec is as following (its extremely ambiguous I know)

In this assignment, you are required to write a comparison tool for two 
versions of a Java source file.
Your program takes as input two .java files representing those two versions
and reports the following atomic changes:

1. AM: Add a new method
2. DM: Delete a method
3. CM: Change the body of a method (note: you need to handle the case where a method is
relocated within the body of its class)
4. AF: Add a field
5. DF: Delete a field
6. CFI: Change the definition of an instance field initializer (including (i) adding an initialization to a
field, (ii) deleting an initialization of a field, (iii) making changes to the initialized value of a field,
and (iv) making changes to a field modifier, e.g., private to public)

So that's what I am working with and my approach was to use reflection as it allows you to do everything but detect differences in the method body.

I had considered the idea that you could create a parser but that seemed ridiculous, especially for a 3 credit undergrad class in project management. Tools like BeyondCompare don't list what methods or fields changed, just lines that are different so don't meet the requirements.

I turned in this assignment and pretty much the entire class failed it with the reason as "our code would not work for java files with external dependencies that are not given or with java files in different projects" - which is completely correct but also I'm thinking, impossible to do.

I am trying to nail down a concrete answer as to why this is not actually possible to do or learn something new about why this is possible so any insight would be great.





Parameter passing to constructor in Java Instantiation

I ran into the following problem with instantiating a Java class:

Say, I have a defined class with constructor:

public A(Integer num, String val, ArrayBlockingQueue<Float> q);

I'm trying to instantiate A as follow:

Class<?> myA = Class.forName(<package_name> + "A");
Class[] param = {Integer.class, String.class, ArrayBlockingQueue.class};
Constructor<?> cons = myA.getConstructor(param);

Yet at runtime, the program thows "NoSuchMethodException":

A.<init>(java.lang.Integer, java.lang.String, java.util.concurrent.ArrayBlockingQueue)

Any pointer would be much appreciated. Thank you!





Reflection on Enums

One of the methods I am currently writing for my Java library takes an array of an arbitrary enumeration type as its sole argument. If any of these is non-null, I can access the instance of java.lang.Class representing that enumeration type, which may or may not be a public type. (If they are all null, there is no purpose to this anyway under the circumstances.) How do I get the number of possible values that enumeration type has? The approach I am currently using - Array.getLength(clazz.getMethod("values").invoke(null)); - fails when the Enum class is not public. How do I fix this?





How do you throw an instance of an Exception class created through reflection?

I am trying to create a function that throws an exception based on the type that you pass in.

private void myFunc(Class<?> exceptionType) {
   ...do some work...
   throw new exceptionOfTypeExceptionTypePassedIn(newMessage);
}

Can you do this?





(How) Can I query classes "post-build", using reflection in C#.Net?

Scenario:

  • I have a list of .cs files in a visual studio project (e.g., MyPOCOs), housing a bunch of POCOs (Plain Old C# Objects)
  • I have to run a custom serialization tool (homegrown and I have access to source code) that converts these POCOs into XML files - the tool does this via reflection.

Currently, MyPOCOs project is marked as a Console App and has a main method like the one below:

class Program
    { 
        static void Main(string[] args)
        {
            //Initialize custom XML Serializer
            GenerateBulkVmXML batchSerializer = new GenerateBulkVmXML();

            //Add individual POCOs to Serializer
            batchSerializer.AddPocoModel(typeof(MyPOCO1), "My.Custom.NameSpace");
            batchSerializer.AddPocoModel(typeof(MyPOCO2), "My.Custom.NameSpace1");
            batchSerializer.AddPocoModel(typeof(MyPOCO3), "My.Custom.NameSpace2");

            //Generate custom XML
            batchSerializer .WriteXML(); 
        }
}

Everytime we "run" the above console app, it triggers the Main method, that queries the POCO classes via reflection and spews out the XML.

Problem: For every new POCO added to the project, we have add a line to the above Main method calling the batchSerializer.AddPocoModel(...) method by passing they type of the newly created POCO. Overtime, the number of POCOs will increase and this well get rather unwieldy.

Proposed Solution: My team suggests we integrate this process with the "build" of the MyPOCO project, but I'm not sure everyone can grasp the viability of this approach. So, when we 'build' the project in visual studio, the above Main method gets executed, in essence. Here are the two problems I see with this approach:

  1. How can I discover the classes to serialize? Currently I add them to the main method via the AddPocoModel method. But if I don't do that, how can I discover them and query them via reflection?
  2. How exactly do I trigger the above main method post-build (i.e., it could be any method in a custom class. I'm just using the Main for the sake of argument. Basically, how can I trigger the method that does what the main method does above)?

How do I achieve this? Or, is there a better solution to the above problem?





Returning an instance of a generic type to a function resolved at runtime

Just to clarify, I have this working using dynamic and MakeGenericType. But I cant help but think there is a better way to do this. What I am trying to do is create a "plug-in" loader, using Unity. I will just explain it as I post the code so you can get a sense for what I am doing.

First I'll just post the plug-in itself:

[RegisterAction("MyPlugin", typeof(bool), typeof(MyPlugin))]
public class MyPlugin: IStrategy<bool>
{
    public IStrategyResult<bool> Execute(ISerializable info = null)
    {
        bool result;
        try
        {
           // do stuff
           result = true;
        }
        catch (Exception)
        {
            result = false;
        }

        return new StrategyResult<bool>
        {
            Value = result
        };
    }
}

Couple things to note here. First is the RegisterActionAttribute:

[AttributeUsage(AttributeTargets.Class)]
public sealed class RegisterActionAttribute : Attribute
{
    public StrategyAction StrategyAction { get; }

    public RegisterActionAttribute(string actionName, Type targetType, Type returnType, params string[] depdencies)
    {
        StrategyAction = new StrategyAction
        {
            Name = actionName,
            StrategyType = targetType,
            ResponseType = returnType,
            Dependencies = depdencies
        };
    }
}

Then the interfaces:

public interface IStrategy<T>
{
    IStrategyResult<T> Execute(ISerializable info = null);
}

public interface IStrategyResult<T>
{
    bool IsValid { get; set; }
    T Value { get; set; }
}

All fairly straight forward. The goal here is just to attach some meta-data to the class when it is loaded. The loading happens via unity using a wrapper that simply loads the assemblies in the bin directory using a file search pattern and adds it to a singleton class with a collection of StrategyActions. I don't need paste all the unity code here as I know it works and registers and resolves the assemblies.

So now to the meat of the question. I have a function on the singleton that executes actions. These are applied with Unity.Interception HandlerAttributes and passed a string like so (I can post the code for this but I didn't think it was relevant):

[ExecuteAction("MyPlugin")]

The handler calls the following execute function on the singleton class to "execute" functions that are registered (added to the collection).

public dynamic Execute(string action, params object[] parameters)
{
    var strategyAction = _registeredActions.FirstOrDefault(a => a.Name == action);
    if (strategyAction == null)
        return null;

    var type = typeof (IStrategy<>);
    var generic = type.MakeGenericType(strategyAction.StrategyType);

    var returnType = typeof (IStrategyResult<>);
    var genericReturn = returnType.MakeGenericType(strategyAction.ResponseType);

    var instance = UnityManager.Container.Resolve(generic, strategyAction.Name);
    var method = instance.GetType().GetMethod("Execute");

    return method.Invoke(instance, parameters);
}

This execute is wrapped in an enumerator call which returns a collection of results, which sorts to manage dependencies and what not (see below). These values are referenced by the caller using the Value property of ISTrategyResult{T} to do various things defined by other business rules.

public List<dynamic> ExecuteQueuedActions()
    {
        var results = new List<dynamic>();
        var actions = _queuedActions.AsQueryable();
        var sortedActions = TopologicalSort.Sort(actions, action => action.Dependencies, action => action.Name);
        foreach(var strategyAction in sortedActions)
        {
            _queuedActions.Remove(strategyAction);
            results.Add(Execute(strategyAction.Name));
        }
        return results;
    }

Now mind you, this works, and I get the return type that is specified by the plugins RegisterAction attribute. As you can see I am capturing the Type of the plugin and the return type. I am using the "generic" variable to resolve the type with unity through the use of MakeGenericType, which works fine. I am also creating a generic representing the return type based on the type from the collection.

What I don't like here is having to use dynamic to return this value to a function. I can't figure out a way to return this as a IStrategyResult{T} because obviously the caller to "dynamic Execute(..." can not, at run-time, imply return type of the function. I mulled around with making the call to Execute with a MakeGenericMethod call as I actually have the expected type the StrategyAction. It would be cool if I could some how figure out away to return a strongly typed result of IStrategyResult{T} while determining the type of T during the call.

I do understand why I cannot do this with my current implementation I am just trying to find a way to wrap all this functionality without using dynamic. And was hoping somebody could provide some advice that might be useful. If that means wrapping this with other calls to non-generic classes or something like that, that would be fine as well if that is the only solution.





Advice on Implementing a fields parameter on API in C#

I am looking for advice as to the implementation of an API that filters the response based on the fields parameter (like the fields parameter in the youtube api - see here http://ift.tt/1mzBOzQ)

My response will contain a complex object that may look something like this

{
"Name": "test",
"Location": "north",
"Items": [
    {
        "Name": "item1",
        "Size": "big",
        "Weight": "heavy"
    },
    {
        "Name": "item2",
        "Size": "Small"
        "Weight": "light"
    }
],
"OrderDetail": {
    "OrderNo": 12345,
    "OrderCount": 5
    }
}

In other words some kind of response object that will contain properties, some of which may hold other whole objects or even arrays of objects. Of course the response may also be an array of these items.

I want to add a parameter to the API which will filter the response to only include the specified properties and nested properties... So for eg if I have url param

fields=Name,Items(Name,Size),OrderDetail(OrderCount)

I will get back the following as my API response.

{
"Name": "test",
"Items": [
    {
        "Name": "item1",
        "Size": "big"
    },
    {
        "Name": "item2",
        "Size": "Small"
    }
],
"OrderDetail": {
    "OrderCount": 5
   }
}

I am trying to find the most efficient way for my service to perform this. Some of the ideas i have had (may or may not work) are as follows:

  1. First generate an ExpandoObject based on the field param list and then just map by response data into the ExpandoObject -- Disadvantage: I dont know datatypes without reflecting out each property -- Advantage: should only have to reflect once and then use some mapper (although which probably also relies on reflection)

  2. Iterate through my entire response object with reflection and null or empty fields based on the field param definition -- Disadvantage: Lots of redundant reflection

I dont know if either of these are good solutions. Please can someone give me some guidance here.

Please also keep in mind that the nested objects could even go 3 layers deep, for eg I could have had another object nested in my Item object which are returning within the array of Items Thanks





Runtime-Type of T in IQueryable

Is there a possibility to get the T-Runtime type of an IQueryable? If it's a normal list, there is no problem, but if I check against an IQueryable, I always get a type of System.Object. My code is looking like this at the moment:

private static Type GetDtoTypeFromDataSource(ReportDataSource dataSourceFromDb)
{
    Type result = null;
    if (dataSourceFromDb.Data.GetType().IsGenericType)
    {
        Type[] genericArguments = dataSourceFromDb.Data.GetType().GetGenericArguments();
        result = genericArguments.First();

        if (result == typeof(Object))
        {
            var obj = dataSourceFromDb.Data.Cast<object>().ToList();

            var t2 = obj.First().GetType();
            var t = obj.GetType().GetGenericArguments();
            var t3 = obj.GetType();

            result = obj.GetType();
        }
    }
    else
    {
        result = dataSourceFromDb.Data.GetType().GetElementType();
    }

    return result;
}

I hoped, if I actually load the List via "ToList" I get the Data, but doesnt work as well.

var t2 = obj.First().GetType();

Would to the trick, but what if the List is empty? This doesn't seem like a good solution to me?





Java 8: create new instance of class with generics using reflection

I have the following method:

public Comparator<T> getComparator()  throws ReflectiveOperationException {
    String className = "some.ClassName";
    Class<Comparator<T>> c = Class.forName(className); // (1)
    return (Comparator<T>) c. newInstance();
}

In the line (1) I get this error:

Type mismatch: cannot convert from Class <capture#1-of ?> to Class<Comparator<T>>

What's wrong in this code and how should I make an instance of Comparator<T>?





dimanche 25 octobre 2015

Dynamically declare a type for a method out parameter

I am struggling to describe this problem I have, but here it is:

Suppose I now have the type of a property on one member of a class (instance):

 Type t = propertyInfo.PropertyType;

How do I declare or setup some variable, in order to receive a method call result later, using the out keyword?

t value; // Obviously doesn't compile, How do I declare this?

// or this?
//var value = default(t); // doesn't work

someObject.GetData(out value);

The premise here is that I don't own someObject and I am stuck with this method call signature.





Improve security of reflected code

Firstly can I just clarify that I am aware that the code outlined below is bad. Can I also reassure you that this is not for a real life product.

I have a VB.NET application which receives a string of math from the user, this string then has all the full stops removed and is then iserted into the middle of a resource string.

Together these strings form some VB.NET source code which is then compiled using a VBCodeProvider and called:

Dim compilerParameters As New System.CodeDom.Compiler.CompilerParameters With
{.GenerateExecutable = False,
 .GenerateInMemory = True}
compilerParameters.ReferencedAssemblies.Add(System.Windows.Forms.Application.ExecutablePath)
Dim assemblyInstance = (New Microsoft.VisualBasic.VBCodeProvider).CompileAssemblyFromSource(compilerParameters, code).CompiledAssembly.CreateInstance("FunctionMadeFromUserInput")
assemblyInstance.GetType.GetMethod("Evaluate").Invoke(assemblyInstance, {Input})

I would like your advice on ways to prevent user injection of malicious code, my specific efforts so far have been:

  1. The only reference in the compiled assembly is to the current application (no reference to System etc.)
  2. The users input is stripped of '.'s before compilation

While doing research to try to answer this question I have come across the System.CodeDom.Compiler.CompilerParameters.Evidence property however in .NET 4 this is deprecated. Then I discovered the idea of placing various <Assembly: System.Security...> attributes in the resource string however I am unable to work out which attributes will reduce the attack surface most effectively.

I am interested in preventing the user entered code from accessing disk and network IO and as many other potentially harmful things you can protect against.

Final disclaimer: I know this is not the best method of evaluating math, the math is not what I'm interested in. I am interested in ways of making execution of user input marginally less abominable.





Create an .EXE thats Calls a function from a .dll

so i have a .dll with a function(static or instance, i can change it, and still works) and i want to create an Exe with a Main as entry point, that reads the command line, and calls the funcion from the .dll

-so i load the dll assembly, and get the type that has the function that i want

        Assembly asmLoaded = Assembly.LoadFrom(nameDLL);
        Type baseType = asmLoaded.GetType(typeName);

-Create the new assembly, module and type for the new Exe

AssemblyName aName = new AssemblyName("AppAsm");

        AssemblyBuilder ab =
        AppDomain.CurrentDomain.DefineDynamicAssembly(
            aName,
            AssemblyBuilderAccess.Save);

        ModuleBuilder mb =
        ab.DefineDynamicModule("AppMod", typeName + methodName + ".exe");

        TypeBuilder tb = mb.DefineType("AppType", TypeAttributes.Public);

-Get the methodInfo from the method that i wan to call, and its parameter Types[] for the later Emit(Opcodes.Call,..);

-Then i define the Method, "Main", to be the entry point

 MethodBuilder metb = tb.DefineMethod("Main", MethodAttributes.Public |
            MethodAttributes.Static, null, new Type[] { typeof(String[])});
 ab.SetEntryPoint(metb);

-By using ildasm, i tried to do this part, Generating the IL

 ILGenerator il = metb.GetILGenerator();
 for (int i = 0; i <paramTypes.Length; ++i)
        {
            il.Emit(OpCodes.Ldarg_0); // get the String[], in 0 cause its static
            il.Emit(OpCodes.Ldc_I4,i);
            il.Emit(OpCodes.Ldelem_Ref);
            il.Emit(OpCodes.Stloc, i);
        }         
        il.Emit(OpCodes.Ldloc, 0);
        il.Emit(OpCodes.Ldloc, 1);
        il.EmitCall(OpCodes.Call, wantedMethodInfo, paramTypes);
        il.Emit(OpCodes.Ret);

-finally i create the Type, and save the assemblyBuilder

tb.CreateType();
ab.Save(typeName + methodName + ".exe");

And of course it doesnt work, xD when i run the exe generated with some values, it throws System.InvalidProgramException: Common Languafe Runtime detected an invalid program. in AppTYpe.Main(String[] ) i think i should probably Pop, some stuff out of the stack, but not sure.





samedi 24 octobre 2015

Difficulty re-sizing array with reflection

I'm trying to re-size an arbitrarily-typed array with reflection. Here's my code:

public static void TestResizeArray()
{
    int[]
        ints;
    Array
        arrayOfInts;

    ints = new int[ 3 ];
    arrayOfInts = (Array) ints;
    ResizeArray( ref arrayOfInts, 5 );
    Debug.Assert( arrayOfInts.Length == 5 ); // passes
    Debug.Assert( ints.Length == 5 ); // FAILS <<<<<<<<<<<
}

public static void ResizeArray(
    ref Array
        theArray,
    int
        newSize )
{
    MethodInfo
        methodInfo,
        genericMethodInfo;
    object[]
        parameters;

    methodInfo = typeof( Array ).GetMethod(
        "Resize",
        BindingFlags.Public | BindingFlags.Static );
    genericMethodInfo = methodInfo.MakeGenericMethod(
        theArray.GetType().GetElementType() );
    parameters = new object[] { theArray, newSize };
    genericMethodInfo.Invoke( null, parameters );
    theArray = (Array) parameters[ 0 ];
}

Calling the generic Array.Resize(...) function is working, in that parameters[0] contains the re-sized array, but it didn't change the theArray variable. Setting theArray to parameters[0] partially works, in that arrayOfInts in the calling function gets re-sized, but that seems to disconnect the ints array from arrayOfInts.

How can I change this so that the ints array gets resized?

Thanks in advance.





Runtime code generation, custom attributes on properties and CustomAttributes versus GetCustomAttributes

I'm building up a library for handling some network devices. The interface needs to return data of type that depends on what particular device is queried. Additionally, as the client system works with such dynamic data by custom attributes attached to entity properties, I need to be able to add attributes dynamically to my dynamic entities' properties.

Here is how I create the entity type and decorate a property with an attribute (I omitted the code for defining either getters and setters or the backing field)

// creates type builder for requested entity schema
var typeBuilder = GetTypeBuilder();
var attrType = typeof(TestAttribute);

var propertyBuilder = typeBuilder.DefineProperty("TestProp", PropertyAttributes.HasDefault, propertyType, null);
var ctorInfo = attrType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault();
var attributeBuilder = new CustomAttributeBuilder(ctorInfo, new object[] { },
    // here I pass collections of data in order to initialize the attribute
    attrProperties.ToArray(), attrPropertiesValues.ToArray(),
    attrFields.ToArray(), attrFieldsValues.ToArray());

propertyBuilder.SetCustomAttribute(attributeBuilder);

var type = typeBuilder.CreateType();

and here is how I later check for the attribute existence on the property

var obj = Activator.CreateInstance(type);

var prop = obj.GetType().GetProperties().First(x => x.Name == "TestProp");
var attributes = prop.GetCustomAttributes(typeof(TestAttribute), false);

The problem is that the last line of code (calling GetCustomAttributes) gives me an empty array while the property prop.CustomAttributes contains an array of one element and that element is my TestAttribute.

Can anyone explain to me the difference? I think I need to have this GetCustomAttributes to work as I cannot be sure what way of retrieving the attributes is used in the client system.

Does it matter that TestAttribute is a member class of my tests' suite class?





Do all Type classes inherit from RuntimeType?

I want to know whether a on object of type Type is actually a type for a normal class (e.g. Object, Int32, etc.) or a type for a meta-object (e.g. typeof(Object), typeof(Int32), etc.).

By type of an object I mean:

Type t = typeof(Object);
Console.WriteLine("Type is {0}", t.FullName);

Type is System.Object

And by type of a type object, i.e. meta-object:

Type t = typeof(Object).GetType();
Console.WriteLine("Type is {0}", t.FullName);

Type is System.RuntimeType

I couldn't find any method/property in Type or TypeInfo to tell whether the object for which a Type object is made is actually a Type rather than a normal object.

If I have the object, I could do that:

bool IsType(object o) { return o is Type; }

But, I don't have the object itself, only its type.

I was hoping for something along the lines:

bool IsType(Type t) { return t.GetTypeInfo().IsType; }

But there's nothing like it, it seems..

So the only thing I can think of so far is:

bool IsType(Type type)
{
    // Can't use typeof(RuntimeType) due to its protection level
    Type runtimeType = typeof(Object).GetType();
    return runtimeType.Equals(type);
}

Yet, I can't be sure that GetType() for all objects of type Type would return RuntimeType, nor that they actually inherit from it...





vendredi 23 octobre 2015

Use one implementation of an interface depending on used generic in implementation

I have two interfaces. One interface contains information, and the second interface is supposed to use the first interface. The second interface have one generic(s) that has to be a implementation of the first interface.

I want to automatically use the implementation of the second interface depending on what implementation of the first interface I receive.

Let me show the interfaces. (I changed domain and simplified it, but you get the basic idea.)

//This contains information needed to publish some information
//elsewhere, on a specific channel (MQ, Facebook, and so on)
public interface PubInfo {

    String getUserName();
    String getPassword();
    String getUrl();

    Map<String, String> getPublishingSettings();
} 



//Implementation of this interface should be for one implementation 
//PubInfo
public interface Publisher<T extends PubInfo> {
    void publish(T pubInfo, String message);
}

Lets assume I would have these implementations of PubInfo...

public class FacebookPubInfo implements PubInfo {
    // ...
}

.

public class TwitterPubInfo implements PubInfo {
    // ...
}

...and these of Publisher

public class FacebookPublisher implements Publisher<FacebookPublisher> {

    @Override
    public void publish(FacebookPublisher pubInfo, String message) {
        // ... do something
    }
}

.

public class TwitterPublisher implements Publisher<TwitterPubInfo> {
    // ...
}    

You get the basic idea, two interfaces with two implementations each.

To the question, finally

Now I'll come to the tricky part for me, and that is that I want to be able to automatically use TwitterPublisher when my service gets a TwitterPubInfo.

I can do that with manual mapping, as you see in the example below, but I can't help to think that it would exist a way to do this more automatically, and not depending upon manual mapping. I use spring, and I think that in there, somewhere it would exist a tool to help me with this, or maybe some other utility class, but I can't find anything.

public class PublishingService {

    private Map<Class, Publisher> publishers = new HashMap<Class, Publisher>();

    public PublishingService() {

        // I want to avoid manual mapping like this
        // This map would probably be injected, but 
        // it would still be manually mapped. Injection
        // would just move the problem of keeping a 
        // map up to date.
        publishers.put(FacebookPubInfo.class, new FacebookPublisher());
        publishers.put(TwitterPubInfo.class, new TwitterPublisher());
    }

    public void publish(PubInfo info, String message) {

        // I want to be able to automatically get the correct
        // implementation of Publisher

        Publisher p = publishers.get(info.getClass());
        p.publish(info, message);

    }

}

I could at least populate publishers in PublishingService with reflections, right?

Do I need to do it myself, or is there any help somewhere else with this?

Or, maybe you think the approach is wrong, and that there exists a smarter way to accomplish what I need to do here, feel free to say that and tell me your superior way :p of doing things (really, I appreciate it).





determine if a method has already been called GetValue .net

Is there a .net method that determines whether or not a given method has been previously called for a given object instance?

Sometimes a property getter method has side effects. For instance, a property getter if not called previously may need to create additional objects and perform other work in order to return the value of a backing field. I can't have that happen. If the getter method hasn't been called previously, I don't need the value.

For example...

object item = something;
foreach (PropertyInfo propertyInfoForItem in item.GetProperties(Reflection.BindingFlags.Public)) {
  //Need something to avoid calling this if the property getter method has not been previously been called for this item
  object itemPropertyValue = nothing;
  itemPropertyValue = propertyInfoForItem.GetValue(item, null);
}

I've looked through the MethodInfo class returned from PropertyInfo.GetGetMethod() and didn't spot anything there that would help.

Any ideas?





C#: Attribute on collection element

In C# can attribute be applied to element, which will be packed in collection? I have Dictionary<string,Func<int,int,int>> and add elements in that way

Dictionary<string,Func<int,int,int>> dict = new Dictionary<string,Func<int,int,int>>();

dict.Add("SUM", (a,b) => {return a+b;});

So I want add additional information to element with key "SUM" such as "Returns summary of two numbers". Can this be done with attributes or I must include additional data in collection?





Reflectively look at a variable name, rather than value

Given the class:

class Statics {
  public static String LOC_MY_SELECTOR;

  static void find(String selector) {
    System.out.println(selector);
  }  

  public static void main(String...args) {
    find(LOC_MY_SELECTOR);
  }
}

How am I able to, at the point of System.out.println get the field name, rather than the value? The value is null, so of course it will print out null. What I want to do, is:

find(LOC_MY_SELECTOR); // to print "LOC_MY_SELECTOR" instead of the value `null`

Is this even possible?





How to make map of .class?

I am new to Java Reflection and generics and I am trying to understand them. Here I came accros a problem. I can make Lists and maps of or and other stuff.. But can I make a map of Classes ?

I have for example this class

public class ClassA{}
public class ClassB extends ClassA{}
public class ClassC extends ClassA{} 

and so on.. Now I want a map like this Map(); In this map I can put anyhing that extends from A. Thats good. But what if I want to store something like this:

ClassX extends ClassA... 
//some stuff
Map<String, ?????> customMapForTest = new HashMap<>();
customMapForTest.add("customKey", ClassX.class);

So I will have something like a map of templates of certain classes I want to use dependant on my settings.

Is something like this possible? How is it called if I want to store this kind of .class files in map ?

To get more into the situation I have my own application //Don't worry, this is not a public project or something.. just for experimenting. I have a file with some characters like this : X7WE2C3AD4A2 Just some random stuff. Now I have a file reader that reads each character and based on it it searches the map I created, takes the class of that file and creates new instance of that class and adds some values based on type.

example:

customMapForTesting.get("X").getClass().getDeclaredConstructor(int.class,String.class).newInstance(numberVariable, stringVariable);

I store that new instances to a different map and use it in some other stuff. Problem is I need all possible objects that are extending my template and I don't want to store instances inside the templateMap...





Is there a way to change property names through reflection in C#?

I am using a system where field names need to be prefixed with a given namespace dynamically.

Is there any way I can do something which can achieve something like this -

var properties = item.GetType().GetProperties();
foreach (var pi in properties)
{
    pi.Name = Settings.Default.NameSpace + "_" + pi.Name;
}





LINQ Select on a dynamic type which has a property name that contains period

I have a list with instances of a dynamic type created using reflection. The dynamic type has properties with names that contain a period like HELLO.WORLD. These properties are of type string.

My goal is to select those properties with LINQ using Select

If i try the following

var lstResult = ((IEnumerable<dynamic>)mydynamicdata).Select(d => d.HELLO.WORLD).AsEnumerable().ToList();

I get the error that the collection does not have HELLO property. Any idea how to select this property? Basically I need a list of string as a result.

Creation of dynamic type

    private object CreateDynamicObject(IEnumerable<string> columnsNames)
    {
        Type dynamicType = GetDynamicType(columnsNames);
        object generetedObject = Activator.CreateInstance(dynamicType);

        return generetedObject;
    }

    private Type CreateDynamicObjectType(IEnumerable<string> columnNames)
    {
        // create a dynamic assembly and module 
        var assemblyName = new AssemblyName { Name = "tmpAssembly" };

        AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
        ModuleBuilder module = assemblyBuilder.DefineDynamicModule("tmpModule");

        // create a new type builder
        TypeBuilder typeBuilder = module.DefineType("BindableRow", TypeAttributes.Public | TypeAttributes.Class);

        foreach (var header in columnNames)
        {
            AddProperty(typeBuilder, header, typeof(string));
        }

        // Generate our type
        Type generetedType = typeBuilder.CreateType();

        return generetedType;
    }

    private void AddProperty(TypeBuilder typeBuilder, string propertyName, Type type)
    {
        FieldBuilder field = typeBuilder.DefineField("_" + propertyName, typeof(string), FieldAttributes.Private);
        // Generate a public property
        PropertyBuilder property = typeBuilder.DefineProperty(propertyName, PropertyAttributes.HasDefault, type, null);

        // The property set and property get methods require a special set of attributes:

        const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;

        // Define the "get" accessor method for current private field.
        MethodBuilder currGetPropMthdBldr = typeBuilder.DefineMethod("get_" + property.Name, getSetAttr, type, Type.EmptyTypes);

        // Intermediate Language stuff...
        ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
        currGetIL.Emit(OpCodes.Ldarg_0);
        currGetIL.Emit(OpCodes.Ldfld, field);
        currGetIL.Emit(OpCodes.Ret);

        // Define the "set" accessor method for current private field.
        MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_" + property.Name, getSetAttr, null, new Type[] { type });

        // Again some Intermediate Language stuff...
        ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
        currSetIL.Emit(OpCodes.Ldarg_0);
        currSetIL.Emit(OpCodes.Ldarg_1);
        currSetIL.Emit(OpCodes.Stfld, field);
        currSetIL.Emit(OpCodes.Ret);

        // Last, we must map the two methods created above to our PropertyBuilder to 
        // their corresponding behaviors, "get" and "set" respectively. 
        property.SetGetMethod(currGetPropMthdBldr);
        property.SetSetMethod(currSetPropMthdBldr);
    }

The following is a screenshot from the debugger http://ift.tt/1Mewi5g





Garbage collector reference (dependency) tracking when parameterized constructor invoked from reflection

I'm running into an issue where a reference (a dependency) injected in the constructor of an object is disposed while it should not.

Because this object is constructed by invoking a constructor by reflection, I suspect the garbage collector not tracking the link between the dependency and the object constructed.

Could there be an issue with garbage collected references and objects constructed by reflection ?

Here are more details about the scenario :
- A generic factory is creating an object from its given generic type (TSomeType)

  • To do so we retrieve the constructor via ConstructorInfo contructor = typeof(TSomeType).GetConstructor(typeof(SomeDependencyClass));
  • We then invoke constructor call with constructor.Invoke(new object[]{someDependencyInstance});
  • This instance is then returned by an IoC (ninject) in an ActionFilterAttribute on the OnActionExecuting method, where I store the reference in a class field for the OnActionExecuted method to use it.
  • When using it in the OnActionExecuted, someDependencyInstance has been disposed.

So my question is : could this be due to the fact that the references are not correctly tracked by the Garbage Collector when injecting it in an object by invoking its constructor by reflection ?





How to load .class and call one of its methods

I've compiled at runtime a java file on file system which is a very simple class:

public class Test {

public static int res(int a, int b) {   
    return a*b;
}   

}

now I just want to call res method from my project (that will be a jar), but my code produce java.lang.ClassNotFoundException: Test

and this is how I've loaded the class:

URL[] urls = new URL[] {new URL("file:///"+UtilOverriding.getFile1().replace("java", "class"))};
        URLClassLoader loader = new URLClassLoader(urls);
        Class clazz = loader.loadClass("Test");





Is there a unit testing library for asserting dto-domain object "equality" via reflection?

I want to automatically assert equality of all matching public get-set properties of a domain entity to it's respective DTO. Like AutoMapper but for comparison.

Ideally it should be a narrowly-focused small library rather than an extra feature of a larger one.





jeudi 22 octobre 2015

C# Reflection : call method with class parameters

I've just started out with C# reflection, and I ran into the issue of calling methods that take internal classes as arguments:

Sample class:

public class MyClass 
{
    public class CustomColor 
    {
        public int h;
        public int s;
        public int v;
    }

    public string[] ConvertColors(List<CustomColor> colors)
    {
        //...
    }
}

The code I'm using to call other methods in this class :

FieldInfo info = cInstanceContainerObject.GetType().GetField("_myClass", BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);
dynamic myClassObject = info.GetValue(cInstanceContainerObject);

Allowing me to do this :

myClassObject.SomeSampleMethod(int sampleParam);

However, I'm stuck on figuring out how to create the proper parameters for the ConvertColors method above. :(





Swapping Values Using Reflection [duplicate]

This question already has an answer here:

I have looked up reflections in java, but still don't quite understand them. I need to "swap" values of two local parameters using a reflection. Here is what I have. I know it doesn't swap the values which is why I need to use the reflection. How do I do this?

public class SwapBla {
static int x = 1;
static int y = 2;
 public static void swap2(int x, int y)
 {
   int temp = x;
   x = y;
   y = temp;
 }
}





="" for generic parameters?

I've been looking into ways to mitigate the performance pains of using reflection's .GetValue() and .SetValue() methods. I've discovered some really awesome ways to do it using expression trees, but came upon this answer to a question here:

http://ift.tt/1OLpr3J

It contains a link to this page:

http://ift.tt/1XngGhu

To view the source code, you have to scroll down and click the very inconspicuous expand link below the The code of the helper header. In looking at the code, you will see things like this:

Func<tobject ,="" tvalue="">

What is =""? No matter what I do, I cannot get any variation of this syntax to work. The answer has 6 votes, so I can only assume it's deserving of them.





Object always nothing when invoking System.Reflection.Assembly.GetExecutingAssembly().CreateInstance

Basically, in this code x is always nothing....

dim x as new object
x = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("MyCode.MyClass") 

In effect, what I'm really trying to do, in the end is this... (setting x as an instance of class MyCode.MyClass)...

dim x as new MyCode.MyClass

Do you know what the issue with the first set of code could be?

I know what you may be thinking. "Why not just do it the second way?" Yes, that would be easier. But, now a little background: We have pretty complicated business rules, customer requirements, etc... in our asp.net web app. But, basically, in one of our database tables there is a field which defines the current datatype/class of a variable. This field is a string. So, using this string, and given the various business rules, I need to dynamically define/instantiate my variable x as a certain class. In the above example "MyCode.MyClass" is the string in the field. So, the x object needs to be an instance of this class. Sometimes x will be an instance of "MyCode.MyClass", other times an instance of "MyCode.AnotherClass", etc....

Is there a better solution than what I'm coding above?

Sorry it's so complex.





Using Reflection to update existing Instance

I have a Dictionary this contains value pairs that I want to match and update in an instance of a class I have.

So for example I have;

name -> test
userid -> 1

In my Class I then have

MyClass.Name
MyClass.UserId

I would like to set the MyClass.Name = test, etc

Currently I have the method below;

 public static GridFilters ParseGridFilters(Dictionary<string,string> data, MyClass myClass)
        {
            foreach (KeyValuePair<string, string> kvp in data)
            {
                Type t = typeof(MyClass);
                t.GetProperty(kvp.Value, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

            }

            return myClass;
        }

How do I then check if the kvp.Key is in (regardless of case which I think i've covered with the BindingFlags) and then set the kvp.Value to the myClass.(kvp.Key)





C# Program gets hung up on asynchronous call inside of dynamically added dll

I have a main program and a helper dll that is added programmatically

Main -

public class MainProgram
{
    public MainProgram()
    {

        byte[] dllByteArray = [dllByteArrayHere];
        byte[] pdbByteArray = [pdbByteArrayHere];

        System.Reflection.Assembly myDllAssembly = System.Reflection.Assembly.Load(dllByteArray , pdbByteArray );

        System.Type MyDLLFormType = myDllAssembly.GetType("HelperNamespace.HelperClass");

        var MyDLLFormInstance = myDllAssembly.CreateInstance(MyDLLFormType.ToString());

    }

}

Helper dll-

namespace HelperNamespace
{
    public class HelperClass
    {

        public HelperClass()
        {

            Console.Write("Start");

            using (var client = new HttpClient())
            {

                var values = new Dictionary<string, string>
                {
                   { "Data", "Data" }
                };

                //Communicate with Data Service
                var content = new FormUrlEncodedContent(values);
                var response = await client.PostAsync( [URL], content);
                var responseString = await response.Content.ReadAsStringAsync();

            }

            Console.Write("End"); 
        } 

    }

}

Currently, when I run MainProgram, the helper dll is successfully added. The problem is that while "Start" is outputed to the console, "End" is never reached.

I believe it is stuck awaiting a response on this line:

var responseString = await response.Content.ReadAsStringAsync();

It is important to note that when the dll is added/referenced using the standard method (By adding as reference), everything runs fine and it does not get "Stuck".

Any idea on what might be going on or how I can go about fixing it? Any input will truly be appreciated.





How do I set a private static final field in a class with private constructor using PowerMockito?

I'm trying to set a private static final field in a class with private constructor for a JUnit test. When I boil the code down to its basics, I get the following:

public class Foo {
    private static final boolean FLAG = false;
    private Foo() { /* don't call me */  }
    public static boolean get() { return FLAG; }
}

My tests looks like this:

@RunWith(PowerMockRunner.class)
@PrepareEverythingForTest  // Whitebox fails without this line
public class FooTest {
    @Test
    public void testGet() {
        Whitebox.setInternalState(Foo.class, "FLAG", true);
        assertTrue(Foo.get());
    }
}

And here is an excerpt from my POM file:

<junit.version>4.11</junit.version>
<powermock.version>1.5.4</powermock.version>
<mockito.version>1.9.5</mockito.version>

When I put a breakpoint on return FLAG;, I can clearly see that FLAG was set to true in IntelliJ's debugger. Yet the test fails with an AssertionError.

Any ideas what to do to make this work?





Java Reflection API. Cant instantiate Inner Class if its not public

Please help me in reflection api. I cant instantiate inner class if it hasnt "public" modifier. I have classes:

public abstract class AbstractClass {
  String str;
    public AbstractClass (String str) {
        this.str = str;
    }
  abstract void process(String str);
}

and

public class Outer {  

  class Inner extends AbstractClass{
    Inner(String str) {
        super(str);
    }

    @Override
    void process(String str) {
        //doSmth
    }
  }
}

And i have method in another place like this:

void fillArray (AbstractClass innerAbstract) {
    try {
        ArrayList<AbstractClass> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Object outerClazz = Class.forName(innerAbstract.getClass().getEnclosingClass().getName()).newInstance();
            Class<?> innerReal = Class.forName(innerAbstract.getClass().getName());
            Constructor<?> ctor = innerReal.getConstructor(outerClazz.getClass(), String.class);
            AbstractClass resultClass = (AbstractClass) ctor.newInstance(outerClazz, innerReal.getName());
            list.add(resultClass);
            resultClass.process("STR");
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
            NoSuchMethodException | SecurityException | IllegalArgumentException |
            InvocationTargetException ex) {
        ex.printStackTrace();
    }

}

Inner class - is a realization of AbstractClass. AbstractClass will have a lot of such realizations in different packages and classes.

The question is. All it works fine, when inner classes have public modifier. But it must not be public. When inner classes have public modifier, i can get a list of its constructors with the innerReal.getConstructors().

But when we delete public modifier of Inner - the list of constructors becomes empty. Reflection api lets me to get inner class with its forName() method, but i cant get its instance with the constructor, because it has not any one.

Thanks in advance for any help! =)





How to detect whether Notifications Panel is expanded?

I found this way to expanded Notifications Panel

Object sbservice = getSystemService("statusbar");
Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
Method showsb;
if (Build.VERSION.SDK_INT >= 17) {
    showsb = statusbarManager.getMethod("expandNotificationsPanel");
} else {
    showsb = statusbarManager.getMethod("expand");
}
showsb.invoke(sbservice);

After looking into source, I also found collapsePanels method to collapse the notification

But I cannot find any way to detect the notification panel status

Because I want to check whether it is opened or closed, and then decide I should open it or close it

How can I know this status?





Type.GetType() not working for F# type in C# code

I have an F# assembly called Assembly1

I have the following module:

namespace Assembly1

module MyModule =
   type MyClass(x: int, y: int) =
   new() = MyClass(0, 0)

In a C# assembly that references this F# assembly, the following code gives me a value of 'null' back:

var myType = Type.GetType("Assembly1.MyModule.MyClass, Assembly1");

Is what I am trying to do not possible?





mercredi 21 octobre 2015

Different IL codes for same method body

Let's suppose I have the following class:

public class SomeClass
{
    public int GetValue()
    {
        return 1;
    }
}

Inspecting the generated IL code for this method:

byte[] methodBody = typeof(SomeClass).GetMethod("GetValue").GetMethodBody().GetILAsByteArray();

We get that methodBody is:

[0, 23, 10, 43, 0, 6, 42] -- 7 bytes

Creating my own method using Reflection.Emit:

MethodBuilder methodBuilder = typeBuilder.DefineMethod("GetValue", MethodAttributes.Public, typeof(int), Type.EmptyTypes);
ILGenerator il = methodBuilder.GetILGenerator();
il.Emit(OpCodes.Ldc_I4, 1);
il.Emit(OpCodes.Ret);

//....

byte[] dynamicMethodBody = dynamicType.GetMethod("GetValue").GetMethodBody().GetILAsByteArray();

We get that dynamicMethodBody is:

[32, 1, 0, 0, 0, 42] -- 6 bytes

Why are the two method bodies different? Aren't they exactly the same?

Furthermore, I'm guessing the first two bytes 32 and 1 in my dynamicMethodBody have something to do with loading the constant 1 to the evaluation stack, but why aren't these two bytes present in methodBody?





C# Reflection to find classes that implement interface with multiple open generic parameters

Let's say I have an interface like this:

public interface ITest<T1, T2>
{
}

And a class like this:

public class Concrete : ITest<int, string>
{
}

Using reflection, how can I find this concrete class? I've tried the following but it doesn't work because I'm not specifying the generic type parameters.

var concretes = Assembly.GetAssembly(typeof(Concrete)).GetTypes()
                        .Where(x => x.IsAssignableFrom(typeof(ITest<,>))
                               && !x.IsInterface);

This returns zero items. Is it even possible to do what I'm trying to do?





Java reflection, call method from superClass?

I've seen a lot of examples, and I know what has been discussed. I do everything right, but I receive an error. Why is that? What am i doing wrong?

Class superClass = rootObject.getSuperclass();
      Method addErrorMethod = superClass.getDeclaredMethod("addErrorMessage", ErrorType.class, String.class, String.class, String.class);
      _log.info(addErrorMethod.getName());
      addErrorMethod.invoke(superClass, ErrorType.FIELD, propertyName, message, "");

I get method, but when you call the invoker. I get the following error.

 java.lang.IllegalArgumentException: object is not an instance of declaring class

Thanks.





Getting list properties type using reflection

tI want get list models properties type using reflection. I have a model list and each of list property's type should required for me

List<WebParameters.Params.AnalitikButceKodlariListesiYilOutput> list = new List<WebParameters.Params.AnalitikButceKodlariListesiYilOutput>();

WebParameters.Params.AnalitikButceKodlariListesiYilOutput item = new WebParameters.Params.AnalitikButceKodlariListesiYilOutput()
            {
                KOD = "a",
                KOD_01 = "",
                KOD_02 = "d",
                KOD_03 = "c",
                KOD_04 = "d",
                BUTCE_ADI = "e",
                YIL = 2015
            };

I try this but it wasn't success.

foreach (var pObject in list)
            {
                foreach (var item2 in pObject.GetType().GetProperties())
                {
                       var type = pObject.GetType().GetProperty(item2.Name).GetType().Name;
                }
             }





Can I use reflection on Prism's EventAggregator?

I am trying to refactor some of my methods in the PRISM framework, and it's not really working out.

I need to publish messages through the EventAggregator, and I have written a method which will look at Types and from here send the messages. But it never sends any messages.

It turns out the safecast as PubSubEvent<object> is not the same as public class EventA: PubSubEvent<DataObject> {}, which means the returnObj?.Publish(data); is null and will not be called.

public struct Parameters
{
    public string Topic;
    public Type Input;
    public Type Output;
}


private List<Parameters> _list;
...
void SomeFunction()
{
    _list.ForEach(m =>
    {
        var data = JsonConvert.DeserializeObject(dataString, m.Output);

        var eventAggType = _eventAggregator.GetType();
        var eventMethod = eventAggType.GetMethod("GetEvent");
        var genericMethod = eventMethod.MakeGenericMethod(m.Input);
        var returnObj = genericMethod.Invoke(_eventAggregator, null) as PubSubEvent<object>;
        returnObj?.Publish(data);

        // var datType = returnObj.GetType();
        // if (datType.BaseType.Name == typeof (PubSubEvent<object>).Name)
        // {
        //  var obj = Convert.ChangeType(returnObj, datType);
        //  ((PubSubEvent<object>) obj).Publish(data);
        // }
    }
}

I tried to modify the code by looking at the type it actually outputs (remove the as PubSubEvent<object>), and it's the same baseType. But the casting to a basic PubSubEvent is not something the program is happy about.

Exception thrown: 'System.InvalidCastException' in MyProject.ModuleA.dll

EXCEPTION: Unable to cast object of type 'MyProject.ModuleA.GlobalEvents.EventA' to type 'Microsoft.Practices.Prism.PubSubEvents.PubSubEvent`1[System.Object]'.

How do I Publish with the correct type? It should look like the following, if you knew what classes you were handling:

_eventAggregator.GetEvent<EventA>().Publish(data);