Automapper AssertConfigurationIsValid stricter control - c#

I just discovered I get no errors if there is no mapping to a property if the source has a property with the same name. We are trying to make it as strict as possible and get errors when there are unmapped properties. It seems like Assert.IsConfigurationValid() doesn't do that. Is there a way to make it work with stricter control?

I dont believe that there is. I had a similar problem on a recent project.
What we did was ensure that every property on the target was specified in the mapping configuration in alphabetical order. Even if it was being ignored.
When errors occured it was possible to do a "visual" check of the target to see if any properties had been added / missed.

Related

Resharper multiple property generation

This might be a lazy request, but is there a way to generate multiple class properties at the same time? Currently, I have a large list of undefined properties and I can simply go through the list, one by one, and generate a property - but it would be ideal to highlight them all and generate one for each, example illustration below...
You can see here that prop1, prop2...etc have errors since the properties don't yet exist, but you can generate a property with resharper...
However, this seems to be one-at-a-time, I was wondering if I am missing a setting?
I've been using Resharper for 5+ years and I'm using Resharper 9.1.3 Ultimate and I don't think what you want is possible.
The only way to make ReSharper create multiple properties at once is to have it implement missing properties from an interface. It might be worth creating a feature request!

Entity Framework Exception: Ambiguous match found

I get the error:
Ambiguous match found
During this code on the .Add
var db = new NexusEntities();
db.Reports.Add(mmr);
From googling it appears to be an issue if the there are two classes with the same name but in different namespaces. As far as I can tell this is not the case... Is there another reason why this error can happen? Or is there a way to tell which parameter it is finding two of?
This is a "weakness" in EF. It happens when the same property appears in class / subtype hierarchy.
Most likely you have a hidden field. i.e. a property that has been redefined.
When EF looks for the a property it too must use the type/base tree to find the property. But if it finds it twice in the tree, it interprets this as a duplicate. EF doesnt just use the lowest most specific override.
So property hiding is not possible with EF.
Check your classes, a property will occur twice somewhere.
Although this is probably a much less likely scenario, but we were running EF Core 1.0 which had only one version of the Include() method... in version 1.1, Microsoft added a second implementation (the string version) and since we were calling this method dynamically we got this error after updating our EF Core to 1.1

Force the usage of an attribute on properties, if they already have another attribute

I want to force the usage of an attribute, if another attribute is used.
If a special 3rd party attribute is attached to a property, this attribute also needs to be given to a property.
Is there any possibility of doing this?
For example:
[Some3rdPartyAttribute("...")]
[RequiredAttribute("...)]
public bool Example{get; set;}
should bring no compile error,
[Some3rdPartyAttribute("...")]
public bool Example{get; set;}
should bring a compile error or warning.
The attribute itself is definded like the example from http://msdn.microsoft.com/en-US/library/z919e8tw(v=vs.80).aspx itself . But how to force the usage of the attribute if another attribute is used?
Unfortunately you cannot generate custom compiler warnings from attributes. Some attributes like System.ObsoleteAttribute will generate a warning or error, but this is hard-coded into the C# compiler. You should find another solution to your problem, maybe letting Some3rdPartyAttribute inherit from RequiredAttribute?
Otherwise you have to change the compiler.
Another option is using some AOP techniques. Like for example:
PostSharp.
Using it you can at compilation analyze yur code and emit a error if some condition does not sutisfies your requirements.
For concrete example on attributes, can have a look on :
PostSharp 2.1: Reflecting Custom Attributes
You can make a console app, that will iterate trough all types in your assembly trough reflection, check if the rule is satisfied and return 0 if it is, and some other error code and output error if the rule is broken.
Then make this console app run as post-build task.
As far as I know, there is no way to check for attributes at compile time.
I recently needed to enforce something similar (all classes derived from a certain base class need certain attributes). I ended up putting a manual check (with [Conditional("DEBUG")]) using reflection into the constructor of the base class. This way, whenever someone creates an instance of a class with missing attributes, they get an exception. But this might not be applicable in your case, if your classes do not all derive from the same class.
You could write some code that runs on application start which uses reflection and would then throw runtime exceptions if an attribute was used without the proper match but I believe that's as far as you can go and personally I wouldn't consider that a good approach as you would need to run the application once to make sure it complies with your rules.
Also, take a look at PostSharp which may help you.
How about using #warning + Unit testing? In this way, whenever you run Unit tests, an warning will be generated (or you could just use Debug.Fail instead of #warning)

AutoMapper - why use Map over DynamicMap?

Assuming the objects you're mapping with AutoMapper require no custom mappings, is there ever a point in doing this:
Mapper.CreateMap<Src, Dest>();
// ....
Mapper.Map(SrcObject, DestObj);
If no custom mappings are required, does the above approach gain you anything over just using DynamicMap without the need for any prior configuration?
Mapper.DynamicMap(SrcObject, DestObj);
I do understand that DynamicMap is required when you're mapping anonymous types, but I'm asking about whether DyanmicMap is ever not preferred for static types that require no custom mappings.
Been a while since I last used Automapper, but if I remember correctly:
In order to use Map, you need to specify those Maps explicitly first via CreateMap. Afterwards you can validate your Configuration by calling AssertConfigurationIsValid.
This happens right after launching your application rather than encountering an error mid execution (given that you create the mappings and validate on startup, which is recommended).
Also some types do not match 1:1, so you would want to specify the exact mappings, not sure if DynamicMap makes use of the Maps you have introduced manually, actually I think it does not.
Just checked, DynamicMap falls back on existing Maps in the current version up on github.
It's also a matter of performance since DynamicMap uses reflection more heavily than the Map method, since you have already specified the mapping configuration and most of it does not have to bee asserted on the fly anymore. Not sure if the new version of Automapper is performing caching in this regard by now though.

Deserialization validation

I'm working with a list of fonts that I serialize and deserialize using DataContractSerializer. In between the two steps, it's conceivable that the user has removed a font from their machine. I'd like to check a font name as it's being deserialized to ensure that it still exists on the system. If it doesn't exist, that element is not included in the collection returned by DataContractSerializer.ReadObject().
Specifically, I'm storing a FontFamily and serializing a property that gets FontFamily.Name. In this property's set accessor, I convert the string back into a FontFamily.
The only reasonable alternative to validation that I can think of would be having the property's set accessor ignore invalid values, and filter out the invalid deserialized objects later. I don't like this option, however - is there a more proper way?
Why not take advantage on the OnDeserializedAttribute? Have your callback do the validation and removal of items that are not valid for the client environment.
http://msdn.microsoft.com/en-us/library/ms733734.aspx
I do have some concerns about how you would go about round tripping the data if you remove or modify the data under the covers.
(For example: I remember being particularly frustrated by older versions of MS Publisher as I was working on a document on two different machines hooked up to two different printers. Whenever I modified the file on one machine, Publisher would be reformat the document to target the printer attached to that machine. When I went back to the other machine where I was going to do the actual printing, Publisher would reformat again, but the margins would not be quite right and so I needed to tweak some more.)
You could also implement IXmlSerializable for you class, which would include your own implementation of ReadXml, allowing you to do whatever validation you wanted as the object was being deserialized.

Categories