dimanche 20 novembre 2016

Javascript get Property name from class declaration

Lets have a javascript "class"

  var User= function(id, firstName, lastName) {
      this.id=id;
      this.firstName=firstName;
      this.lastName=lastName
  }
  var user = new User (1,"I", "am");

I would like to reference a specific field name of user class, lets say the id field, without using the String "id"

... something like (user->id).getName(); (should return the String "id")

Note : Enumerating the user Object properties is not helping me since I will have to choose among them using the String "id" and so hard code somewhere

hope I am clear.

The goal is to select some properties of user Object to fill in a table without hard coding the object properties as Strings. Thanks





Strange reflection error on inferred type

I have some strange effects when trying to run f# code via reflection.
Given the following type

type Box<'a, 'b> = Box of 'a * 'b

and this function

//iToS :: Box<'a,'b> -> Box<string,'b>
let iToS (Box (i, v)) = Box ((sprintf "%A" i), v)

I can easily and correctly run the following code

let r01 = iToS (Box (1, 1))

However I need to run this function at the sharp edges of my system boundaries and the only way to do so is to fall back on reflection usage.
So I created this function that should take a function like the above and a record of the given type and apply it.

let convert<'t> (f:Quotations.Expr) (v:'a) : 't =
    let methi e =
        let rec methi' e =
            match e with
                | Call (x, mi, y) -> mi
                | Lambda (_, body) -> methi' body
                | _ -> failwith <| sprintf "not a function %A" e
        methi' e

    let apply f v =
        let m = methi f
        m.Invoke(null, [|box v|])

    apply f v :?> 't

If I now run this however like below.

let r10 = (convert<Box<string, int>> <@ iToS @>) (Box (1, 1))

I get the following error

System.ArgumentException : Object of type 'Box`2[System.Int32,System.Int32]' cannot be converted to type 'Box`2[System.Object,System.Object]'.
at System.RuntimeType.CheckValue (System.Object value, System.Reflection.Binder binder, System.Globalization.CultureInfo culture, System.Reflection.BindingFlags invokeAttr) [0x0007d] in <8cd55ece525b4760b63de40980e005aa>:0
at System.Reflection.MonoMethod.ConvertValues (System.Reflection.Binder binder, System.Object[] args, System.Reflection.ParameterInfo[] pinfo, System.Globalization.CultureInfo culture, System.Reflection.BindingFlags invokeAttr) [0x0007f] in <8cd55ece525b4760b63de40980e005aa>:0
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00014] in <8cd55ece525b4760b63de40980e005aa>:0
at System.Reflection.MethodBase.Invoke (System.Object obj, System.Object[] parameters) [0x00000] in <8cd55ece525b4760b63de40980e005aa>:0
at convert[t] (Microsoft.FSharp.Quotations.FSharpExpr f, Box`2[a,b] v) [0x00006] in <5831a15618eafa12a745038356a13158>:0
at test convert () [0x000e6] in <5831a15618eafa12a745038356a13158>:0
at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00038] in <8cd55ece525b4760b63de40980e005aa>:0

Who is trying to convert something into a `Box and why? Any help is appreciated

PS: Some clarafications
a) this is explicitly a question about using reflection within the contaxt of F#
b) yeah, I know my real problem could be solved without reflection and I have done so already. It increases my code size by 40% easily.
c) yeah, I know reflection is dog slow. I am willing to trade speed (i dont need) for cleaner code.





samedi 19 novembre 2016

How can I create classes and Endpoints at runtime?

I would like some directions here.

I need to build a CRM type program (kind of like Salesforce) for a very specific use. However, I need to give the clients the chance of creating new Objects at runtime (like in Salesforce, you have standard objects like Leads, Accounts, Opportunities.. but clients can also create custom objects and fields for these objects at runtime). Besides creating the custom object, Salesforce also creates a SOAP and a REST API for it.

I am programming this solution in Java however I have no idea how I could build the functionality I just mentioned in my program.

Does anyone have an idea?

Thanks.





Set field or property value before constructor

Is it possible to assign a value to a field or property before the constructor of the class and using reflection?

Thank you





Subclass Reflection type error

I'm currently having some issues with a method I made. I use reflection to run through my class and get all it's properties. I use this to cast my models to DTO and vice-versa.

The problem I am encountering is that, whenever my class has another class as an attribute, I get an error.

Object of type 'UserTypeProxy' cannot be converted to type 'MyNamespace.DTO.UserTypeDto'.

This is my code:

public static T Cast<T>(object myobj)
{
    Type _objectType = myobj.GetType();
    Type target = typeof(T);

    var x = Activator.CreateInstance(target, false);

    var z = from source in _objectType.GetMembers().ToList()
            where source.MemberType == MemberTypes.Property
            select source;

    var d = from source in target.GetMembers().ToList()
            where source.MemberType == MemberTypes.Property
            select source;

    List<MemberInfo> members = d.Where(memberInfo => d.Select(c => c.Name)
       .ToList().Contains(memberInfo.Name)).ToList();

    PropertyInfo propertyInfo;
    object value;

    foreach (var memberInfo in members)
    {
        propertyInfo = typeof(T).GetProperty(memberInfo.Name);
        var propy = myobj.GetType().GetProperty(memberInfo.Name);
        value = propy.GetValue(myobj, null);

        propertyInfo.SetValue(x, value, null); //<-- this is the line that gives the error
    }
    return (T)x;
}





Angular 2/Typescript: Get value from [object Object]

I have an angular 2 web application that fires some events. On of the properties of event.target.parentNode looks like this. The nodeValue and value show [object Object]. How can I get the actual content of this object?

enter image description here

Edited to add code:

pressed(event, item: someItem) {
        console.log(event);
  console.log(event.target.parentNode.attributes[1].value);
        console.log("pressed");
    }
<div class="grid" [ngGrid]="{'max_cols': 3, 'auto_resize': true}">
        <sticky-note *ngFor="let item of items"
                     [stickyNote]="sNotes" class="grid-item" [(ngGridItem)]='item.config'
                     (onDragStop)="dragged(item)"  (press)="pressed($event, item)" (pressup)="pressedup($event, item)" #gItem> </sticky-note>
      
    </div>




vendredi 18 novembre 2016

Spring java.lang.NoClassDefFoundError in CCTOR

I am writting simple app using Spring and Hibernate using following beans definition xml file:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://ift.tt/GArMu6"
    xmlns:xsi="http://ift.tt/ra1lAU"
    xsi:schemaLocation="http://ift.tt/GArMu6
    http://ift.tt/QEDs1e">

   <bean id="hibernateConfiguration" class="pl.wicia.projector.database.DBConfiguration" scope="prototype">
       <constructor-arg name="path" value="pl/wicia/projector/database/cfg.xml"/>
   </bean>

   <bean id="sessionFactory" class="pl.wicia.projector.database.HibernateSessionFactory" scope="prototype">
       <constructor-arg name="dbConfig" ref="hibernateConfiguration"/>
   </bean>

</beans>

Now, I wanted to create data base configuration wrapper using injection by constructor-args:

package pl.wicia.projector.database;

import org.hibernate.cfg.Configuration;

public class DBConfiguration {

    private Configuration configuration;

    public DBConfiguration(String path){
        this.configuration = new Configuration(); <--- this throws Exsception
        this.configuration.configure(path);
    }

    public Configuration getConfiguration() {
        return configuration;
    }
}

And this line produces following exception:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateConfiguration' defined in class path resource [pl/wicia/projector/spring/db_beans.xml]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [pl.wicia.projector.database.DBConfiguration]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: javax/transaction/SystemException
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:279)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1148)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1051)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:325)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1076)
    at pl.wicia.projector.main.Projector.main(Projector.java:23)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [pl.wicia.projector.database.DBConfiguration]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: javax/transaction/SystemException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:122)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:271)
    ... 8 more
Caused by: java.lang.NoClassDefFoundError: javax/transaction/SystemException
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.jboss.logging.Logger$1.run(Logger.java:2554)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.jboss.logging.Logger.getMessageLogger(Logger.java:2529)
    at org.jboss.logging.Logger.getMessageLogger(Logger.java:2516)
    at org.hibernate.internal.CoreLogging.messageLogger(CoreLogging.java:28)
    at org.hibernate.internal.CoreLogging.messageLogger(CoreLogging.java:24)
    at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:86)
    at pl.wicia.projector.database.DBConfiguration.<init>(DBConfiguration.java:22)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
    ... 10 more
Caused by: java.lang.ClassNotFoundException: javax.transaction.SystemException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 25 more

This is how I create my beans:

ApplicationContext context = new ClassPathXmlApplicationContext("pl/wicia/projector/spring/db_beans.xml");
DBConfiguration config = (DBConfiguration)context.getBean("hibernateConfiguration");

Any idea what is happening? :)