vendredi 24 juillet 2015

get method info into attribute in C#

I want to get method info into attribute in C#.

something like this

Attribute

public class ReflectionAttribute : Attribute
    {
      public ReflectionAttribute()
      {      
                //reflection things comes here 

                // for example
                // var myMethod =  this.GetMethodInfo()
      }

    }

Class

 public  class ReflectionTest
    {

      [Reflection()]
      public string SendMessage()
      {

          return "Hello World";

      }

    }

I just want to get information about SendMessage method inside attribute when SendMessage method is invoked.

is it possible?

thank you.





Get rawValue from enum in a generic function

I have some generic reflection code written in swift. In that code I'm having trouble getting the value for properties that are based on an enum. The problem comes down to the fact that I'm not able to execute the .rawValue on the property value which is of type Any. The Swift reflection code will return the enum's value as type Any. So how can I get from an Any to an AnyObject which is the rawValue of the enum.

The only workaround i found so far is extending all enum's with a protocol that has a method that returns a string. Below you can see a unit test that's OK using this workaround.

Is there any way to solve this without adding code to the original enum's?

for my reflection code I need the getRawValue method signature to stay as it is.

class WorkaroundsTests: XCTestCase {
    func testEnumToRaw() {
        let test1 = getRawValue(MyEnumOne.OK)
        XCTAssertTrue(test1 == "OK", "Could nog get the rawvalue using a generic function")
        let test2 = getRawValue(MyEnumTwo.OK)
        XCTAssertTrue(test2 == "1", "Could nog get the rawvalue using a generic function")
    }


    enum MyEnumOne: String, EVRaw {
        case NotOK = "NotOK"
        case OK = "OK"
        func toString() -> String {
            return self.rawValue
        }
    }
    enum MyEnumTwo: Int, EVRaw {
        case NotOK = 0
        case OK = 1
        func toString() -> String {
            return String(self.rawValue)
        }
    }

    func getRawValue(theEnum: Any) -> String {
        // What can we get using reflection:
        let mirror = reflect(theEnum)
        if mirror.disposition == .Aggregate {
            print("Disposition is .Aggregate\n")

            // OK, and now?

            // This does not complile:
            // return enumRawValue(rawValue: theEnum)

            // This works, but I would like to skip this extra protocol
            if let value = theEnum as? EVRaw {
                return value.toString()
            }
        }
        var valueType:Any.Type = mirror.valueType
        print("valueType = \(valueType)\n")
        // No help from these:
        //var value = mirror.value  --> is just theEnum itself
        //var objectIdentifier = mirror.objectIdentifier   --> nil
        //var count = mirror.count   --> 0
        //var summary:String = mirror.summary     --> "(Enum Value)"
        //var quickLookObject = mirror.quickLookObject --> nil

        let toString:String = "\(theEnum)"
        print("\(toString)\n")
        return toString
    }

    func enumRawValue<E: RawRepresentable>(rawValue: E.RawValue) -> String {
        let value = E(rawValue: rawValue)?.rawValue
        return "\(value)"
    }
}

protocol EVRaw {
    func toString() -> String
}





Scala 2.11.6 scala.tools.reflect.package$.ToolBox error at test time

I'm experiencing a strange behavior of the scala 2.11 reflection library.

In a simple application that uses the sorm-framework I can invoke persistence methods from the console:

[INFO] Building sorm-test 1.0-SNAPSHOT

[INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- scala-maven-plugin:3.2.0:console (default-cli) @ sorm-test --- [WARNING] Expected all dependencies to require Scala version: 2.11.6 [WARNING] org.scala-lang:scala-reflect:2.11.0 requires scala version: 2.11.6 [WARNING] sorm-test:sorm-test:1.0-SNAPSHOT requires scala version: 2.11.6 [WARNING] com.github.nikita-volkov:sext:0.2.4 requires scala version: 2.11.6 [WARNING] com.typesafe.scala-logging:scala-logging-slf4j_2.11:2.1.2 requires scala version: 2.11.0 [WARNING] Multiple versions of scala libraries detected! [WARNING] scala-maven-plugin cannot fork scala console!! Running in process Welcome to Scala version 2.11.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_40). Type in expressions to have them evaluated. Type :help for more information.

scala> import TestRun._

import TestRun._

scala> TestRun.dodb()

TestRun.dodb()

Some(Artist(2,Map(Locale(2,en) -> Vector(Nirvana), Locale(1,ru) -> Vector(Нирвана)),Set(Genre(1,Map(Locale(2,en) -> Vector(Rock), Locale(1,ru) -> Vector(Рок))), Genre(2,Map(Locale(2,en) -> Vector(Hard Rock), Locale(1,ru) -> Vector(Тяжёлый рок, Тяжелый рок))), Genre(4,Map(Locale(2,en) -> Vector(Grunge), Locale(1,ru) -> Vector(Грандж))))))

But if I call the same method from a Test (scalatest)

class TestDb  extends FlatSpec with Matchers  {
import TestRun._

"A test db" should "save Stuff" in {
    TestRun.dodb()
}

}

I got this exception:

java.lang.NoSuchMethodError: scala.tools.reflect.package$.ToolBox(Lscala/reflect/api/JavaUniverse$JavaMirror;)Lscala/tools/reflect/ToolBoxFactory;

at sorm.persisted.PersistedClass$.createClass(PersistedClass.scala:104)

Now I triple checked and scaliest is not the issue: it has a dependency from scala 2.11.6 as everything else

INFO] --- scala-maven-plugin:3.2.0:testCompile (compile) @ sorm-test --- [WARNING] Expected all dependencies to require Scala version: 2.11.6 [WARNING] org.scala-lang:scala-reflect:2.11.0 requires scala version: 2.11.0 [WARNING] Multiple versions of scala libraries detected! [WARNING] Zinc server is not available at port 3030 - reverting to normal incremental compile [INFO] Using incremental compilation [INFO] Compiling 1 Scala source to /Users/sam/dev/projects/sorm-test/target/test-classes... [INFO] [INFO] --- maven-surefire-plugin:2.10:test (default-test) @ sorm-test --- [INFO] Surefire report directory: /Users/sam/dev/projects/sorm-test/target/surefire-reports


T E S T S

Running TestDb Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 3.679 sec <<< FAILURE!

Results :

Tests in error: TestDb: scala.tools.reflect.package$.ToolBox(Lscala/reflect/api/JavaUniverse$JavaMirror;)Lscala/tools/reflect/ToolBoxFactory;





How annotation check validation at runtime

I am working with custom annotation building ,I am creating some custom annotation that will validating some data.I am not able to write the annotation processor for that annotation.

i.e. I created a custom annotation UserRole as :

public @interface UserRole
{
    int[] value() default {0};
}

I will use this annotation as follow :

import java.util.List;
public class Demo
{
    public void checkValidUser(@UserRole({1,2})List<Integer> roles){
        // some code here
        }
}

I want to write Annotation processor so that I can check if given list contain any role that is specified in annotation at runtime because I will provide List at runtime. I need help to write that annotation processor.

Thanks in Advance.





How do I declare and invoke a C# object when given the object name as a string?

I have a lot of classes written and I receive a String. I want directly to declare and initiate the class that the value of the String is. I don't want to browse every single class written to see which is. Here is an example:

class Car
{
      public void startCar()
      {
            Console.WriteLine("Car started");
      }
}

class Main
{
      private void treeView1_Click(object sender, EventArgs e)
      {
         String s="Car"
        // I said Car obj because that's the value of the string
         Car obj = new Car();

         // or like this
         value.string obj = new value.string();
         obj.startCar();


      }



}





How to use reflection to solve this?

           {
           IReflectionType1 iType1object = StaticClass1.GetObject1<IReflectionType1>();
           ReflectionType2 object2 = new ReflectionType2("parameter1","parameter2");
           iType1object.RunAsync(
                reflectionObject =>
                    reflectionObject.Method1(object2)
                    .OnCompleted(StaticMethodOne)
                    .OnProgressUpdated(StaticMethodSecond));

            }


   private static void StaticMethodSecond(int i, int i1, string arg3)
    {
        Console.WriteLine("{0} {1} {2}", i, i1, arg3);
    }

    private static void StaticMethodOne(ReflectionObject3 obj3)
    {
         obj3.Method3();
    }

This is my skeleton of problem. I must use reflection because I must load at runtime IReflectionType1,ReflectionType2,Method1,ReflectionObject3,reflectionObject (in async method) And now I have problem how to use reflection to change lambda expression. As i wrote "reflectionObject" is also type to get from reflection The second problem is how to use type from reflection as a parameter(in staticMethodOne)

Please help





jeudi 23 juillet 2015

How to Add to an unknown List property of an object at runtime?

I have a 'Profile' object/class with an IList of 'Addresses', of which, I will only know their type [profile / addresses] at runtime via GetType() / GetProperties() etc., though I wish to .Add to this list e.g.:

var profile = session.Get<ProfileRecord>(1);

dynamic obj = new ExpandoObject();
obj = profile;
obj["Addresses"].Add(addressNew);

This does not work due to:

Cannot apply indexing with [] to an expression of type 'Test.Models.ProfileRecord'.

I've been looking at IDictionary, but have been unsuccessful in my attempts, nor even know if I should be heading down that path - so what is the correct way to go about this? This entire concept is new to me, so please don't over assume my capabilites ;) Many thanks in advance.