Dynamic LINQ for Silverlight

Yesterday my colleague asked me if I knew a way to run LINQ queries with externally defined expressions against queryable objects in Silverlight 4.0. What he was after could look like this:

    // Some expression in string format
    var expression = "Price > 10 and Name != \"Fork\"";

    // Iterate target collection and filter with string expression
    foreach (var product in this.Products.AsQueryable().Where(expression))
    {
        // ObservableCollection<Product> that is bound to the UI
        this.FilteredProducts.Add(product);
    }

I remembered that Microsoft’s Dynamic LINQ extension can be used to handle that kind of needs in non-Silverlight applications. The Dynamic LINQ library for C# can be downloaded here and the DynamicQuery can be found at \LinqSamples\DynamicQuery directory. I also remembered that there are some issues that makes using the same implementation a bit challenging in Silverlight. The problem is that Silverlight doesn’t have all the needed classes implemented from System.Threading namespace.

After googling a bit I found this. This solution spared my time since I didn’t need to start moving the ReaderWriterLock and other classes that were needed for the Silverlight. Cheers. So, now we have all the needed code to get Dynamic LINQ to work in Silverlight environment, but how to actually use it? Here is a simple example that should get you going.

I used test entity called Product with some simple properties:

    // Simple demo entity for testing
    public class Product
    {
        public string Name { get; set; }
        public int AmountInStore { get; set; }
        public bool IsAvailable
        {
            get { return this.AmountInStore > 0; }
        }
        public double Price { get; set; }
}

And then I added this to the code behind of the MainPage.xaml.

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Dynamic;
using System.Windows;
using System.Windows.Controls;

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();

        // Create mock data
        this.Products = new List<Product>
          {
            new Product { Name = "Hammer", Price = 20.00d, AmountInStore = 10 },
            new Product { Name = "Knife", Price = 10.00d, AmountInStore = 1 },
            new Product { Name = "Pan", Price = 18.99d, AmountInStore = 100 },
            new Product { Name = "Pen", Price = 1.20d, AmountInStore = 50 },
            new Product { Name = "Bicycle", Price = 299.00d, AmountInStore = 15 },
            new Product { Name = "Fork", Price = 0.50d, AmountInStore = 1000 }
          };

        this.FilteredProducts = new ObservableCollection<Product>(this.Products);
        this.DataContext = this;
    }

    // Demonstrates data collection
    public List<Product> Products { get; private set; }

    // Filtered collection that is bound to the UI
    public ObservableCollection<Product> FilteredProducts { get; set; }

    // Testing how the querying is working.
    private void FilterButtonClick(object sender, RoutedEventArgs e)
    {
        var expression = this.ExpressionField.Text;

        if (string.IsNullOrEmpty(expression))
        {
            this.FilteredProducts.Clear();

            this.Products.ForEach(x => this.FilteredProducts.Add(x));
        }
        else
        {
            this.FilteredProducts.Clear();

            foreach (var product in this.Products.AsQueryable().Where(expression))
            {
                this.FilteredProducts.Add(product);
            }
        }
    }
}

Remember to add System.Linq.Dynamic namespace to get extension rolling.

references:

Posted in LINQ, Silverlight | Tagged , , | 1 Comment

Simple business rule validation engine

The validation of the Business Rules is often the core of the application. In Domain Driven Design focus is in the domain objects and domain logic. This means that application is built robust domain object validation structure.  I created a simple but effective ‘engine’ for the business rule validation. In the N-tier/N-layer architecture Domain or business objects are living in the Business Layer. The Business layer knows how business objects interact with each other. In point of the validation engine, Business layer also enforces the rules and workflows for the business objects. This means that validation engine is used in the Business Layer of the application.

To be more exact, business rules locate in the entities that in most of the cases live in the Business Layer. In point of the WPF or Silverlight applications, these entities can be used in the Presentation Layer if it is appropriate in the case. The Presentation Layer can use the same engine to validate the objects but if they are used in the UI and data binding, the solution needs to be extended. One way to extend this approach is to implement IDataErrorInfo interface in the business objects.  I will probably implement that later on.

Before we start to build the engine we need to clarify what we want to achieve.

Targets:

  • Simple way to attach business rules to the business objects
  • Creating new business rules should be easy
  • Business rules can be reused in other entities and depending on the implementation in other solutions as well.
  • Validation errors include enough information and they can be customized.

Overview of the base classes

I decided to create the abstract base class for the validatable business objects and call it ValidatableObjectBase. The name simply presents that the object implements needed functionality to handle validation logic. Since this is an abstract class the business entities need to be derived from it directly or via some kind of entity base class. The ValidatableObjectBase implements the basic functionality to validate the object, how to attach the business rules to it and how to expose the validation exceptions.

Next to validatable objects we need business rules to attach. For this I created an abstract class called ValidationRuleBase that implements IValidationRule interface. The interface presents a validation rule that can be added to the validatable objects collection of validation rules. The validation rules also contain general and specific error messages so I needed some kind of object to preserve error information.

An ErrorObject is a container class for the error information. It has two error messages. ErrorMessage property contains user friendly error message and more detailed version of the error message can be fetched via GetDetailedErrorMessage method. The ErrorObject class implements IErrorObject interface.

Now we have general view of the engine. Let’s see how to use it.

Attaching the business rules to the entities

I had two ideas how to attach the rules to the entities: by using custom attributes or adding rules explicitly in code. After thinking this through I decided to attach rules explicitly. I started to think that if I add all the rules by attributes, the list of the attributes could start to grow too much and make the code less readable. Also concentrating the rules in one place makes it easy to see all the validation rules at the same time. If rules were attached using attributes, it would be easier to see what rules are attached to certain properties, but getting an overview would be much harder. Anyway, this could be done either way but this time I decided to implement it without attributes.

New business rules can be attached to the business objects by using ValidatableObjectBase’s AddValidationRule method that takes IValidationRule as a parameter.

protected void AddValidationRule(IValidationRule rule)
{
    this.validationRules.Add(rule);
}

I like to add business rules to the entity inside of the entity’s constructors like this

public CustomerEntity()
{
    // Add business rule: The identifier have to be 0 or positive value
    this.AddValidationRule(new IdentityValidationRule("Id"));

    // Add business rule: The customer name have to be longer than 2 letters and no longer
    // than 10
    this.AddValidationRule(new RegexValidationRule("Name", @"^.{3,10}$"));
}

Here we add two business rules to the CustomerEntity. Currently I am using a string to hook properties to the validation rules but I’ll fix that later. First new IdentityValidationRule is added that hooks validation for the Id property of the CustomerEntity. Then new instance of RegexValidationRule is added with regular expression to the Name property. Both IdentityValidationRule and RegexValidationRule are concrete implementation of ValidationRuleBase class.

Validation

The ValidatableObjectBase exposes two methods to handle validation. Validate method runs all the attached validation rules and ValidatePropertyByName method runs all the validation rules that are attached to a certain property. In every validate call, the list of validation errors are cleared and new errors are added to the list. The ValidatableObjectBase exposes those errors via ValidationErrors property that returns a list of IErrorObjects.

ErrorObject implements IErrorObject and can be used in most of the cases. But if more detailed error messages are needed, the ErrorObject can be extended. The ErrorObject has several properties but the most important is ErrorMessage that contains user friendly error message. For logging and debugging error messages, ErrorObject has SetDetailedErrorMessage and GetDetailedErrorMessage methods. SetDetailedErrorMessage method just replaces detailed error message that is returned by the GetDetailedErrorMessage method. If there isn’t any explicitly set detailed error message, ErrorObject creates a new one using other properties of the ErrorObject. The GetDetailedErrorMessage method is virtual so it can be overridden if needed.

Creating new ValidationRules

New business rules can be added to the system by creating a new class that implements IValidationRule interface. The ValidationRuleBase class implements the interface and you can derive new rules directly from it. The base class contains abstract method for the validation that must be overridden in the concrete class.

public abstract bool Validate(ValidatableObjectBase businessObject);

For example, let’s see how Validate method is done in RegexValidationRule.

public override bool Validate(ValidatableObjectBase businessObject)
{
    try
    {
        // Get property from the given business object
        var property = this.GetPropertyValue(businessObject).ToString();

        // If regular expression is empty, throw ArgumentException
        // If expression is null and match is called, it counts as success, but I wanted to cut that out.
        if (string.IsNullOrEmpty(this.expression))
        {
            throw new ArgumentException("Expression value is not set. Currently RegexValidationRule does not support empty validation expression.");
        }

        // Match propertys value to the given expression
        return Regex.Match(property, this.expression).Success;
    }
    catch (Exception exception)
    {
        Debug.WriteLine(exception);
        return false;
    }
}

First the value of the property is read from the given business object and checked that the expression is not empty. The expression is defined in the constructor. After that the check, if the value of the target property matches to the expression, is done. This way new business rules can be created quite easily and focus can be set to the validation logic more than wiring things up.

Full code can be downloaded here.

Posted in Architecture, Design Patterns, ExcitingHours, General | Tagged , , , , | 3 Comments

Moving to new challenges!

Lately there have been a lot of things to handle outside of programming scene so there hasn’t been any posts lately but now it’s going to change (at least I hope so).

I got a new job as a Software Architect at ESRI Finland and I am very happy about it. I’ll start working there at the end of November. My current work at Softability is ending next Friday so I’ll have a couple of weeks off before starting at ESRI.

ESRI Finland in brief (text taken from http://www.esri.fi/en/)

Esri Finland offers market-leading GIS solutions to both public organizations and private companies of any size in Finland. Our mission is to recognize and implement together with our customers the possibilities related to their business activities by utilizing Esri’s GIS solutions and our broad cooperation network. In addition to GIS software we offer extensive professional services including e.g. consultancy, GIS analysis and project services, as well as training, maintenance and support services.

There will be a lot of challenges but I am very eager to start working there. Wish me luck!

Posted in General, Uncategorized | Tagged , , | 1 Comment

How to build enterprise level application with WPF and Silverlight presentation technologies

This idea is now pending. At the moment I am too busy at work to do any coding at free time.

I have been thinking to start a long series about enterprise application development for some time and now got down the concept. I will start to create an application called ExcitingHours. The ExcitingHours is an hour record / billing system software for small companies. The software will not be perfect since it is built to demonstrate architecture and patterns in the enterprise wide software development and the main focus is kept in how to implement the concepts and design.

I will be blogging the development process and posts are mostly written with “Problem – Design – Solution” concept. This means that I will define a problem in the beginning of the post and after that moving to designing the solution for problem. After design is decided, I will show how I actually wrote the solution code in the important parts. This way we can keep the focus in the how to solve issues with patterns and practices. Whole solution code will be downloadable in every post and free to use as it is. If the blog or the code helps you please let me know so I can keep track if my work really helps at all.

What the series is all about?

  • Building Enterprise ready application with multiple Microsoft technologies
  • 3 layered architecture with tiering possibility between presentation and business layers.
  • Multiple presentation applications with one back-end
  • Best practices in 3 layered architecture
  • Design patterns in real enterprise application

Technologies used in the project:

  • Windows Presentation Foundation (WPF)
  • Silverlight (SL)
  • Windows Communication Foundation (WCF)
  • Windows Workflow Foundation (WF)
  • Entity Framework (EF)

ExcitingHours – What it is?

As I said, it is a software to handle billing and hour reporting in the small company. There will be management tool called “ExcitingHours Manager” build with Windows Presentation Foundation 4.0(WPF) for the managers and administrators. The management tool will contain functionality to manage users, projects, hour reports, bills and show some analysis in Business Intelligence (BI) style. The ExcitingHours Manager also contains interface for the report approving workflow that is built over Windows Workflow Foundation 4.0 (WF). In the workflow submitted time entry will go to the manager for approval and it can be returned or approved and so forth.

The ExcitingHours is actually a Silverlight 4.0 application for the users to actually do the hour reporting. If I have time, I might add Windows 7 Phone version of it to the application compilation. Basically the idea is that managers and administrators have a Windows application to manage everything they needed to and for the users there is a web-based application to report the hours. The management application could be built into the ExcitingHours but I think that this concept has it own strong points and with this I can demonstrate multi-presentation – single-back-end style application.

General view to architecture


The ExcitingHours is built over basic 3-layer architecture with single entry point to the backend via Windows Communication Foundation (WCF) services. The Presentation Layer (PL) contains ExcitingHours and ExcitingManager applications that are interface to the users. Business Layer (BL) contains all business logic, validation, workflow engine, workflow rules and so on. The Data Access Layer (DAL) contains data store, that is in this case MS SQL Express server and data objects. I will dig to the general architecture more closely in the next post.

Stay tuned!

Posted in Architecture, Design Patterns, ExcitingHours | Tagged , , , , , , , | 1 Comment

Weak Event Design Pattern and implmenting SettingsStore with Observation

Weak Event Design Pattern is used to fight against memory leaks that occured from having strong relations between event listeners and providers. If we are using typical [source].[event] += [listener delegate] syntax to register listeners to the events, the [source] will keep an internal list of the registered listeners. If the source has a longer lifetime than listener, that can result to memory leaks. Generally you should be ok, if you always remove event handler explicitly.

source.SomeEvent += new SomeEventHandler(MyEventHandler)

We can generalize when to use the Weak Event Design Pattern. The cases are:

  • Source object’s lifetime is longer than the listener’s.
  • Listener does not know when to unregister the events.
  • Assosiation with the source’s and the listener’s lifetimes are not clear.

Using Weak events we can use a listener to register and recieve events without affecting its lifetime in any way. Garbage colletor can dispose the listener event if the listener is listening to the event. You can think that in the SettingsStore demo application the SettingStore object exceeds lifetime of the loaded “modules”. In real highly modular application this would be the case but in the demo, I didn’t built a real envirioment for this. I might build another demo using MEF and modular architecture with layer and module separation.

Implementing the Weak Event Pattern

Implementation is quite straightfoward.

Derive a manager class from the WeakEventManager class.

The WeakEventManager class is an abstract class that one to one realtion with the event that is is associated. This mean, you cannot handle more than one event in one WeakEventManager subclass, but you you can use same subclass with events that has same signature.

Use EventManager post-fix with naming. You might use one to one naming with the event that the manager class is handling. From MSDN you can find a list of notes to the implementors that are handled here. The code is from the demo project.

“Provide a static AddListener method. Sources call AddListener to add a listener for the managed weak event. Your implementation calls the protectedAddListener method to implement this behavior.”

public static void AddListener(SettingsStore source, IWeakEventListener listener)
{
     CurrentManager.ProtectedAddListener(source, listener);
}

“Provide a static RemoveListener method. Sources call RemoveListener to add a listener for the managed event. Your implementation calls the ProtectedRemoveListener method to implement this behavior.”

public static void RemoveListener(SettingsStore source, IWeakEventListener listener)
{
    CurrentManager.ProtectedRemoveListener(source, listener);
}

“Override the StartListening method to cast the source to the type that owns the event, and connect the handler on the source to the event being managed.”

protected override void StartListening(object source)
{
    var store = source as SettingsStore;
    if (store == null)
    {
        return;
    }

     store.SettingsChangedEvent += this.SettingsChangedHandler;
}

“Override the StopListening method to cast the source to the type that owns the event, and disconnect the handler on the source to the event being managed.”

protected override void StopListening(object source)
{
     var store = source as SettingsStore;
     if (store == null)
     {
         return;
     }

     store.SettingsChangedEvent -= this.SettingsChangedHandler;
}

“Implement the handler, which should call the DeliverEvent event, so that the managed event is forwarded to its weak event pattern listeners.”

private void SettingsChangedHandler(object sender, SettingsChangedEventArgs eventArgs)
{
    DeliverEvent(sender, eventArgs);
}

“Provide a CurrentManager property that returns the specific manager type being implemented. The get accessor for CurrentManager should call the GetCurrentManager method to make sure that there is not already an initialized instance. If so, that instance is returned properly typed. If there is no initialized instance, the get accessor should call the SetCurrentManager method to initialize one.”

private static SettingsChangedEventManager CurrentManager
{
    get
    {
        var manager = (SettingsChangedEventManager)GetCurrentManager(typeof(SettingsChangedEventManager));
        if (manager == null)
        {
            manager = new SettingsChangedEventManager();
            SetCurrentManager(typeof(SettingsChangedEventManager), manager);
        }

         return manager;
    }
}

Implement the IWeakEventListener interface to class that registers weak event

The interface contains only one method – ReceiveWeakEvent method. The method is called when the event is raised from the EventManager implementation.

In the demo SettingsObserver handles the method like this. The class has internal list of delegates that are invoked when correct event is raised.

public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs eventArgs)
{
    if (managerType != typeof(SettingsChangedEventManager))
    {
        return false;
     }

      var settingName = ((SettingsChangedEventArgs)eventArgs).SettingName;

      if (String.IsNullOrEmpty(settingName))
      {
           // If empty is returned, raise all registered observations.
           foreach (var items in this.settingNameToHandlerMap)
           {
               var handler = items.Value;

               // Could use sender as SettingsStore here.
               handler(this.sourceStore.GetSetting(this.sourceStore.GetSetting(items.Key)));
           }
       }
       else
       {
           // Invokes first action found registered with the settings name.
           Action handler;
           if (this.settingNameToHandlerMap.TryGetValue(settingName, out handler))
           {
               handler(this.sourceStore.GetSetting(settingName));
           }
        }

        return true;
}

The Demo / example application

I created a quite simple application to demostrate the pattern. I was also creating the first version of centralized settings store for modular applications. The implementation is not perfect and SettingsStore could be improved quite a lot, like by making it strongly typed. The application contains tree separate “Modules”: Module1, Module2 and SettingsEditor. SettingsEditor is a centralized place to make changes to the settings store. When the change is done, SettingsStore raises event that is delivered to the modules by SettingsObserver class that implements IWeakEventListener interface. You can download the code from here.

Here is overview to the project:
View to the SolutionExplorer

References:

Posted in Architecture, Design Patterns, WPF | Tagged , , , | 1 Comment