Support serialization with Expando object

Recently I have a chance to work with project that need to store dynamic data, work with dynamic data. The data will be stored in RavenDB. After some considerations, I decided to use this implementation from Rick  Strahl. Everything works fine, except saving to database. It is store as empty object in RavenDB.

Just add these lines of code will solve the problem


public override IEnumerable<string> GetDynamicMemberNames()
{
return Properties.Keys;
}

The end result is nice

ExpandoRavenDB

WPF: Mystery bug: Hunt, fix, but still not understand why

I got a bug report from client for a WPF application. Please look at the picture below:

mysterybug

The expected dropdown values are: I , unique II, III, IV, V

But it displayed “II” instead of “III”. I then check the value from data source. The data was correct. I then brought up my Visual Studio and ran the app. No, issue found.

After some discussion, I then tried with Windows 7, and Windows 8. And after some tries with changing the value for “III” item. The conclusions are:

  1. It works fine with Windows Server 2008 R2.
  2. It does not work on Windows 7 and Windows 8
  3. Only happen if “III” stands alone. If you add space (“I II”), it works

After hunting down the code, I ended up at the template to display the combo box item ( I need to use custom template for my own purpose)

<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}" Height="35" Padding="5"></TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>

Accidentally, I changed Padding from “5” to “3” ( I love number “3”). To my all surprise, it worked Smile. I then tried with number “4”. It did not.

It will work with value less than or equal 3.

But I still do not understand the reason Sad smile Just post it here if someone can explain to me or if someone has the same problem might find the answer.

Design and implement a template engine–part 2

In the Design and implement a template engine – part 1 I mentioned about a better solution: Reuse Razor Engine. In the post, I go in detail of how to implement it. But, first, we need to know some concepts:

Concepts

  1. Template Engine: Use to render a template into string
  2. Template Model Builder: Build the Model object which is used to fill in the data in template
  3. Template Model Expander: Expand the Model object with more properties
  4. And Template: the template

Implementation

The implementation assume that you already know about dynamic object and Razor Syntax (which is used in MVC – Views)

public interface ITemplateModelExpander
{
    /// <summary>
    /// Expand a dynamic object with more properties. The input object is sharing between expanders. Each expander will expand the properties that most make sense to them
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    dynamic Expand(dynamic obj);
    /// <summary>
    /// True if want to tell the <see cref="ITemplateModelBuilder"/> that, use the result of Expand method as the input for the next expander.
    /// The implementation should be very careful when setting true. Most of the time, it should be false
    /// </summary>
    bool UseResultForNextExpander { get; }
}

ITemplateModelExpander is the one that will be implemented in many classes. As its purpose, we want to expand the dynamic object to build up a real Model for the template.

Next we will see how we define a Template Model Builder.

/// <summary>
/// Builder is for building the object model using the inner expanders
/// </summary>
public interface ITemplateModelBuilder
{
    /// <summary>
    /// return the dynamic object that can be used in template
    /// </summary>
    /// <returns></returns>
    object Build();
    /// <summary>
    /// Append expander
    /// </summary>
    /// <param name="expander"></param>
    void AppendExpander(ITemplateModelExpander expander);
    void AppendExpanders(IEnumerable<ITemplateModelExpander> expanders);
    /// <summary>
    /// Clear all expanders. It is useful when you want to empty the object model and start adding new expander.
    /// Mostly you will use it if there is a single <see cref="ITemplateModelBuilder"/> in the system (Singleton lifestyle)
    /// </summary>
    void ClearExpanders();
}

It does 1 main thing: Build; which builds the Model object (of course, dynamic object) using expanders. That’s why you see 3 more methods related to Expander.

Then I make a simple implementation for the Model Builder:

public class StandardTemplateModelBuilder : ITemplateModelBuilder
{
    private readonly List<ITemplateModelExpander> _expanders = new List<ITemplateModelExpander>();

    public object Build()
    {
        var model = new ExpandoObject();
        foreach (var expander in _expanders)
        {
            var result = expander.Expand(model);
            if (expander.UseResultForNextExpander)
            {
                model = result;
            }
        }
        return model;
    }

    public void AppendExpander(ITemplateModelExpander expander)
    {
        _expanders.Add(expander);
    }

    public void AppendExpanders(IEnumerable<ITemplateModelExpander> expanders)
    {
        _expanders.AddRange(expanders);
    }

    public void ClearExpanders()
    {
        _expanders.Clear();
    }
}

Pretty simple right Smile

Let’s talk about Template, I have this simple interface:

/// <summary>
/// Define a template entry.
/// </summary>
public interface ITemplate
{
    /// <summary>
    /// The template, which tell <see cref="ITemplateEngine"/> how to render output
    /// </summary>
    string Template { get; set; }
    /// <summary>
    /// The builder which will build the model to populate data for the template
    /// </summary>
    ITemplateModelBuilder ModelBuilder { get; }
}

Define it as interface gives me power to change the template type. Even though, I just have Razor template for now:

public class RazorTemplate : ITemplate
{
    public RazorTemplate(ITemplateModelBuilder modelBuilder)
    {
        if(modelBuilder == null)
            throw new ArgumentNullException("modelBuilder");
        ModelBuilder = modelBuilder;
    }
    public string Template { get; set; }
    public ITemplateModelBuilder ModelBuilder { get; private set; }
}

You might wander why do I not inject template property directly in the constructor? Because, I want to resolve the ITemplate instance using an IoC container, such as Windsor and wire up with correct ITemplateModelBuilder which is StandardTemplateModelBuilder in this case. (I will show you how to use it later)

The last part, the Template Engine:

/// <summary>
/// Engine to render output base on template
/// </summary>
public interface ITemplateEngine
{
    string Render(ITemplate template);
}

Very simple. It just render an ITemplate instance.

The implementation is based on Razor Engine

/// <summary>
/// Simple implementation using Razor engine
/// </summary>
public class RazorBasedTemplateEngine : ITemplateEngine
{
    public string Render(ITemplate template)
    {
        return Razor.Parse(template.Template, template.ModelBuilder.Build());
    }
}

It asks the ModelBuilder from Template to build up the dynamic model object which is used to populate the template.

Usage

Have a look at this Unit Test:

[Test]
public void Test_simple_render_engine()
{
    // Arrange
    var engine = new RazorBasedTemplateEngine();
    var modelBuilder = new StandardTemplateModelBuilder();
    var template = new RazorTemplate(modelBuilder)
    {
        Template = @"Hello @Model.Name"
    };
    modelBuilder.AppendExpander(new SampleByNameExpander("Thai Anh Duc"));
    // Act
    var result = engine.Render(template);
    // Assert
    Console.WriteLine(result);
    Assert.AreEqual("Hello Thai Anh Duc", result);
}

I setup Engine, ModelBuilder, and Razor Template. These objects can be wire up automatically by IoC, see below

public class TestIoCWireUp
{
    private readonly ITemplateEngine _engine;
    private readonly ITemplate _template;

    public TestIoCWireUp(ITemplateEngine engine, ITemplate template)
    {
        if (engine == null)
            throw new ArgumentNullException("engine");
        if (template == null)
            throw new ArgumentNullException("template");
        _engine = engine;
        _template = template;
    }

    public string RenderNameTemplate(string template)
    {
        _template.Template = template;
        _template.ModelBuilder.AppendExpander(new SampleByNameExpander("Thai Anh Duc"));
        return _engine.Render(_template);
    }
}

And very simple implementation for SampleByNameExpander:

public class SampleByNameExpander : ITemplateModelExpander
{
    private readonly string _name;

    public SampleByNameExpander(string name)
    {
        _name = name;
    }
    public dynamic Expand(dynamic obj)
    {
        obj.Name = _name;
        return obj;
    }

    public bool UseResultForNextExpander { get {return false;} }
}

If you want to expand the Model with more properties that make sense to your application, you can add as many as possible. Just make sure you add the expander for the ModelBuilder of the Template you want. Or you can create a big giant Expander which will expose lot of properties at once. However, I will not encourage that. It is much more maintainable with simple small classes.

And, that’s it. Hope it help Smile

Design and implement a template engine – part 1

Recently, I got a task which is typical in many systems: Template with merge fields. The common usage is for email.

Given that an employee is created, the system will notify the manager by email with template:

Dear Manager,

New employee {Name} has been created on {DateTime.Now}.

From the above statement, we have template with 2 merged fields: Employee Name and Created Date. There are some solutions. But I name the old way of doing it here for reference:

Replace merge fields using string.Replace or Regex.

You can imagine it and how to do it. Or you event did it some times.

A better approach: Take advantages of Razor Engine.

The template will be in razor syntax

Dear Manager,

New employee @Model.EmployeeName has been created on @DateTime.Now.ToString(“s”).

In the next post, I will discuss about implementation.

Azure Continuous Delivery with Visual Studio Online

Last week, I had a project which uses Visual Studio Online and deploys the services to Azure cloud service. The deploy structure of the project is that, we have 3 versions: Test, Demo and Production. They all share the same codebase, just different in the configuration file.

Following this article http://www.windowsazure.com/en-us/documentation/articles/cloud-services-continuous-delivery-use-vso will easily setup the integration between Azure service and Visual Studio Online. However, as a newbie in this Azure, Deploy world I had trouble with making it work. Simply, the build was ok but the deployment was not. After some tries, I finally managed to make it work. Someone out there might have the same issue, or fighting with getting it work. I post my experience here, so hope It helps.

Have a look at this link (Image): http://screencast.com/t/01tqq0j7

In Deployment setting:

  1. Path to Deployment Setting: Path to the Publish profile you have when you created the Deployment Azure project
  2. Window Azure Deployment Environment: Auto filled when Azure cloud service and Visual Studio Online link together.

In Build section:

Make sure you point to the solution file. The solution file must contains ONE Azure Deploy project only. It seems not possible to deploy to 3 Azure Cloud Services in one single solution file. So I just made one for each.

Another notice: make sure the deployment project references ONLY to the Azure Role project.