can any body have idea for create dynamic class at run time.i have one dictionary<string,object> which is contains datatable's all columns with it's datatype my plan is to create a dynamic class base on dictionary. means datatable's column name is property of class. after create list<dynamic class> and bind to grid
it's grate help if you have code for it
meta-programming on Silverlight is fairly limited, but TypeBuilder is probably what you are looking for. An easier option, though, is to use ExpandoObject and dynamic, but frankly: you might as well just use the dictionary. I'm not sure I'd bother going to the trouble of meta-programming for this.
If you do go that route, you can get a new empty list via:
IList list = (IList)Activator.CreateInstance(
typeof(List<>).MakeGenericType(newType));
Related
I am building web service in C# for a particular application, I have a XML definition of module. I have created a class called Field that holds the properties of all fields on a module. What I would like to do is create the field objects but name them dynamically then add them to a list of some sort. So when I reference them from the client it would be like this:
Module.Fields.MyDynamicName.FieldProperty
Is this possible to do? and could anyone point me in the right direction on how to do this.
Hope my question makes sense.
Basically you need to design for "deferred design", which means you do not know at compile time what the design is, but you still need to accommodate it.
There are probably a few ways but what I have done in the past is use a dictionary list of Key/Value pairs to store fields. Using serialization (I prefer Json) you can shove just about anything into a string and store it as the Value, then deserialize it when you need it.
I'm trying to create objects dynamically but I don't know how to. What I need is, I have a class for that object, and objects properties are stored in the database. Then I'll need to compare the properties of each object to get the desired result.
So I need to dynamically create objects on the fly with the properties loaded from database.
I don't think you need to create objects dynamically, just create one statically that matches your db schema with the property details, then you can compare the values of the properties across rows, or within an instance of your object.
I have been working on something similar to this. There are several things:
Include the System.Reflection namespace
Create an object dynamically using Activator
Get the object properties using the myObjectType.GetProperties() method
Here is an example of a generic object creation function using the above methods:
using System.Reflection;
public static Item CreateItem<Item>(object[] constructorArgs, object[] propertyVals)
{
//Get the object type
Type t = typeof(Item);
//Create object instance
Item myItem = (Item)Activator.CreateInstance(t, constructorArgs);
//Get and fill the properties
PropertyInfo[] pInfoArr = t.GetProperties();
for (int i = 0; i < pInfoArr.Length; ++i)
pInfo.SetValue(myItem, propertyVals[i], null); //The last argument is for indexed properties
return myItem;
}
Of course the above example assumes that the values in the property value array are arranged correctly, which is not necessarily the case, but you get the idea.
With the PropertyInfo class you can get properties, get property names, get attributes associated with the properties, etc. Powerful technology. You should be able to do what you need with the above info, but if not let me know and I will add more info.
If you have a number of objects you want to instantiate from database values it can be done something like this.
//database code goes here, results go in results
List<ClassName> l = new List<ClassName>()
foreach(Row r in results){
l.Add(new ClassName(){ClassProperty1 = r.Property1,ClassProperty2 = r.Property2});
}
Are you talking about Dictionary?
var dict=new Dictionary<string, string>();
dict.Add("property1", "val1");
dict.Add("property2", "val2");
var prop2val=dict["property2"];
Maybe Activator is what your looking for?
http://msdn.microsoft.com/en-us/library/system.activator.aspx
Check this class, compile in the realtime. But it's performance is not quite good.
http://msdn.microsoft.com/zh-cn/library/microsoft.csharp.csharpcodeprovider(VS.80).aspx
You could use reflection to dynamically build your objects:
Reflection msdn reference
I think that you want to retrieve rows from the DB and directly assign them to object given that the properties of the object are equivalent to the columns of DB table. If that what you mean then I believe you can't :)
Rob Conery did a small project called Massive that pretty much does what you're trying to accomplish. It's essentially a small ORM, in 400 lines of Dynamic C# 4.0 code.
Rob has been doing this kind of thing for quite some time with SubSonic, so you might find his approach with Massive quite interesting.
http://blog.wekeroad.com/helpy-stuff/and-i-shall-call-it-massive
Some of the code is explained here, with examples:
http://blog.wekeroad.com/microsoft/the-super-dynamic-massive-freakshow
I am currently referencing a generic DataSet via an index and would like to convert this to a strongly-typed DataSet of the table type. The issue is that my index to the DataRow is a variable.
Currently I am doing the following where the History_Column value is pulled from the database.
e.Dr[c.History_Column.ToString()] = Entry;
I would like to define the DataRow ('Dr' in the example) as a type of the table so I can do something similar to the following:
e.Dr.COLUMN_NAME = Entry;
How can I use dynamic variables in this fashion?
Thanks!
You could use a dynamic type to get you part of the way there, but your goal sounds kind of contradictory.
dynamic Dr = new ExpandoObject();
Dr.whatever = 6;
Dr.anything = "asdf";
If you use ExpandoObject with dynamic, you can assign any property.
A strongly-typed dataset is a class in your application that derives from the built-in dataset class. You have to add them to your project in visual studio. Here are some directions for creating strongly typed datasets.
However, I suggest that you take the opportunity to refactor and get away from datasets altogether (if you can). Entity Framework provides strongly typed property accessors for each column, a better "unit-of-work" pattern, a graphical database mapping tool, and it is much easier to use.
I have a record type like this:
type Rule = {extension: string seq; subdir: string}
let rules : Rule list = // ...
And I want to bind it's instance to DataGridView. All my UI logic is implemented with C#. What is the best way to do this? Just make a reference to FSharp.Core in my C# project and bind? Or to make some simple record like this
type SimpleRule = {extension: string; subdir: string}
and a function that converts Rule list to a SimpleRule seq, which is represented as IEnumerable in C#.
The second way seems to be the best because I don't need to make a reference to FSharp.Core and I will work with IEnumerable, but there is too much conversion code and I am having problems with writing it. Maybe there is a better way to solve the problem?
I ended up using mutable record. Also I've created some wrapper-class for my library, which have several methods to add/delete rules and apply them, so I don't use any of F# classes such as FSharpList in C#.
Currently, I've created a class with ~30 properties to be set. This is done to build up a URL request later on(ie, "http://www.domain.com/test.htm?var1=a&var2=b...&var30=dd").
The issue I'm facing is the property names don't necessarily match the query variable names(this is intended to be different). For example, I may have a variable titled "BillAddress", whereas the query variable will need to be "as_billaddress".
I have no control over the query variable naming scheme as these are set at an external source.
One possible solution I've used is creating a custom attribute and decorating the properties with their respective query counterparts:
[CustomQueryAttribute("as_billaddress")]
string BillAddress{get;set;}
To retrieve the attribute though, requires a little reflection and due to the larger number of properties, I was curious if there is a neater way to accomplish this functionality. Not so much as setting/retrieving custom attributes without reflection, but being able to tie an alternate string variable to any property.
I've also pondered about setting each variable up as a sort of KeyValuePair, with each key representing the query counterpart, but I didn't get too far in that thought.
To summarize/clarify my above backstory, what would you do to associate a string with a property(not the value of the property)?
As always, any comments are greatly appreciated.
I would probably stick with a custom attribute, but the other potential option would be to do something like hold a static Dictionary that had string and property info (or property name), so you could get/set the property directly via this.
Something like:
static Dictionary<string, PropertyInfo> propertyMap = new Dictionary<string, PropertyInfo>();
static MyClass()
{
Type myClass = typeof(MyClass);
// For each property you want to support:
propertyMap.Add("as_billaddress", MyClass.GetProperty("BillAddress"));
// ...
}
You could then just do a dictionary lookup instead of using reflection in each call... This could also be setup fairly easy using configuration, so you could reconfigure the mappings at runtime.
A custom attribute seems like the best option to me - the framework seems to do this a lot as well (specifically with serialization).
If you look at popular ORM mappers then nearly all either use custom attributes or some kind of XML mapping file. The advantage of the latter is that you can modify the mapping without recompiling your application - the downside is that it hurts performance. However, I'd say your choice seems perfectly reasonable.