Dynamic Type Creation - dynamic

I'm trying to create a dynamic type in .Net.
I want to get a group of Key Value pairs from a DB table and create a new type of object that has a Property-Value relation.
Example:
If I have a row in the table that has a field that says "Licence Plate" and the other field says "STKOVFL". I want to create an object that has a Property called Licence_Plate, and returns the String "STKOVFL".
Is it possible with introspection?
Best Regards!

Here is an very simple example of what your trying to do.
public class ExampleD : DynamicObject
{
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
if (binder.Name == "Licence_Plate")
result = "STKOVFL";
return result != null;
}
}
Console.WriteLine(d.License_Plate);

Related

Bug with my relation HasMany/BelongsTo

I have a model Work with this relation
public function types()
{
return $this->belongsTo('App\Models\Type');
}
And a model Type with this relation
public function works()
{
return $this->hasMany('App\Models\Work');
}
I try to access in my view show view to type but I've a lot of errors
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name
I try this : $work->types()->name for get data.
In my DB, my table 'Works' have a foreignkey 'type_id'.
I would like to get the 'type' of the post. There can be only one per post.
Thank you very much !
Semantically you want to make your relationships like so:
Work
// A work is of a single type
public function type()
{
return $this->belongsTo('App\Models\Type');
}
Type
// A type of work can have many items of work
public function works()
{
return $this->hasMany('App\Models\Work');
}
You can then access the relationship like so:
$type = Work::first()->type // return object of type Type
$works = Type::first()->works // return collection of objects of type Work
EDIT
By accessing the relationship with () you are returning the underlying query builder instance of the relationship and you will need to finish your statement with ->get() like so:
$works = Type::first()->works()->get();
You should have on Work Model:
public function type()
{
return $this->belongsTo('App\Models\Type');
}
and on your view:
$work->type->name;
Since you are not using default id as foreign key you should add
protected $primaryKey = "type_id";
in your model

Scala: How to transform a POJO like object into a SQL insert statement using Scala reflection

I'm facing this (at least for me) interesting task: getting a SQL insert statement from a POJO like object. Let me say I don't need to add a framework between my Scala application and the DB because I just need to insert data into a single DB table.
So, supposing the attributes of my class are named equally to those of the DB table, I'd like to use Scala reflection in order to get from a class like this one
class MyDataObj {
var a:Int = 345
var b:Boolean = false
var c:Double = 1243.98
var d:String = "A random string"
}
a SQL insert statement like this
INSERT INTO table_a (a, b, c, d) values (345, false, 1243.98, 'A random String');
Well, what we need is
1) access to the class attributes
2) access to the attribute types
3) access to the attribute values of the object instance
In order to get something like this
List( ("a","Int",345), ("b","Boolean",false), ("c","Double",1243.98), ... )
that will be easy to transform into what we want.
Up to now, I've just found out how to access to the attributes names
val columns = typeOf[MyDataObj].members.view.filter{_.isTerm}.
filter{!_.isMethod}.map{_.name}.toList
How can I get the rest I need?
Thanks as usual for supporting me.
In your case, you can use the following codes:
val o = new MyDataObj
val attributes = o.getClass.getDeclaredMethods.filter {
_.getReturnType != Void.TYPE
}.map {
method => (method.getName, method.getReturnType, method.invoke(o))
}
Here I use getDeclaredMethods to get the public methods in the MyDataObj. You need to notice that getDeclaredMethods can not get methods in its parent class.
For MyDataObj, getDeclaredMethods will return the following methods:
public double MyDataObj.c()
public boolean MyDataObj.b()
public java.lang.String MyDataObj.d()
public int MyDataObj.a()
public void MyDataObj.c_$eq(double)
public void MyDataObj.d_$eq(java.lang.String)
public void MyDataObj.b_$eq(boolean)
public void MyDataObj.a_$eq(int)
So I add a filter to filter out irrelevant methods.

Converting String to Type class object

I have a table storing datatypes of all the parameters and another table with the parameter values. When I use this in C# console app, how do I create a Type[] with the types present in the table?
Its not clear how you store the type in database. Assuming its the assembly qualified name (eg: System.String)
var types = new List<Type>();
foreach(var row in myTable.AsEnumerable())
{
var typeName = row.Field<string>("ColumnName");
types.Add(Type.GetType(typeName));
}
var array = types.ToArray();

EclipseLink - #ReadTransformer

I have this code:
#Column(name = "foo")
#ReadTransformer(transformerClass=transformer.class)
private Date foo;
public static class transformer implements AttributeTransformer {
#Override
public void initialize(AbstractTransformationMapping atm) {
}
#Override
public Object buildAttributeValue(Record record, Object o, Session sn) {
}
}
My question is, how do I get the value to transform (from column foo) inside of buildAttributeVaule? It is not inside the record array.
You need one or more #WriteTransformer to write the fields you want selected (and thus get them selected), #Column is not used with a transformation mapping.
However, if you just have a single column, then just use a converter instead, #Convert,
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Mapping/Basic_Mappings/Default_Conversions_and_Converters
First check that the SQL generated is reading in the "foo" column by turning on logging. If it is, then check that the database is returning "foo" and not "FOO" - java is case sensitive on string looksups. It could be that "FOO" is in the record instead of "foo".

Dynamic Table Names in Linq to SQL

Hi all I have a horrid database I gotta work with and linq to sql is the option im taking to retrieve data from. anywho im trying to reuse a function by throwing in a different table name based on a user selection and there is no way to my knowledge to modify the TEntity or Table<> in a DataContext Query.
This is my current code.
public void GetRecordsByTableName(string table_name){
string sql = "Select * from " + table_name;
var records = dataContext.ExecuteQuery</*Suppossed Table Name*/>(sql);
ViewData["recordsByTableName"] = records.ToList();
}
I want to populate my ViewData with Enumerable records.
You can call the ExecuteQuery method on the DataContext instance. You will want to call the overload that takes a Type instance, outlined here:
http://msdn.microsoft.com/en-us/library/bb534292.aspx
Assuming that you have a type that is attributed correctly for the table, passing that Type instance for that type and the SQL will give you what you want.
As casperOne already answered, you can use ExecuteQuery method first overload (the one that asks for a Type parameter). Since i had a similar issue and you asked an example, here is one:
public IEnumerable<YourType> RetrieveData(string tableName, string name)
{
string sql = string.Format("Select * FROM {0} where Name = '{1}'", tableName, name);
var result = YourDataContext.ExecuteQuery(typeof(YourType), sql);
return result;
}
Pay attention to YourType since you will have to define a type that has a constructor (it can't be abstract or interface). I'd suggest you create a custom type that has exactly the same attributes that your SQL Table. If you do that, the ExecuteQuery method will automatically 'inject' the values from your table to your custom type. Like that:
//This is a hypothetical table mapped from LINQ DBML
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.ClientData")]
public partial class ClientData : INotifyPropertyChanging, INotifyPropertyChanged
{
private int _ID;
private string _NAME;
private string _AGE;
}
//This would be your custom type that emulates your ClientData table
public class ClientDataCustomType
{
private int _ID;
private string _NAME;
private string _AGE;
}
So, on the former example, the ExecuteQuery method would be:
var result = YourDataContext.ExecuteQuery(typeof(ClientDataCustomType), sql);