Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.






July 2012 - Posts

Using AutoMapper to build base class for mappers between domain classes and models

It is often good idea to isolate our domain model from consuming applications by using service layer and data transfer objects (DTO) or application specific models. Using DTO-s means that we need two-way mapping between domain classes and DTO-s. In this posting I will show you how to use AutoMapper to build generic base class for your mappers.


AutoMapper is powerful object to object mapper that is able to do also smart and complex mappings between objects. Also you can modify existing and define your own mappings. Although it is possible to write way faster lightweight mappers still AutoMapper offers very good performance considering all the nice features it provides.

What’s most important – AutoMapper is easy to use and it fits perfect to the context of this posting.

Why mapping?

To those who have no idea about the problem scope I explain a little bit why mapping between domain classes and application specific models or DTO-s is needed. Often domain classes have complex dependencies between each other and they may also have complex dependencies with their technical environment. Domain classes may have cyclical references that makes it very hard to serialize them to text based formats. And domain classes may be hard to create.

By example, if you are using vendor offered powerful grid component then this component may want to serialize its data source so it can use it on client side to provide quick sorting and filtering of grid data. Moving from server to client means serialization to JSON or XML. If our domain objects have cyclical references (and it is normal they have) then we are in trouble. We have to use something lighter and less powerful, so we use DTO-s and models.

If you go through all complexities mentioned before you will find more issues with using domain classes as models. As we have to use lightweight models we need mappings between domain classes and models.

Base mapper

Instead of writing mapper for each type-pair mappings you can avoid writing many lines of repeating code when using AutoMapper. Here is my base class for mappers.

public abstract class BaseMapper<T, U> where T : BaseEntity where U : BaseDto, new()


    protected IMappingExpression<U, T> DtoToDomainMapping { get; private set; }

    protected IMappingExpression<T, U> DomainToDtoMapping { get; private set; }


    public BaseMapper()


        DomainToDtoMapping = Mapper.CreateMap<T, U>();


        var mex = Mapper.CreateMap<U, T>()

                        .ForMember(m => m.Id, m => m.Ignore());


        var refProperties = from p in typeof(T).GetProperties()

                            where p.PropertyType.BaseType == typeof(BaseEntity)

                            select p;


        foreach (var prop in refProperties)


            mex.ForMember(prop.Name, m => m.Ignore());



        Mapper.CreateMap<PagedResult<T>, PagedResult<U>>()

              .ForMember(m => m.Results, m => m.Ignore());



    public U MapToDto(T instance)


        if (instance == null)

            return null;


        var dto = new U();


        Mapper.Map(instance, dto);


        return dto;



    public IList<U> MapToDtoList(IList<T> list)


        if (list == null)

            return new List<U>();


        var dtoList = new List<U>();


        Mapper.Map(list, dtoList);


        return dtoList;



    public PagedResult<U> MapToDtoPagedResult(PagedResult<T> pagedResult)


        if (pagedResult == null)

            return null;


        var dtoResult = new PagedResult<U>();

        Mapper.Map(pagedResult, dtoResult);

        Mapper.Map(pagedResult.Results, dtoResult.Results);


        return dtoResult;



    public void MapFromDto(U dto, T instance)


        Mapper.Map(dto, instance);



It does all the dirty work and in most cases it provides all functionality I need for type-pair mapping.

In constructor I define mappings for domain class to model and model to domain class mapping. Also I define mapping for PagedResult – this is the class I use for paged results. If inheriting classes need to modify mappings then they can access protected properties.

Also notice how I play with domain base class: the code avoids situations where AutoMapper may overwrite ID-s and properties that extend domain base class. When you start using mapping then you very soon find out how bad mess AutoMapper can create if you don’t use it carefully.

Methods of mapper base:

  • MapToDto – takes domain object and returns mapped DTO.
  • MapToDtoList – takes list of domain objects and returns list of DTO-s.
  • MapToDtoPagedResult – takes paged result with domain objects and returns paged result with DTO-s.
  • MapFromDto – maps DTO properties to domain object.

If you need more mapping helpers you can upgrade my class with your own code.


To give you better idea about how to extend my base class here is the example.

public class FillLevelMapper : BaseMapper<FillLevel, FillLevelDto>


    public FillLevelMapper()



            l => l.Grade, m => m.MapFrom(l => l.Grade.GradeNo)




Mapper classes extend from BaseMapper and add their specifics to mappings that base mapper doesn’t provide.


Mapping is also one repeating patterns in many systems. After building some mappers from zero you start recognizing parts they have in common. I was able to separate common operations of my mappers to base class using generics and AutoMapper. Mapper classes are very thin and therefore also way easier to test. AutoMapper makes a lot of dirty work for me that is otherwise time consuming to code. Of course, by all it’s power you must use AutoMapper carefully so it doesn’t do too much work.

ASP.NET MVC: Creating user configurable charts

Although summer here is awful and nice at same time it’s time to blog. Couple of years ago I wrote about how to use MS Chart control in ASP.NET MVC projects. Now let’s extend my solution and let’s add support for simple chart modifications. I used this solution in one of my projects to let users visualize their data better.

Extending IReportControl interface

Although it is possible to create new interface that extends IReportControl interface I found it better for my solution to modify IReportControl. Here is my new IReportControl interface:

public interface IReportControl : IDisposable
int ChartStyle { set
; }
int ChartType { set
; }
bool Enable3D { set; }
     void DataBind();
object DataSource { set
; }
void SaveChartImage(Stream stream);

We have now three new options:

  • Enable3D - show chart as 3D
  • ChartStyle - set chart style
  • ChartType - set chart type

Now let’s fit these new options to our charting solution.

Code behind chart controls

Now we have to modify code behind chart controls so it implements our new interface. This code is not very fool proof by every aspect but it thin enough to visualize you what we are doing.

public partial class SalaryStatsByLevelsChart : UserControl, ISalaryStatsByLevelsChart


    public override void DataBind()






    public object DataSource




            Chart1.DataSource = value;




    public void SaveChartImage(Stream stream)





    public int ChartType




            foreach (var serie in Chart1.Series)


                serie.ChartType = (SeriesChartType)value;





    public bool Enable3D




            Chart1.ChartAreas[0].Area3DStyle.Enable3D = value;




    public int ChartStyle




            Chart1.Palette = (ChartColorPalette)value;




Here you can see clearly why I defined only setters for new properties – I don’t ask values of these properties from chart. I only set these values.

Updating ChartLoader class

In my previous post I created ChartLoader class that has only one method – SaveChartImage(). Now we are standing on cross-road:

  • we can modify this method and add new arguments to its signature,
  • we can modify ChartLoader class to just load control and after we have made modifications we need we will use overload of SaveChartImage() that accepts IReportControl.

I choose simpler way and modify the signature of SaveChartImage() method:

public static class ChartLoader


    public static void SaveChartImage(string controlLocation,
        IEnumerable data, Stream stream,

        int chartType, int chartStyle, bool enable3D)


        using (var page = new Page())

        using (var control = (IReportControl)page.LoadControl("~/Charts/" + controlLocation))


            control.ChartType = chartType;

            control.ChartStyle = chartStyle;

            control.Enable3D = enable3D;


            control.DataSource = data;






Now SaveChartImage() makes some dirty work for us and our application don’t care about how exactly charts are modified.


Here is the example result of my chart with display options:

ASP.NET MVC: Configurable chart

Now users can select options and decide how they want charts to be shown – 2D or 3D, what color scheme to use and what type of chart is best to visualize their data.

Posted: Jul 26 2012, 12:14 PM by DigiMortal | with 1 comment(s)
Filed under: ,
Using SocialCounter.NET with ASP.NET MVC

I found small library called SocialCounter.NET that is able to display some data from popular social sites. Although it is possible to use widgets offered by social networks there are also scenarios when you don’t want or can’t use these JavaScript based widgets. In this posting I will show you how to use SocialCounter.NET.

Start with downloading SocialCounter.NET. You can also use NuGet package manager to download SocialCounter.NET.

Using SocialCounter.NET is very easy as you can see from this example view:

@using SocialCounter.NET;

     ViewBag.Title =
"Home Page"

    Twitter followers: @Counter.GetTwitterFollowersCount("gpeipman")<br />
    Facebook friends: @Counter.GetFacebookFriendsCount("gpeipman")<br />
    Facebook likes: @Counter.GetFacebookLikes("")<br />
    Delicious saves count: @Counter.GetDeliciousSaveCount("")<br />

SocialCounter.NETAnd the result is shown on image on right.

You can use SocialCounter.NET by example on user profile pages and on your content pages where you want to show how many people have saved current page as bookmark.

SocialCounter.NET supports also LinkedIn, RSS-feeds and Google Plus accounts. In future – I hope – they will add support for more social networks to their library.

Posted: Jul 05 2012, 09:56 PM by DigiMortal | with 1 comment(s)
Filed under: ,
Cone of Uncertainty in classic and agile projects

David Starr from made interesting session in TechEd Europe 2012 - Implementing Scrum Using Team Foundation Server 2012. One of interesting things for me was how Cone of Uncertainty looks like in agile projects (or how agile methodologies distort the cone we know from waterfall projects). This posting illustrates two cones – one for waterfall and one for agile world.

Cone of Uncertainty

Cone of Uncertainty was introduced to software development community by Steve McConnell and it visualizes how accurate are our estimates over project timeline. Here is the Cone of Uncertainty when we deal with waterfall and Big Design Up-Front (BDUF).

Cone of Uncertainty
Cone of Uncertainty. Taken from MSDN Library page Estimating.
The closer we are to project end the more accurate are our estimates.
When project ends we know exactly how much every task took time.

As we can see then cone is wide when we usually have to give our estimates – it happens somewhere between Initial Project Concept and Requirements Complete. Don’t ask me why Initial Project Concept is the stage where some companies give their best estimates – they just do it every time and doesn’t learn a thing later.

This cone is inevitable for software development and agile methodologies that try to make software world better are also able to change the cone.

Cone of Uncertainty in agile projects

Agile methodologies usually try to avoid BDUF, waterfalls and other things that make all our mistakes highly expensive. Of course, we are not the only ones who make mistakes – don’t also forget our dear customers. Agile methodologies take development as creational work and focus on making it better.

One main trick is to focus on small and short iterations. What it means? We are estimating functionalities that are easier for us to understand and implement. Therefore our estimates are more accurate. As we move from few big iterations to many small iterations we also distort and slice Cone of Uncertainty. This is how cone looks when agile methodologies are used.

Cone of Uncertainty in agile projects
Cone of Uncertainty in agile projects.
We have more cones to live with but they are way smaller.

I don’t have any numbers to put here because I found any but still this “chart” should give you the point: more smaller iterations cause more but way smaller cones of uncertainty. We can handle these small uncertainties because steps we take to complete small tasks are more predictable and doesn’t grow very often above our heads.

One more note. Consider that both of charts given in this posting describe exactly the same phase of same project – just uncertainties are different.

More Posts