Fluent interfaces introduction and sample.

Learning how to write a fluent interface can help when you want to write the next ORM or if you just wonder how to concatenate your methods in a LINQ style. I’m particularly interested in using this technique to write Html helpers. Anyway, let see a basic example.

A simple calculator class/interface , using a fluent interface:

Code Snippet
public interface IFluentCalcolator
{
    IFluentCalcolator Init(decimal number);
    IFluentCalcolator Add(decimal number);
    IFluentCalcolator Substract(decimal number);
    IFluentCalcolator Multiply(decimal number);
    IFluentCalcolator Divide(decimal number);
    decimal Result();
}

public class FluentCalculator : IFluentCalcolator
{
    private decimal _initialValue = 0;
    public IFluentCalcolator Init(decimal number)
    {
        _initialValue = number;
        return this;
    }

    public IFluentCalcolator Add(decimal number)
    {
        _initialValue += number;
        return this;
    }

    public IFluentCalcolator Substract(decimal number)
    {
        _initialValue -= number;
        return this;
    }

    public IFluentCalcolator Multiply(decimal number)
    {
        _initialValue *= number;
        return this;
    }

    public IFluentCalcolator Divide(decimal number)
    {
        _initialValue /= number;
        return this;
    }

    public decimal Result()
    {
        return _initialValue;
    }   
}

And here’s how to use it, the method concatenation looks coolWinking smile

Code Snippet
[Test]
public void FluentCalculator_Test()
{
    var fluentCalcolator = new FluentCalculator();
    var result = fluentCalcolator.Init(10).Add(10).Divide(4).Multiply(5).Result();
    Assert.True(result == 25);
}

Easy join tables with EF Code First.

Entity Framework Code First is getting even better, release after release. Here’s how to easily get a many to many relationship between two entities. Not to much to do really, once the relationship is specified within the two classes (an ICollection navigation property for each of the two ends in the relation), EF will take care of creating a join table.

Code Snippet
public class Character : BaseEntity
{
    public string Name { get; set; }
    public bool IsEvil { get; set; }
    public virtual ICollection<Videogame> Videogames { get; set; }
}

public class Videogame : BaseEntity
{
    public string Name { get; set; }
    public DateTime ReleasedDate { get; set; }
    public virtual ICollection<Character> Characters { get; set; }
    public Author Author { get; set; }
}

 

Code Snippet
[Test]
public void CreateJoinTable()
{
    var character = new Character() {Name = "Wario", IsEvil = true};
    var videogame = new Videogame() {Name = "Super Mario Bros 20", ReleasedDate = DateTime.Now , Characters = new Collection<Character>()};
    videogame.Characters.Add(character);
    var context = new NerdContext();
    context.Add(videogame);
    context.SaveAllChanges();
}

image

Default value if null object in an extension method.

Sometimes you need to get a value from a nested object and in order to do it we need to be sure that the object hierarchy do not have any null objects in it.

This lead to a long series of checks. Here an example, assuming we got these entities:

Code Snippet
  public class Country
  {
      public string Name { get; set; }
  }

  public class Author
  {
      public string Name { get; set; }
      public DateTime DateOfBirth { get; set; }
      public Country Country { get; set; }
  }

  public class Character : BaseEntity
  {
      public int Name { get; set; }
      public bool IsEvil { get; set; }
      public virtual ICollection<Videogame> Videogames { get; set; }
  }

  public class Videogame : BaseEntity
  {
      public string Name { get; set; }
      public DateTime ReleasedDate { get; set; }
      public virtual ICollection<Character> Characters { get; set; }
      public Author Author { get; set; }
  }

When trying to get the contry name of the author of a videogame, we should check both the Author and the Country object not to be null otherwise we’ll get the following (where Author is null) :

image

So in order to avoid this our check should be:

Code Snippet
if (videoGame.Author != null && videoGame.Author.Country != null)
{
    countryName = videoGame.Author.Country.Name;
}

But this can become really verbose if there’s a lot of nesting in place. Let’s then use an extension method that allow to get a default value for each object in the chain that is null, :

Code Snippet
if (videoGame.Author.GetDefault().Country != null)
{
    countryName = videoGame.Author.Country.Name;
}

Here’s the extension method:

Code Snippet
public static class DefaultIfNullExtension
{
    
    public static TSource GetDefault<TSource>(this TSource source) where TSource : class
    {
        TSource sourceInstance = null;
        sourceInstance = source ?? Activator.CreateInstance<TSource>();
        return sourceInstance;
    }

}

Developer homework test.

Below you can find a test I received via email long time ago. Also, in this attachment there’s what I think is a good solution, any tough or suggestion is appreciated !

Developer Homework

Please write code to fulfill the requirements of the following user stories. We are looking for answers that demonstrate good test driven development and object orientated programming skills.

Guidance
We are looking for simple solutions to the problem, so console apps are fine. Having said that
please feel free to show us how you would solve the problem. The nature of the exercise is
very open in order for us to get a feel for your style of development.
We expect the piece of work to take no more that an evening worth of work – 3 hours or so.
You do not need to create the content for the articles, it is enough to provide a title and indicate
that a given article has content of a particular type.
Please do give feedback about the exercise.

Stories

  • So that we have rich content to attract users to our website and increase advertising
    revenue. As a journalist, I would like to be able to create a library of articles with a mix
    of content, consisting of: text, video, audio and pictures.
  • So that I can extent the reach of our content to different audiences and therefore
    increase opportunities for advertising revenue. As a journalist, I would like to be able to
    publish articles to multiple platforms: FreeSat, PS3, Web & mobile.
  • So that the user gets a positive user experience, as an editor, I only wish to have articles
    with content compatible with a given platform, published on a platform.
  • So that I can see the distribution of content on platforms and better manage further
    distribution to maximise revenue. As an Editor, I would like to see what articles are
    published on which platforms, including those that have not yet been published.

image

Here’s the source code for the solution.

Ignore all non exisisting properties with Automapper

Code Snippet
public static class MappingCustomExtension
{
    public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
    {
        var sourceType = typeof(TSource);
        var destinationType = typeof(TDestination);
        var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType) && x.DestinationType.Equals(destinationType));
        foreach (var property in existingMaps.GetUnmappedPropertyNames())
        {
            expression.ForMember(property, opt => opt.Ignore());
        }
        return expression;
    }

}

LuceneWrap write.lock FIX

After getting a feedback on an article I’ve posted time ago on Codeproject I’ve updated the source code in order to fix an appended lock created after a search.  I’m posting here the project because the article is approved on Codeproject and to get it changed I’ll need to contact the staff, wait, post the updates etc etc…  In the article and its comments you can find what’s all about. Click here to download the updated Tests sources.

MVC Radiobutton group

In order to group a series of radiobutton and allow only one control of the group to be selectable we’ll have to set the same value for the “name” attribute on all controls of the group. In Vb.Net

Code Snippet
<div id="group1">
    @Html.RadioButton("group1", False, New With {.class = "radioClass"})
    @Html.RadioButton("group1", False, New With {.class = "radioClass"})
    @Html.RadioButton("group1", False, New With {.class = "radioClass"})
</div>
<div id="group2">
    @Html.RadioButton("group2", False, New With {.class = "radioClass"})    
    @Html.RadioButton("group2", False, New With {.class = "radioClass"})
    @Html.RadioButton("group2", False, New With {.class = "radioClass"})
</div>

From Asp.net Webforms to Asp.net MVC

I’ve been using MVC recently for a while now, both at work and on my own, I am really enjoying it, the implementation proposed by Microsoft is simple and effective and it sticks more to the nature of a web session(request/response) than the Webform model with all it’s page lifecycle, control events and so on.  The move to MVC should happen when you are not using anymore the core feature of Asp.net Webforms: its controls. If you find yourself creating an html list inside the aspx page using a foreach instead of using a repeater, if you prefer using jQuery instead of an Update Panel, then you should move to MVC.

This is not a comparison between the two tecnologies, there’s plenty of resources out there, here are the key points making me prefer MVC over Webforms.

  • Absence of  in-between page states (Page load, render etc),  with MVC you call an action and you get a response back, that’s it.
  • Cleaner pages without generated code (es ViewState).
  • More control over the content and what is rendered using a View engine and html instead of webcontrols.
  • Possibility to unit test each request a client will make.
  • A lot of community resources.

Webforms has been the perfect fit in the pre Ajax era, when tools like jQuery didn’t exist, the common focus was on trying to do everything “server side”. MVC reverse this statement: the look and behaviour of the page is handled by the View while the server is only responsible of receiving and responding to the client requests. Assuming that with both MVC and Webforms you can achieve exactly the same goals, the choice is really up to how many feauters of each model you will use.