Archive for category fun with C#

Dynamic Data and Behavior in a Strongly-Typed Codebase

With my previous post I’ve wrapped up an entire series where I talk about creating a dynamic DTO decorator, which started off as a way to leverage C#’s Dynamic Features to get rid of the need to implement INotifyPropertyChanged on every ViewModel and then morphed into decorating the object with some extra behavior (on the previous post, we’ve added support for some visual behavior).

As I mentioned many time in the series, the implementation I showed is a simplified version of something I had in a large Real World application. In this post I want to just mention some other things that were done in that application, to give you an idea on where else we can go with that approach.

Dynamic Entities

There was a requirement where the application shipped with a database structure, but then it could be extended in production, based on each client’s needs. The clients couldn’t create completely arbitrary new data structures; instead, they’d create new tables which added columns to existing ones (a sort of inheritance).

The codebase had entities defined with the properties the application shipped with, but these entities also needed to be extended at the clients to support the columns they added to the tables in the database (they could only do this to very specific tables through the application).

In order to support that behavior, we created a DynamicEntity class, which followed the same approach of implementation as the DynamicDtoDecorator I’ve described on my series. The data access layer was responsible for setting things up so that NHibernate could work with the “dynamic” columns added to the tables. This layer would also dynamically add default values to certain properties on the entity, as specified by the end-users. The users could, for example, set the default value for a new property (new column in a table) by creating a expression such as x.PropertyA + x.PropertyB (where PropertyA may be one that ships with the application, while PropertyB may be a user-defined one).

Dynamic Business Logic

As the DynamicEntity travelled from the data access layer through the business layer, the framework added some special dynamic behavior as specified by users through the application. For example, the users could set range validation for properties on the entity (both for properties that shipped with the app, as well as those created by the client).

Dynamic Behavor for Presentation Layer

As the DynamicEntity reached the Presentation Layer, the framework added dynamic behavior related to presenting the entity to the user, such as handling what the background cell color should be for each property on the entity based on its value, whether a cell should be read-only, etc. Make sure to check out my previous post for an example of this.

From the database to the user interface

The framework provided an interface (IHandleRow, or something like that), which the different layers of the application (data access layer, business layer, presentation layer) could implement to inject the specific dynamic data and/or behavior the application needed on each layer. Since the end-users could override behavior shipped with the application, as well as add behavior to the columns they added, this approach using the C# Dynamic Features has helped tremendously in making an otherwise strongly-typed codebase support the business requirements.

Leave a comment

Fun with C#: Adding visual behavior to dynamic view model

As promised on my previous post, let’s see how we can add a nice little feature that leverages the capabilities of the DynamicDtoDecorator we’ve been creating across several blog posts. The gist of this feature is to add dynamic properties to the view model to help support a “dynamic background color” behavior for the data properties that need it.

As an example, let’s take a screen that has some data grid similar to this:

Now, let’s pretent there’s a requirement where the cell background must be green when a product name is “banana”, and yellow for anything else:

Of course, the background has to change accordingly when the user changes the product name on the screen.

Adding to the example, let’s say that the category cell background color must change based on the category:

And finally, the total cell background must also change… however, it also depends on the category, and it uses different colors:

If you’ve been following my series on “How to get rid of INPC using Dynamic” (starting here), you know my example app here uses a DynamicDtoDecorator that takes a POCO ViewModel, enhances it with INPC behavior, and is then bound to the view. Using that decorator we can tap into WPF’s databinding features to make it easier to expose this visual behavior we want for the data.

The main idea here is the following: the ViewModel already contains the data that we want displayed on the UI. We can then use the decorator to enhance the ViewModel to help the view display that data.

I’ll walk you through how I’ve implemented this type of feature in this sample app. Bear in mind this is a much trim down version from a real world, much larger, app that I’ve worked on a while ago. I’ll point out the main differences between the sample and the real app when appropriate.

In order to support visual aspets for the InvoiceItemViewModel class, I’ve created a class named InvoiceItemVisuals, starting it off like this:

public class InvoiceItemVisuals
{
}

I’ve then added a method specifically to define the cell background definitions for an invoice item:

public IEnumerable<cellbackgrounddefinition> GetCellBackgrounds()
{
    yield return new CellBackgroundDefinition("ProductName",
        new [] { "ProductName" }, 
        vm => vm.ProductName == "Banana",
        new Dictionary
        {
            {true, Brushes.Green},
            {false, Brushes.Yellow}
        });
    yield return new CellBackgroundDefinition("Category",
        new[] { "Category" },
        vm => vm.Category,
        new Dictionary
        {
            {"1", Brushes.LightBlue},
            {"2", Brushes.LightGray},
            {"3", Brushes.LightSalmon}
        });
    yield return new CellBackgroundDefinition("Total",
        new[] { "Category" },
        vm => vm.Category,
        new Dictionary
        {
            {"1", Brushes.Red},
            {"2", Brushes.Pink},
            {"3", Brushes.Purple}
        });
}

</cellbackgrounddefinition

The CellBackgroundDefinition is a generic class that expects to know the type of ViewModel it works with, and takes in four important pieces for it to work:

  1. The name of the data property bound to the cell;
  2. A list of dependent properties. For instance, the background color for the total cell depends on the value of the category;
  3. A Func that takes in an instance of the ViewModel, and returns whatever gives the value that’ll be used to determine the cell background color. In the example above, we’re interested on the value of Category; 
  4. A dictionary indicating the colors to be used for each expected value (in the example above, “1” is red, “2” is pink, “3” is purple.

Real World: the application in the real world didn’t have those definitions set in code; instead, those were all stored in the database, with support to have both default settings that shipped with the app, as well as user overrides.

Once we have those “background definitions” specified, we have to inject them into our decorated DTO (in our case, the view model). For that, I’ve added an InjectInto method to the InvoiceItemVisuals class:

public void InjectInto(DynamicDtoDecorator decoratedDto)
{
    GetCellBackgrounds().ForEach(definition =>
    {
        var backgroundProperty = {0}#x22;{definition.PropertyName}_Background";
        decoratedDto.RegisterPropertyDependencies(backgroundProperty, definition.DependsOn);
        decoratedDto.Register(backgroundProperty, () => definition.Func(decoratedDto.GetDto()), newValue => {});
    });
}

The method takes in the DynamicDtoDecorator, goes through all the cell background definitions, and register those as dynamic properties and their dependencies. As mentioned before, the new property is named after the data property it refers to, and it has a “Background” suffix, so for the Category background, we’ll have a “Category_Background” property.

Notice that the Register method on the DynamicDtoDecorator takes in the name of the new property, as well as Funcs for the property’s getter and setter. Our getter in this case simply calls the Func that is part of the background definition (which, for the Category background looks like vm => vm.Category), whereas the setter doesn’t really need to do anything.

The final piece for this feature to work is to set things up in the UI so it knows how to use our dynamic properties. Please, remember this is a WPF application, so we can create styles and triggers to handle the visual stuff. Instead of defining those declaratively in XAML, we do it imperatively in C#. To keep things simple in this sample app, I’ve added a ConfigureDataGrid to my InvoiceView Window class, which in turn calls a ConfigureCellBackgrounds method, and this is the guy who does the heavy lifting here:

private void ConfigureDataGrid()
{
    var modelVisuals = new InvoiceItemVisuals();
    ConfigureCellBackgrounds(modelVisuals);
}

private void ConfigureCellBackgrounds(InvoiceItemVisuals modelVisuals)
{
    var cellsBackgrounds = modelVisuals.GetCellBackgrounds();

    cellsBackgrounds.ForEach(cellDefinition =>
    {
        var column = (DataGridTextColumn) ItemsGrid.Columns
            .Single(c => c.Header.ToString() == cellDefinition.PropertyName);
        var style = new Style(typeof(TextBlock));

        cellDefinition.TriggerDefinitions.ForEach(trigger =>
        {
            var binding = {0}#x22;{cellDefinition.PropertyName}_Background";
            var propertyValue = trigger.Key;
            var propertyBackground = trigger.Value;
            var dataTrigger = new DataTrigger
            {
                Binding = new Binding(binding),
                Value = propertyValue
            };
            dataTrigger.Setters.Add(new Setter
            {
                Property = TextBlock.BackgroundProperty,
                Value = propertyBackground
            });
            style.Triggers.Add(dataTrigger);
        });

        column.ElementStyle = style;
    });
}

Breaking down the implementation of ConfigureCellBackgrounds, here’s what we do:

  1. Get the cell background definitions and loop through them;
  2. Get a reference to the GridColumn that hosts the data cell we’re interested in;
  3. Go through the TriggerDefinitions;
  4. Set up the Binding expression so it points to the appropriate “Cell_background” property;
  5. Put the binding expression in a DataTrigger for the TextBlock.BackgroundProperty;
  6. Put the data trigger in a new style created for TextBlock (where the values are displayed on the UI);
  7. Set the style on the grid column.

Done.

If you’d like to check out this sample app in action, here’s a link to the repo in GitHub:

Dynamic Decorator

Once again, bear in mind that this sample app shows a very simplified version of a full-blown Real World app that used this approach extensively. In the full app, a lot of the implementation went into a custom framework, and expressions and definitions for visual things and behaviors were specified both in C# code (for the options shipped with the application) and stored in the database (for the options overridden by specific clients and users).

I’ve used this approach successfully in at least two other projects, and will probably keep it in mind to use again if appropriate. 🙂

Leave a comment

Fun with C#: Enhancing ViewModels with a Dynamic Decorator

I’ve been posting a series on how to use C# Dynamic Features in order to get rid of implementing INotifiyPropertyChanged (INPC) on my ViewModels. If you’ve been following those posts, you’ll notice that the class I created to enable this is called DynamicDtoDecorator.

That class initially started as a proxy, simply bridging access to the properties on the internal object. After I added the INPC support to it, it really became a decorator. But I really started leveraging its abilities as a decorator when I started injecting more properties into the object in order to support more visual behavior.

As I mentioned back in this post, I wanted to leverage WPF’s data-binding capabilities. Using those capabilities to simply show data on the screen is really just the tip of the iceberg; the framework also allows binding to be used to do things like controlling visibility of UI elements, change visual aspects for elements (for instance, changing the background color of a grid cell), etc.

In this post, we saw that we can use the decorator like so:

var viewModel = new InvoiceItemViewModel { ProductName = “Some value" };
dynamic decorator = new DynamicDtoDecorator(viewModel);

We can then bind UI elements to the ProductName property, which is exposed through the decorator. Now, maybe we have some requirement that indicates the background where we show product name should change based on some data (which could potentially be changed by the user). It’d be handy to have a property on object like so:

decorator.ProductName_Background

Usually, property names in C# classes don’t have an “_”, but I do that as a simple convention so it makes it easy to parse it out and know the “data” property and the visual aspect we’re talking about there. Also, bear in mind that in the real world app where I’ve used this approach nobody would be accessing those properties directly in code: each property gets added dynamically to the decorator, and the all the data-binding is also hooked up dynamically.

In the next post we’ll see how we make the main part of that actually happen.

Leave a comment

Fun with C#: How to get rid of INPC using Dynamic – Part 5

Taking it from where we left off at the previous post on this series, let’s improve our DynamicDtoDecorator so it handles raising PropertyChanged events for properties that depend on other properties.

First, let’s revisit our InvoiceItemViewModel class:

public class InvoiceItemViewModel
{
    public string ProductName { get; set; }
    public string Category { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }
    public decimal Total => Price * Quantity;
}

As far as the UI is concerned, whenever either Price or Quantity changes on that object, the display of Total should refresh accordingly. In other words, Total depends on both Price and Quantity. I wanted to represent this dependency decorating the property with an attribute in the following manner:

[DependsOnAttribute("Price, Quantity")]public decimal Total => Price * Quantity;

Let’s look at the changes needed to implement that behavior. First, the implementation of DependsOnAttribute:

public class DependsOnAttribute : Attribute
{
	public string PropertyNames { get; set; }

	public DependsOnAttribute(string propertyNames)
	{
		PropertyNames = propertyNames;
	}
}

Definitely nothing special there. Next, changes to the DynamicDtoDecorator. Starting with a property to keep a dictionary of property dependencies (the key is the name of the property that has dependencies and the value is a list of properties that it depends on):
readonly Dictionary<string, IEnumerable<string>> _propertyDependencies = new Dictionary<string, IEnumerable<string>>();
We then change the RegisterProperties method so it verifies whether the property its registering has dependencies, and if so, it calls out the RegisterPropertyDependencies method:

protected virtual void RegisterProperties(object dto)
{
    dto.GetType()
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .ToList()
        .ForEach(prop =>
        {
            object[] notIndexedProperty = null;
            Func valueGetter = () => prop.GetValue(dto, notIndexedProperty);
            Action valueSetter = newValue => prop.SetValue(dto, newValue, notIndexedProperty);
            Register(prop.Name, valueGetter, valueSetter);

            var dependsOn = prop.GetCustomAttributes(true).OfType().SingleOrDefault();
            if (dependsOn != null)
            {
                RegisterPropertyDependencies(prop.Name, Array.ConvertAll(dependsOn.PropertyNames.Split(','), d => d.Trim()));
            }
        });
}

Here’s the implementation of RegisterPropertyDependencies:

public void RegisterPropertyDependencies(string property, string[] dependencies)
{
	_propertyDependencies.Add(property, dependencies);
}

We then have to change the SetProperty method to make sure we raise PropertyChanged for properties that depend on the property being changed:

public virtual void SetProperty(string propertyName, dynamic value)
{
	if (!_members.ContainsKey(propertyName))
		throw new InvalidOperationException({0}#x22;Unregistered member: {propertyName}");

	if (_members[propertyName].Get() == value) return;

	_members[propertyName].Set(value);
	RaisePropertyChanged(propertyName);
	RaisePropertyChangedForDependentsOn(propertyName);
}

Here’s the implementation for the RaisePropertyChangedForDependentsOn method:

void RaisePropertyChangedForDependentsOn(string propertyThatWasChanged)
{
    _propertyDependencies.ForEach(dependentProperty =>
    {
        var dependableProperties = dependentProperty.Value;
        if (!dependableProperties.Contains(propertyThatWasChanged)) return;

        var dependentPropertyName = dependentProperty.Key;
        RaisePropertyChanged(dependentPropertyName);
    });
}

The code simply looks through the registered properties that have dependencies and raise the event as appropriate.

This pretty much wraps up all the main pieces for getting rid of direct implementation of INotifiyPropertyChanged in ViewModels by using the C# Dynamic features. I’ll be keeping the latest version of the code in this repository, so feel free to check it out. I’ll be writing new posts for other improvements I’ve added to the decorator and you might find useful. Stay tuned!

In case you missed any part of this series, here are the links to Part 1, Part 2, Part 3 and Part 4.

Leave a comment

Fun with C#: How to get rid of INPC using Dynamic – Part 4

With what we wrote up to the previous post, we should be able to write the following code:

var viewModel = new InvoiceItemViewModel { ProductName = “Some value" };

dynamic decorator = new DynamicDtoDecorator(viewModel);

The next step is to enable access to the properties through the decorator, like so:

decorator.ProductName = “Some new value”;
Console.WriteLine(decorator.ProductName);

Since the decorator variable above has been declared as dynamic, the compiler won’t complain about the DynamicDtoDecorator not having such a thing as a ProductName property. However, during runtime, the code will blow up when it tries to access that property. Here’s what we need to do to the DynamicDtoDecorator class so it knows how to set a value to a dynamic property:

public override bool TrySetMember(SetMemberBinder binder, object value)
{
    SetProperty(binder.Name, value);
    return true;
}

public virtual void SetProperty(string propertyName, dynamic value)
{
    if (!_members.ContainsKey(propertyName))
        throw new InvalidOperationException({0}#x22;Unregistered member: {propertyName}");
    if (_members[propertyName].Get() == value) return;
    
    _members[propertyName].Set(value);
    RaisePropertyChanged(propertyName);
}

Our DynamicDtoDecorator class inherits from DynamicObject, which provides a TrySetMember method: this method gets called during runtime whenever we try to set a member on the object. Its SetMemberBinder parameter has a Name property, which gives us the name of the member we’re trying to set (in earlier example, that’d be the “ProductName” property). The method also takes in the value we’re trying to set the member to. Finally, the method is supposed to return true or false in order to indicate whether it could successfully set the value or not.

I’ve created a SetProperty method, which is called by the TrySetMember method, just to keep things more organized. This method performs a some simple validation (making sure the given property name is registered within the decorator), sets the value on the property using our PropertyAccessor, and calls RaisePropertyChanged.

The code that allows us to get the value of a property is very similar:

public override bool TryGetMember(GetMemberBinder binder, out object result)
{
    if (_members.ContainsKey(binder.Name))
    {
        var propertyValue = _members[binder.Name];
        result = propertyValue.Get();
        return true;
    }
    result = null;
    return false;
}

So, whenever we try to get the value of a dynamic property, a TryGetMember method is called. It takes in a GetMemberBinder, which gives us the name of the member we’re trying to access, and it also takes in an out parameter to which we set what value we want returned out of that operation. The method itself needs to return a boolean indicating whether or not the method succeeded.

That’s it! The most basic implementation of our decorator is ready: we can instantiate it passing in a ViewModel or other type of DTO, set it to the DataContext in WPF visual elements, and use DataBinding. The data displays on the UI, and should values in properties change, the UI should be updated to reflect the change.

So far, what we’re calling a decorator is really a proxy, since it doesn’t really add much functionality to the underlying object. However, once I got to this point, I started seeing other things I could use this approach for, and the class really became a decorator. But more on that on some other upcoming posts. We’re not done with this series yet!

Leave a comment

Fun with C#: How to get rid of INPC using Dynamic – Part 3

On this part of this series, we start looking at the DynamicDtoDecorator class. We begin by seeing how it takes in the object that it decorates and how it figures out what the public instance properties in the decorated object are, and how to access them. We’ll be seeing how we use the PropertyAccessor class created in the previous installment of this series.

Our DynamicDtoDecorator! We start like this:

public class DynamicDtoDecorator : DynamicObject, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = (sender, args) => { };

	void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

The class inherits from DynamicObject so we can get some dynamic support for free. It also implements INotifyPropertyChanged. “But aren’t we trying to get rid of INotifyPropertyChanged?”. Yes, we’re trying to get rid of it in our ViewModels, but we still need it somewhere for WPF binding to work.

Next, we have a private field to store the DTO (Data Transfer Object) that the class decorates. The DTO is passed into the class constructor

readonly object _dto;

public DynamicDtoDecorator(object dto)
{
    _dto = dto;
    RegisterProperties();
}

Notice that the constructor calls out to a RegisterProperties method. Let’s see what that method looks like:

protected void RegisterProperties()
{
    _dto.GetType()
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .ToList()
        .ForEach(prop =>
        {
            object[] notIndexedProperty = null;
            Func valueGetter = () => prop.GetValue(dto, notIndexedProperty);
            Action valueSetter = newValue => prop.SetValue(dto, newValue, notIndexedProperty);
            Register(prop.Name, valueGetter, valueSetter);
        });
}

The method looks for any public instance property on the DTO type, creates getter and setter delegates, and register them with in the decorator. If you’ve been following my series on this topic, you’ll remember my explanation on a PropertyAccessor class I created in the previous installment, so you can already think how those getter/setter delegates are going to be used, right? Well, alright, I forget things all the time, too, so let’s see what that Register method looks like:

public void Register(string propertyName, Func valueGetter, Action valueSetter)
{
    var fullPropertyName = propertyName;

    if (_members.ContainsKey(fullPropertyName))
       return;

    dynamic initialValue = valueGetter.Invoke();
    var propertyValue = new PropertyAccessor(propertyName, valueGetter, valueSetter, initialValue);
    _members.Add(fullPropertyName, propertyValue);
}

Nothing special going on there. The _members field is defined in the class like this:

readonly Dictionary<string, PropertyAccessor> _members = new Dictionary<string, PropertyAccessor>();

Just a pretty Dictionary, that’s all.

Right now, our decorator knows what it needs to access on the decorated object, and how to access it. In the next part we explorer how this is going to be exposed to the outside world. Stay tuned!

Leave a comment

Fun with C#: How to get rid of INPC using Dynamic – Part 2

el;In Part 1, I mentioned I wanted to decorate a ViewModel with “notify property changed” behavior, so I could keep my ViewModel as clean as possible. In this part I’ll go over how the properties on the decorated object are going to be accessed.

Say we have the following code:

dynamic viewModel = new DtoDecorator(new InvoiceItemViewModel());
viewModel.ProductName = “My great product”;
Console.WriteLine(viewModel.ProductName);

A “non-dynamic” implementation of the decorator could look somewhat like this (disregard the implementation of INotifyPropertyChanged for now):

public class DtoDecorator
{
    InvoiceItemViewModel _decoratedViewModel;

    public DtoDecorator(InvoiceItemViewModel viewModel)
    {
	_decoratedViewModel = viewModel;
    }

    public string ProductName 
    {
        get 
        {
            return _decoratedViewModel.ProductName;
        }
        set
		{
			_decoratedViewModel.ProductName = value;
		}
    }
}

The important aspect in the code above is that the decorator has to be able to access properties on the decorated object. In order to come up with a generic way to do that, I’ve created a PropertyAccessor class, designed to get/set value on a property.

The PropertyAccessor class uses a Func delegate to do the “get” and an Action delegate to do the “set”, like so:

var viewModel = new InvoiceItemViewModel { ProductName = “Some value" };

var getter = new Func(() => viewModel.ProductName);
var setter = new Action(value => viewModel.ProductName = value.ToString());
_propertyAccessor = new PropertyAccessor("ProductName", getter, setter, initialValue);

With that in place, we can get or set that property like so:

_propertyAccessor.Set(“New value”);
var currentValue = _propertyAccessor.Get();

This is what the PropertyAccessor class looks like:

public class PropertyAccessor
{
    readonly Func _getter;
    readonly Action _setter;

    public PropertyAccessor(string propertyName, 
        Func getter, 
        Action setter,
        dynamic initialValue)
    {
        PropertyName = propertyName;
        _getter = getter;
        _setter = setter;
        InitialValue = initialValue;
        CurrentValue = initialValue;
    }

    public string PropertyName { get; }
    public dynamic InitialValue { get; }
    public dynamic CurrentValue { get; private set; }

    public bool Changed => InitialValue != CurrentValue;

    public dynamic Get()
    {
        return _getter.Invoke();
    }

    public void Set(dynamic value)
    {
        _setter.Invoke(value);
        CurrentValue = value;
    }
}

Notice we also keep track of initial and current values so we can do some basic change tracking, which comes in handy.

Now that we have a generic way to get/set value on properties of an object, the next step will be to look at that decorator class. Coming up next!

Leave a comment

Fun with C#: How to get rid of INPC using Dynamic – Part 1

Continuing on with our series on using the dynamic features of C#, let me share how I’ve used it to address an issue that bugged me several years ago.

When creating ViewModels for WPF applications, I got fed up with having to implement INotifyPropertyChanged and pollute the classes like this:

public class InvoiceItemViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

private string _productName;

public string ProductName
{
get { return _productName; }
set
{
if (_productName != value)
{
_productName = value;
OnPropertyChanged("ProductName");
}
}
}
}

I didn’t want to see 12 lines in the code for each property exposed. Instead, I wanted to have something like this:

    public class InvoiceItemViewModel
{
public string ProductName { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
public decimal Total => Price * Quantity;
}

That’s as simple as the class can get. That’s how I wanted my ViewModels to look like. Notice it doesn’t even inherit from any baseclass, and it doesn’t have any attributes decorating the class (the way I also did at some point when using IL weaving tools such as PostSharp).

WPF databinding is late-bound, so as long as the property exists on the object during runtime, everything works just fine. When it comes to changing data in the UI and having WPF broadcast the message that the some properties have changed, well, the ViewModel needs to raise the PropertyChanged event. So, I decided to go ahead and create a DynamicDecorator class, which would decorate my ViewModels with the “notify property changed” behavior.

Before assigning my ViewModel to the UI’s DataContext property, I’d use the decorator, somewhat like this:

DataContext = new DynamicDecorator(new InvoiceItemViewModel());

In reality, I had an interceptor in my repository that’d do the decoration part automatically for me, but that’s beyond the point here.

In other words, say I had the following code somewhere in my WPF app:

var item = GetItem();
item.ProductName = “Banana”;

The implementation of GetItem could look like this:

InvoiceItemViewModel GetItem()
{
    return new InvoiceItemViewModel();   
}

But then again, since WPF’s databinding is late-bound, GetItem, in my case, looked something like this:

dynamic GetItem()
{
    return new DynamicDtoDecorator(new InvoiceItemViewModel());
}

The DynamicDtoDecorator simply intercepts access to the properties on the ViewModel it decorates, and it raises PropertyChanged when appropriate. I’ll show and explain the implementation of that class on my next post.

Wondering why the class is named Decorator, instead of Proxy? That’s also coming up in another post. Stay tuned!

Leave a comment

Fun with C#: After dynamic features arrived

Today I’ll continue with our series on dynamic stuff, taking it from where we left off in our previous post. So, building on top of the same simple examples, let’s see what changed for me once the dynamic features arrived to C#.

Bending strong typing

Remember how C# is strongly-typed?

var myVariable = 1234;
myVariable = “Woohoo!!”;   // Nope...

We can bend that rule if we declare types as dynamic:

dynamic myVariable = 1234;
myVariable = “Oh, boy…”;

Yes, I hope you can see how writing code like that can cause all sorts of trouble. But, it does come in handy when we have good use for it. Anyway, when we declare something as dynamic, we’re telling the C# compiler “look, the actual type of this will have to be determined during runtime”. Of course, in the sample above, we have an integer and string, so it wouldn’t make sense at all to use dynamic there. However, in real world apps, the actual value types would only be known during runtime.

Now, take this example:

var names = new[] { "Claudio", “Paul" };
var result = names.Select(n => new { Length = n.Length }).ToList();
Console.WriteLine(result.GetType().Name); // List’1 

Notice that the type of result is List’1, because we’re projecting the items into new anonymous types, and using var to let the compiler infer the type.

So what happens if we changed the code to this:

dynamic result = names.Select(n => new { Length = n.Length }).ToList();
Console.WriteLine(result.GetType().Name);  // List’1

By changing the type of the variable to dynamic we told C# the type would only be known during runtime. Regardless, in that case, the type still ends up being List’1 at runtime.

What if we follow that code with this:

result = “Woohoo";
Console.WriteLine(result.GetType().Name);  // string

The type of result would be changed to string, which proves the data type is indeed dynamic.

The ever expanding object

As part of the dynamic features, we also got an ExpandoObject class. If we instantiate that class and type the variable to either ExpandoObject or var, we get access to the members of that class that were statically typed. But the real fun comes in when we type the variable to dynamic. Check this out:

dynamic user = new ExpandoObject();            

user.FirstName = "Claudio”;            
user.LastName = "Lassala”;            

user.FullName = new Func(() => $"{user.FirstName} {user.LastName}");            

Console.WriteLine(user.FullName()); 

In the example above, the FirstName and LastName are properties we added dynamically to that user object. FullName is a method that returns a string.

We could also have defined the FullName method before defining the other properties:

dynamic user = new ExpandoObject();         

user.FullName = new Func(() => {0}#x22;{user.FirstName} {user.LastName}");

user.FirstName = "Claudio”;            
user.LastName = "Lassala”;             

Console.WriteLine(user.FullName()); 

That would still work just fine, given that during runtime, when FullName() was called for the first time, the properties it depends on would already have been added to the object. What if the properties weren’t there already? It’d throw an exception, which we can handle gracefully.

Let’s revisit a sample from previous posts and make it use dynamic:

var instanceType = Type.GetType("Playground.User");            
dynamic instance = Activator.CreateInstance(instanceType);            
object hello = instance.SayHello();            
Console.WriteLine(hello.ToString());

The main change there is that we assign the return of CreateInstance to a dynamic variable. From there on, we can call methods on it that the compiler doesn’t know about during compile time. NOTE: this feature was great when working with Excel automation!!!

Now that we know all of that, going back to the idea that I wanted to instantiate classes and call methods for which I have strings that represent their names (these strings are likely coming from a database or configuration file, for instance). So I’d like to be able to write something like this:

dynamic instance = MakeObject("Playground.User");            
dynamic result = instance.Call("SayHello");            
Console.WriteLine(result);

That’s an easy thing to pull off now that we know about ExpandoObject and dynamic types. Here’s the implementation of MakeObject:

private static dynamic MakeObject(string className)
{    
    var instanceType = Type.GetType(className);    
    dynamic instance = Activator.CreateInstance(instanceType);    

    dynamic expando = new ExpandoObject();    

    expando.Call = new Func((methodName) =>    
    {        
        IEnumerable methods = instance.GetType().GetMethods();        
        var method = methods.SingleOrDefault(x => x.Name == methodName);        
        return method.Invoke(instance, null);    
    });                
    return expando;
}

So we use Reflection to instantiate the given type, add a Call method to an ExpandoObject, which in turn calls the method we want on the real object, also using Reflection, and things just work!

Using Reflection in this case is just one option. If this approach presents a performance issue, the Reflection part can be replaced with other alternatives (IL emit, dynamic compilation of code, building Expression Trees), but the client code of this functionality wouldn’t have to change: it’d still be using strings to know the name of the class to instantiate and the name of the method to call on the object.

This series will continue, as there’s quite a number of some other useful things we can do with this knowledge acquired so far!

2 Comments

Fun with C#: Before there were dynamic features

In my previous post, I mentioned about Visual FoxPro being a weakly-typed, dynamic, object-oriented language, which also featured it’s own SQL (Structured Query Language), and a fast local database. When I got to C#, I found a language that was strongly-typed, object-oriented, with no easy way to perform queries, and very hard to create dynamic behavior. But let me brake that down, pretty much the way I did with FoxPro in the previous post:

Object-Oriented

Instantiate an object and call a method on it. Similar to the way I did in FoxPro, but with a key difference: the class name isn’t a string passed into a function!

User user = new User();
user.SayHello();

SQL (Structured Query Language)?

In the first two versions of C# there was just no easy way to query things. But then we were presented with LINQ (Language Integrated Query) in version 3!!

myCustomers = from c in customers 
                           where c.Id == 1 
                           select c;

customer = myCustomers.SingleOrDefault();

customer.Address 
customer.PhoneNumber 

That was very similar to the way I could do a SELECT followed by a SCATTER in FoxPro. I loved it!

I didn’t like the way the code read, though, with the “select” coming at the end (after so many years of starting my queries with SELECT). Once I got over that, I started to appreciate the fact that I could write my queries like this:

customer = customers.where(c => c.Id == 1).SingleOrDefault();

Or even better, like this:

Customer customer = customers.SingleOrDefault(c => c.Id == 1);

“What does that have to do with the topic of this series?”, you might ask. Stay with me…

Strongly-typed

Consider the following code:

var myVariable = 1234;
myVariable = “Woohoo!!”;   // Nope...

Well, since C# is strongly-typed, knowing the type of data we get back from queries is very important. Take this example:

var customers = customers 
                 .SingleOrDefault(c => c.Id == 1)
                 .Select(c => new { Address = c.Address, PhoneNumber = c.PhoneNumber  });

When C# 3 introduced type inference, many developers were confused with the keyword var, thinking it meant “variant”; in other words, a variable declared as var should be assigned different types of data at will. That was not the case; var was just a way to tell the compiler “hey, the type of this variable will be whatever type I’m assigning to it as I declare it.”

With that said, in prior examples we were having the query return a Customer object. In the example above, on the other hand, we return some sort of list of anonynous objects, by using the new keyword without the name of a class, but giving it the properties and initial values we want on them. So we just told the compiler “I need a new object that has these properties with these values”. The compiler creates a class for us containing those properties; it is not a class created dynamically during runtime.

Now, let’s take that example a step further:

var customers = customers 
                  .SingleOrDefault(c => c.Id == 1)
                  .Select(c => new { c.Address, c.PhoneNumber  });

customers = “can’t do this!”;

Again, we declare a customers variable, and let the compiler infer its type. Next, we try to assign some string content to that same variable. The compiler yells at us, proving that var does not mean variant.

Dynamic (before C# Dynamic)

Let’s now have a look at how we implement dynamic things before the so-called “C# Dynamics” were introduced. Let’s revisit this simple sample:

User user = new User();
string hello = user.SayHello();
Console.WriteLine(hello);

What if we didn’t know during compile time what type of User to instantiate? And what if we only knew during runtime what method to execute? The way to that back then was only by using .NET Reflection, like so:

var instanceType = Type.GetType("Playground.User");            
object instance = Activator.CreateInstance(instanceType);            

MethodInfo theMethod = instanceType.GetMethods().SingleOrDefault(m => m.Name == "SayHello");           
object hello = theMethod.Invoke(instance, null); 
           
Console.WriteLine(hello.ToString());

That way, both the class and method names where represent by strings. When doing that, we always work with object; that’s what the Activator’s CreateInstance method returns, and it’s also what the Invoke method on a MethodInfo instance returns. Using type inference here (declaring the variables with var) wouldn’t help us much.

Another option to create some sort of dynamic code back then was by emitting IL (Intermediate Language). Not exactly a fun thing to do. There are good cases for it, though, so check out some real world users of Reflection.Emit.

Yet another option, which I’ve used at least twice in successful projects, was to build C# code as strings within the application, and handle it over to the C# compiler during runtime. What type of code got created dynamically was controlled within the application, and it was executed within a sandbox, so the end-users couldn’t really “do anything they wanted”. In fact, I have used this approach in conjunction with the dynamic features once they become available.

Coming up next, dynamic code after the C# dynamic features arrived. Stay tuned!

Leave a comment