AutoMapper pivot configuration

In our project we’re AutoMapper to transform a list of name – value pairs to objects with properties. It pivots by mapping the name of the pair to the property and assigning the value to it.

We created an extension method that takes a Func to return the Name and a Func to return the Value. The configuration is very short when using this extension method. See the listing below

Mapper.CreateMap<List<Data>, Person>()
      .ConvertFromList(x => x.Name, x => x.Value);

The List with Data objects is the name-value pairs, where Person is the actual object with the properties mapped by the name.

The extension method looks impressive, but that is because of the Name and Value Func and not because of the complexity.

public static IMappingExpression<List<TSource>, TDest> ConvertFromList<TSource, TDest>(
    this IMappingExpression<List<TSource>, TDest> exp,
    Func<TSource, string> name,  // Function to return the Name
    Func<TSource, object> value) // Function to return the Value 
{
    var allPropertyFlags = BindingFlags.Instance | 
                           BindingFlags.Public | 
                           BindingFlags.NonPublic;
    foreach (var prop in typeof(TDest).GetProperties(allPropertyFlags)) {
        // map with value (implicit conversion) of the first item with Name equal to the property name
        exp.ForMember(prop.Name, map => map.MapFrom(src => value(src.First(s => name(s) == prop.Name))));
        // only when name exists will there be mapped
        exp.ForMember(prop.Name, map => map.Condition(src => src.Any(s => name(s) == prop.Name)));
    }
    return exp;
}

We’re happy with the current configuration, but we think case sensitivity could get an issue.

References

AutoMapper Dictionary Flattening on stackoverflow, origional source for our solution

Posted in Development | Tagged , | Leave a comment

Week roundup

Last week recap and links:
Image courtesy of kanate / FreeDigitalPhotos.net

Image courtesy of kanate / FreeDigitalPhotos.net

What are your best reads this week? Leave them in the comments below.

Posted in Uncategorized | Tagged , , , , , | Leave a comment

ASP.NET MVC WebApi and Xml serialization

In our project we use XSD to describe messages over project boundaries. This way we can all develop in our own speed. The XSD describes XML with attributes and elements. ASP.NET MVC WebApi supports this, but not out-of-the-box. Default the datacontract serializer is used and that uses elements.

Consider the message class

// the (simplified) class generated from the xsd
[Serializable]
public class HelloWorld {
    [System.Xml.Serialization.XmlAttribute]
    public int Id { get; set; }
    [System.Xml.Serialization.XmlAttribute]
    public string Sender { get; set; }
}

Using all the defaults and the HttpClient code below

using (var client = new HttpClient()) {
    var task = client.PostAsXmlAsync<HelloWorld>(uri, 
        new HelloWorld { Id = 10, Sender = "eric" });
    task.Wait();
    // do something with task.Result.IsSuccessStatusCode
}

The message send over the wire (caught with Fiddler) is nothing like the expected XML. If we would validate using the XSD this would fail.

<HelloWorld xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
            xmlns="http://schemas.datacontract.org/2004/07/Messsages">
<_x003C_Id_x003E_k__BackingField>10</_x003C_Id_x003E_k__BackingField>
<_x003C_Sender_x003E_k__BackingField>eric</_x003C_Sender_x003E_k__BackingField>
</HelloWorld>

To get the correct message we must use the Xml Serializer. This can be set on the HttpClient

using (var client = new HttpClient()) {
    var task = client.PostAsync<HelloWorld>(uri,
        new HelloWorld { Id = 10, Sender = "eric" },
        new XmlMediaTypeFormatter { UseXmlSerializer = true }
    );
    task.Wait();
    // do something with task.Result.IsSuccessStatusCode
}

This will generate the correct Xml

<HelloWorld xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
            xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
            Id="10" 
            Sender="eric" />

The message is now in the correct Xml, but the server cannot read it since that is still using the default. Change the server side serializer in the config and you’re good to go.

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Web API configuration and services
        config.Formatters.XmlFormatter.SetSerializer<HelloWorld>(
                new XmlSerializer(typeof(HelloWorld)));
        // Web API routes
        config.MapHttpAttributeRoutes();
        // other code ....
    }
}

Even with this change in configuration the Json format can be used. Hurrah for ASP.NET MVC WebApi!

Posted in Development | Tagged , , , , , | Leave a comment

Open your application to Powershell

The SDN – Software Development Network – is a special interest group for dutch developers. Four times a year they organise an event where people present and talk about their passion.

As a member of the SDN you are aware of the latest developments. You are part of a network of professional developers who assist each other in word and deed. This means there is a technical helpdesk at your fingertips so you can book considerable time savings in solving problems.
sdn.nl with Google translate

This meeting I did a talk called “Open you application to Powershell”.

Quick recap

I showed a demo I created with an Ops colleague. The demo is a ASP.NET MVC website with a members only area but without the signup. All users must be created with a powershell commandlet. This powershell commandlet accepts objects from the pipeline to allow easy creation by importing a CSV.

My talk was recorded using Google Hangouts, you can check it on youtube. [dutch]

Slides on my dropbox

Posted in Conference | Tagged , , , , , | 2 Comments

Week roundup

Last week recap and links:
Image courtesy of kanate / FreeDigitalPhotos.net

  • Autorest on Azure Friday. Using swagger to generate proxy code to REST API, like you would use WSDL for a webservice
  • ARM and PowerShell DSC working together to create and provision a VM
  • I’m running a marathon! 5 tips from the Ginger Runner

Image courtesy of kanate / FreeDigitalPhotos.net

What are your best reads this week? Leave them in the comments below.

Posted in Uncategorized | Tagged , , , , , , , | Leave a comment