Model conversion coverage - c#

We recently introduced a completely new data model which is different from our current model from the logical structure point of view. We also changed the language of the model from German to English, because we want to open the models structure as XML to our customer.
In order to be able to convert the model we implemented a explicit conversion which basically matches all properties from the different classes of the new model into our old model.
Like this:
private OldModel Convert(NewModel src)
{
var dst = new OldModel();
dst.Prop1 = src.SomeOtherProp
dst.Prop2 = Convert(src.ComplexProp);
//....
return dst;
}
Now we want to make sure, all of the properties of the new model are written into the old model for coverage and testing purposes. We also want to make sure we didn't forget any property and also guarantee that for future model extensions, we don't forget a property.
My idea would be to parse the codefile, extract all properties which are read from the new model, run over the new model with reflection compare them with the actual properties within it.
This solution feels not like a good one :-) Any suggestions?
I appreciate any help!

I suggest to use mapping libs like AutoMapper. They allow to configure mapping, converters and operate with public properties and specific methods.

We finally decided to parse the codefile with regular expressions like this:
#"private static [a-zA-Z0-9.]+[ ]+Convert[(][^)]*[)]\s*[{](?<body>[^{}]*(((?<Open>[{])[^{}]*)+((?<Close-Open>[}])[^{}]*)+)*(?(Open)(?!)))[}]";
It will match methods like this private static Namespace.ClassName Convert(Namespace.ClassName input) and will extract the methods body.
Since the converter methods follow a simple structural pattern, it was easy to extract the information I needed.

Related

Entity Framework conversion of data type (Data mapping)

If I have a dictionary,
e.g. var results = (IDictionary<string, object>)fb.Get("me");
And that dictionary contains primitives, arrays and dictionaries of data can it be passed as a model directly? How does one override a mapping of a particular entry, say I want the date to be stored as a string formatted in a certain way.
Atm I'm doing the custom mapping in the Controller, but that has already started to become messy having all parsing code in the one place.
The alternative is I pass the dictionary in to the constructor of the model, and do the class specific parsing there..
Create a new class for the parsing logic rather than complicate your controller or your model. This parsing service class would contain all the messy parsing logic. This will keep your controller and model much cleaner.
var parsingService = new ParsingService(tb.Get("me"));
var model = parsingService.GetModel();

Custom Data Annotations ( DataType )

Is it possible to add new datatypes to the existing DataAnnotations (I'm not looking for a validator but a raw data type). For example
Currnetly you have
[DataType(DataType.Html)]
public string Footer {get; set;}
And into the mix you can add ~Views/Shared/EditorTemplates/Html.cshtml
I'd like to be able to add [DataType(DataType.CSS)] I know in theory I could use a UIHint for adding a specific view, but if possible I'd like to do it at an even earlier stage and specify the datatype rather than relying on UI Hints.
Any pointers would be greatly appreciated. A Quick search of S.O seems a lot of answers around Custom meta-data types, custom validators, and multiple datatyps but I can't seem to find one for adding a new core data-type.
DataType has a second constructor that takes a string. However, internally, this is actually the same as using the UIHint attribute.
Adding a new core DataType is not possible since the DataType enumeration is part of the .NET framework. The closest thing you can do is to create a new class that inherits from the DataTypeAttribute. Then you can add a new constructor with your own DataType enumeration.
public NewDataTypeAttribute(DataType dataType) : base(dataType) { }
public NewDataTypeAttribute(NewDataType newDataType) : base (newDataType.ToString()) { }
Yes, you can. DataTypeAttribute has a constructor that accepts string.

Linq to DataTable without enumerating fields

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

Update base properties - ASP.NET MVC- c#

I have the following code in a model
base.Name = instance.Name;
base.SSN = instance.SSN;
base.DateModified = DateTime.Now
base.ClienType = instance.ClientType;
If I add more properties to my base then i have to update my model to update the properties. Is there an easier way to update the base.properties instead of listing each of them and then updating the same?
Yes i know i am being lazy
I'm not quite sure why you are doing this, but you might want to take a look at AutoMapper - if your properties are the same on both side you can get it to automatically map one to the other without doing any real setup.
You could use Automapper to automatically map where there is a naming convention.
Also beware that things the following would not map as one has one less t
base.ClienType = instance.ClientType;

PostSharp for an object mapper

I'm considering using PostSharp for entity-to-DTO and DTO-to-entity mapper. To do that task manualy for about a 100 entities would be a maintenence nightmare. I've looked at AutoMapper on codeplex, but i think the overhead might be a serious problem in my case, besides i feel that PostSharp could give me some extra control over the mapping convention. If anyone can share any experiences with this king of problems, that would be great.
The direction i'm think in is something like this (please somebody tell me if this is not possible):
The aspect that i am planing to stick to a class would fill the next two methods with content:
EntityType EntityToDTO(DTOType DTO) {}
DTOType DTOToEntity(EntityType Entity) {}
The first method would return entity based on DTO, the second one would do the oposite. Inside the aspect i'm planing to loop through each property, create new target and asign the value of a property to the counterpart from target object. Is this possible to do at compiletime witout any runtime overhead?
If your DTOs field names match your entity field names, then I'd use Duck Typing
http://www.deftflux.net/blog/page/Duck-Typing-Project.aspx
http://haacked.com/archive/2007/08/19/why-duck-typing-matters-to-c-developers.aspx
Your code would work like this
UserDTO user = DuckTyping.Cast<UserDTO>(userEntity);
Basically, the duck typing library will be mapping over the fields by matching the names. They use dynamically generated IL to archive this.
If that has the potential of being too slow, I'd probably try to get CodeSmith to generate the methods for me.
If it helps, there is a project called PostSharp4ET that basically implements support for POCO objects to Entity Framework 1. See http://www.codeplex.com/efcontrib.
Note that PostSharp is not very good at generating new code. It is good at mixing new code with existing one. If you need to generate code, I would recommend writing a C# code generator based on reflection, and compile the resulting code. Or use a tool like CodeSmith, as mentioned previously.

Categories

Resources