I am writing a control which will generate some JavaScript to write a table row to an HTML table and bind back to an IEnumerable at the server side.
Is there any way I can identify:
how many fields each object has
what these properties are called and
their data types?
Yes, and it's called reflection. Or you can simply provide these values declaratively, like when you create GridView and you specify columns for instance...
http://msdn.microsoft.com/en-us/library/ms173183(v=vs.110).aspx
Look at the Type class and the PropertyInfo class.
Related
this is the more or less the schema i want to generate my dynamic form on based on the fields above. i am going to add the direction , max size, default value and like wise some more fields in it. i am looking for recommended ways and methods in asp.net mvc for generating dynamic fields at runtime.
1) if i design my own engine for it then how? i am interested on that also but this is the last thing i am looking at. method to apply validation is very important in my scenario
2) any framework that may lessen the working time? or anything else?
I'll describe the generic approach, I don't want to code it for you.
Create meta class to describe each field (type, name, maxlength, null value handling, data source for combos, etc.)
Load the data from database and preprocess it
Populate the ViewBag with sanitized values
Create helper that will generated the control specific code
Html.ControlFor("Name", metadata);
Loop in view over the metadata collection.
which will generate textbox, combobox, etc.
Remeber that MVC form handling works over list of key-values, it's the Binder feature that converts it to objects. Saving data won't be difficult (dynamically created INSERT, UPDATE statement, ...).
Greetings all,
I have a list of "Types" meeting a certain critera that I obtained through reflection. Each of the types is a different feature that the user will potentially choose at runtime. If I add more subclasses later, this dynamic implementation would save my having to remember to update the user control is the idea here.
The list of types is nice, but it'd be nice to display something more meaningful than the Name as it's written in code. For example, instead of "RacingBikeDesigner", I'd like to display "Racing Bike Designer", and maybe even display other properties associated with that type like "Description" so that the user knows what that particular choice does.
So I guess the question is, given a Type, how can I provide a more meaningful representation to the user? Could I maybe add a static field to each subclass and call that from the Type, or could I perhaps use a type converter somehow?
The user control (ListBox, ComboBox, etc) is bound to the return value below, but it's not user-friendly:
List<string> LeftHandedUserChoices = new List<string>();
Type[] AllTypesInThisAssembly = Assembly.GetAssembly(typeof(UserChoices)).GetTypes();
foreach (Type _currentType in AllTypesInThisAssembly)
if (_currentType.IsSubclassOf(typeof(UserChoices)))
LeftHandedUserChoices.Add(_currentType.Name);
return LeftHandedUserChoices;
Cheers,
Q
You have a couple of options for doing this. You could use an attribute on your type for the description, or put it in a static field/property on the Type and retrieve that using reflection.
If localization is an issue, you will probably want to store the resource string name, and display the resource value at runtme.
Add custom C# Attributes to your types.
One method is for you to parse class names based on the naming convention you are using (looks like Pascal in your case). For instance RacingBikeDesigner will become Racing Bike Designer. Here is a parsing example.
I want to store list of parameters (that will define how document is going to be generated on the web page) in data base.
There is a number of item (or document) types, each type has a different set of parameters that vary (each type has it's own parameters).
Is it a good idea to store all parameters (key-value) as JSON in table's column?
Otherwise I would have to create Parameter Table for every Type and column for every parameter (10-30 params for every type).
A note: I am not going to search by parameters or something like that.
I will load the the JSON string (if I'll choose JSON), serialize it to Object and apply them on document as usual.
Since you have no requirement of searching by parameters, To me Json seems to be more robust because you will have Object ready with information when you Deserialize it. where as if you store it in columns and table you will have to initialize class members yourself. It will also have performance benifit as there will be only one column to fetch based on your document type.
Conclusion go with Json data in Database
Sounds like you should have a look at http://sisodb.com. However, it does support querying, but that is something you could turn-off and only rely on GetById.
I'm using LINQ to Entities on a database which structure is not known in advance. I use reflection to retrieve the information, and now have a list of strings with all the table names. Because I use LINQ, I also have the datasource encapsulated in a C# class (linqContext), with each table being a property of that class.
What I want to achieve is this:
Assume one of the strings in the table names list is "Employees". This is known in code, I want to do the following:
linqContext.Employees.DoSomethingHere();
Is this possible? I know that if all the propertie were just items in a list, I could use the string as indexer, linqContext["Employees"]. However, this is not the case :(
Firstly I wouldn't use reflection to get this information, I would use the MetadataWorkspace property of the ObjectContext as this already has the information. Something like this:
EntityContainer container = context.MetadataWorkspace
.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
var setNames = container.BaseEntitySets.Select(b =>b.Name);
Once you have the set names you can get the data from a specific set as follows:
context.CreateQuery<T>("[" + entitySetName + "]");
The generic repository I use actually searches the container for the entity set that matches a given type so that calling code can just pass the type in and get back the appropriate collection.
Use reflection to either retrieve the named property of the DataContext, or to retrieve the entity type and then call DataContext.GetTable(type).
http://msdn.microsoft.com/library/system.reflection.fieldinfo(VS.90).aspx
i´m trying to query a DataTable object without specifying the fields, like this :
var linqdata = from ItemA in ItemData.AsEnumerable()
select ItemA
but the returning type is
System.Data.EnumerableRowCollection<System.Data.DataRow>
and I need the following returning type
System.Data.EnumerableRowCollection<<object,object>>
(like the standard anonymous type)
Any idea?
Thanks
If I understand you correctly, you'd like to get a collection of objects that you don't need to define in your code but that are usable in a strongly typed fashion. Sadly, no you can't.
An anonymous type seems like some kind of variant or dynamic object, but it is in fact a strongly typed class that is defined at compile time. .NET defines the type for you automatically behind the scenes. In order for .net to be able to do this, it has to have some clue from the code with which to infer the type definition. It has to have something like:
from ItemA in ItemData.AsEnumerable()
select ItemA.Item("Name"), ItemA.Item("Email")
so it knows what members to define. There's no way to get around it, the information has to logically be there for the anonymous type to be defined.
Depending on why exactly your are trying to do this, there are some options.
If you want intellisense while still encapsulating your data access, you can return xml instead of a datatable from your encapsulated data access class. (You can convert data tables to xml very easily. You'll want to use the new System.Xml.Linq classes like the XElement. They're great!) Then you can use VS2008's ability to create an xsd schema from xml. Then use/import that schema at the top of your code page, and you have intellisense.
If you have to have an object an with properties for your data, but don't want to define a class/structure for them, you'll love the new dynamic objects coming in C#4.0/VB10. You have object properties based on what the sql returns, but you won't have intellisense. There is also a performance cost to this, but (a) that might not matter for your situation and (b) it actually is not so bad in some situations.
If you're just trying to avoid making a lot of classes, consider defining structs/structures on the same code file, beneath your class definition. When you add more columns to your result set, it's easy to adjust a struct with more public fields.
In short you can have any two of the following three: (a) dynamic, (b) strontly-typed objects, (3) intellisense. But not all three.
There is one way to accomplish what you want, but it required knowledge of dynamic linq. You would build the query during run-time and then use it. I am no expert and have never really played around with it, but here is a link to Scott Guthrie's blog about it - Dynamic Linq. Hope that helps.
Wade